@Scheduled(fixedRate = 30000)
 public void addTick() {
   // Only add ticks if staterunner handled all previous ones
   if (!eventQueue.contains(TournamentEvent.TICK)) {
     putEvent(TournamentEvent.TICK);
   }
 }
Beispiel #2
0
 /**
  * Returns <code>true</code> if a given job is waiting or running; <code>false</code> if the job
  * is finished or doesn't exist in the queue.
  *
  * <p>Only used by PluginStarter, candidate for deprecation
  */
 public boolean isJobActive(Job job) {
   synchronized (_jobLock) {
     if (_readyJobs.contains(job) || _timedJobs.contains(job)) return true;
   }
   for (JobQueueRunner runner : _queueRunners.values())
     if (runner.getCurrentJob() == job) return true;
   return false;
 }
 /**
  * 添加Url进入BlockingQueue
  *
  * @param url
  */
 private void putUrlToQueue(String url) {
   // 不存在在添加新任务
   if (!urlQueue.contains(url)) {
     try {
       urlQueue.put(url);
     } catch (InterruptedException e) {
       e.printStackTrace();
     }
   }
 }
Beispiel #4
0
  /**
   * Asks a question for a given employee
   *
   * @param employee the Employee to assist
   */
  public void askQuestion(Employee employee) {
    // Add question to queue
    long startCheck = System.currentTimeMillis();

    synchronized (hasQuestion) {
      hasQuestion.add(employee);
    }

    // Waiting until question can be answered
    while (hasQuestion.contains(employee)) {
      // Is it time for the 4 o'clock meeting?
      try {
        if (office.getTime() >= 1600 && !employee.isAttendedEndOfDayMeeting()) {
          office.waitForEndOfDayMeeting();
          System.out.println(
              office.getStringTime()
                  + " Developer "
                  + employee.getEmployeeName()
                  + " attends end of day meeting");
          sleep(150);
          employee.setAttendedEndOfDayMeeting(true);
        }
        synchronized (questionLock) {
          // Tell the Manager there is a question.
          office.notifyWorking();
          questionLock.wait();
        }
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }

    synchronized (questionLock) {
      // Question is being answered
      while (employee.isWaitingQuestion()) {
        try {
          questionLock.wait();
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    }

    long endCheck = System.currentTimeMillis();

    employee.addToWaitingQuestion((endCheck - startCheck) / 10);

    System.out.println(
        office.getStringTime()
            + " Developer "
            + employee.getEmployeeName()
            + "'s question is answered");
  }
Beispiel #5
0
  /** Enqueue the specified job */
  public void addJob(Job job) {
    if (job == null || !_alive) return;

    // This does nothing
    // if (job instanceof JobImpl)
    //    ((JobImpl)job).addedToQueue();

    long numReady = 0;
    boolean alreadyExists = false;
    boolean dropped = false;
    // getNext() is now outside the jobLock, is that ok?
    synchronized (_jobLock) {
      if (_readyJobs.contains(job)) alreadyExists = true;
      numReady = _readyJobs.size();
      if (!alreadyExists) {
        // if (_timedJobs.contains(job))
        //    alreadyExists = true;
        // Always remove and re-add, since it needs to be
        // re-sorted in the TreeSet.
        boolean removed = _timedJobs.remove(job);
        if (removed && _log.shouldLog(Log.WARN)) _log.warn("Rescheduling job: " + job);
      }

      if ((!alreadyExists) && shouldDrop(job, numReady)) {
        job.dropped();
        dropped = true;
      } else {
        if (!alreadyExists) {
          if (job.getTiming().getStartAfter() <= _context.clock().now()) {
            // don't skew us - its 'start after' its been queued, or later
            job.getTiming().setStartAfter(_context.clock().now());
            if (job instanceof JobImpl) ((JobImpl) job).madeReady();
            _readyJobs.offer(job);
          } else {
            _timedJobs.add(job);
            // only notify for _timedJobs, as _readyJobs does not use that lock
            // only notify if sooner, to reduce contention
            if (job.getTiming().getStartAfter() < _nextPumperRun) _jobLock.notifyAll();
          }
        }
      }
    }

    _context.statManager().addRateData("jobQueue.readyJobs", numReady, 0);
    if (dropped) {
      _context.statManager().addRateData("jobQueue.droppedJobs", 1, 0);
      _log.logAlways(
          Log.WARN, "Dropping job due to overload!  # ready jobs: " + numReady + ": job = " + job);
    }
  }
  @Override
  public boolean publish(final EventInformation event)
      throws RemoteException, InterruptedException {

    boolean result = false;
    getLock().readLock().lock();
    synchronized (queue) {
      if (!queue.contains(event) && !processingEvents.containsKey(event)) {
        result = true;
        queue.add(event);
      }
    }

    getLock().readLock().unlock();
    return result;
  }
  @Test
  public void testAddMessageToLogBuffer() throws InterruptedException {
    BlockingQueue<Reaction> sharedQueue = new LinkedBlockingQueue<Reaction>();
    BlockingQueue<String> logSharedQueue = new LinkedBlockingQueue<String>();

    DBWriter dbw = new DBWriter(sharedQueue, logSharedQueue);
    Reaction singleReaction = new Reaction();

    assertFalse(sharedQueue.contains(singleReaction));

    singleReaction.put("UNIQUE-ID", "RXN-1748");
    singleReaction.put("TYPES", "NORMAL");

    dbw.addMessageToLogBuffer(singleReaction);
    assertTrue(logSharedQueue.peek().contains("---- collected UNIQUE ID RXN-1748 from buffer"));
  }
Beispiel #8
0
 /**
  * Send command to socket server.
  *
  * @param command Command need to send
  */
 public void sendCommand(String command) {
   Xlog.v(TAG, "enter sendCommand");
   String sendComm = "$" + command + "*" + calcCS(command);
   Xlog.v(TAG, "Send command: " + sendComm);
   if (!mSendThread.isAlive()) {
     Xlog.v(TAG, "sendThread is not alive");
     mSendThread.start();
   }
   if (command.equals(sendComm) || mCommandQueue.contains(sendComm)) {
     Xlog.v(TAG, "send command return because of hasn't handle the same");
     return;
   }
   try {
     mCommandQueue.put(sendComm);
   } catch (InterruptedException ie) {
     Xlog.w(TAG, "send command interrupted:" + ie.getMessage());
   }
 }
Beispiel #9
0
  /**
   * Add a request to the stack of requests to execute in the update thread.
   *
   * @param uiRequest The request to execute in the update thread.
   */
  public void request(Request uiRequest) {

    UpdateRequest newRequest =
        new UpdateRequest(
            uiRequest,
            new RuntimeException(
                Locale.explain("err.originates")
                    + Thread.currentThread().getName())); // $NON-NLS-1$

    /* Don't process a request if the next pending or currently executing request is the same. */
    if (newRequest.equals(currentRequest) || requests.contains(newRequest)) return;

    /* Add this request to the request list. */
    synchronized (requests) {
      try {
        if (!requests.offer(newRequest, 500, TimeUnit.MILLISECONDS))
          throw new InterruptedException("Maximum wait time elapsed.");
      } catch (InterruptedException e) {
        logger.err(e, "err.updateQueueFull", newRequest);
      }
    }
  }
Beispiel #10
0
 @Override
 public boolean contains(Object o) {
   return delegate.contains(o);
 }
  @Override
  public boolean contains(Object o) {

    return localInternalQueue.contains(o);
  }
Beispiel #12
0
 /**
  * Checks if the lead is asking a question
  *
  * @param lead the Team Leader
  * @return if the question queue has the given leader in it
  */
 public boolean isLeadAsking(Employee lead) {
   return hasQuestion.contains(lead);
 }
  /**
   * Process all elements from the {@code failedToProcess} and then {@code things} concurrently in
   * the underlying pool. Processing happens concurrently maintaining {@code
   * JobSchedulerImpl.CORES_COUNT} parallelism. Stop when {@code tombStone} element is occurred. If
   * was unable to process some element, add it back to the {@code failedToProcess} queue.
   *
   * @return true if all elements processed successfully, false if at least one processor returned
   *     false or exception occurred
   */
  public <T> boolean processQueue(
      @NotNull final BlockingQueue<T> things,
      @NotNull final Queue<T> failedToProcess,
      @NotNull final ProgressIndicator progress,
      @NotNull final T tombStone,
      @NotNull final Processor<? super T> thingProcessor) {
    class MyTask implements Callable<Boolean> {
      private final int mySeq;
      private boolean result;

      private MyTask(int seq) {
        mySeq = seq;
      }

      @Override
      public Boolean call() throws Exception {
        ProgressManager.getInstance()
            .executeProcessUnderProgress(
                () -> {
                  try {
                    while (true) {
                      progress.checkCanceled();
                      T element = failedToProcess.poll();
                      if (element == null) element = things.take();

                      if (element == tombStone) {
                        things.offer(element);
                        result = true;
                        break;
                      }
                      try {
                        if (!thingProcessor.process(element)) {
                          result = false;
                          break;
                        }
                      } catch (RuntimeException e) {
                        failedToProcess.add(element);
                        throw e;
                      }
                    }
                  } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                  }
                },
                progress);
        return result;
      }

      @Override
      public String toString() {
        return super.toString() + " seq=" + mySeq;
      }
    }

    boolean isSmallEnough = things.contains(tombStone);
    if (isSmallEnough) {
      try {
        // do not distribute for small queues
        return new MyTask(0).call();
      } catch (RuntimeException e) {
        throw e;
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    }

    List<ForkJoinTask<Boolean>> tasks = new ArrayList<>();
    for (int i = 0; i < JobSchedulerImpl.CORES_COUNT; i++) {
      tasks.add(pool.submit(new MyTask(i)));
    }

    boolean result = true;
    RuntimeException exception = null;
    for (ForkJoinTask<Boolean> task : tasks) {
      try {
        result &= task.join();
      } catch (RuntimeException e) {
        exception = e;
      }
    }
    if (exception != null) {
      throw exception;
    }
    return result;
  }