예제 #1
0
  public T receive() {
    lock.lock();
    try {
      while (true) {
        DelayedMessage message = queue.peek();
        if (message == null && stopping) {
          return null;
        }
        if (message == null) {
          condition.await();
          continue;
        }

        long now = timeProvider.getCurrentTime();
        if (message.dispatchTime > now) {
          condition.awaitUntil(new Date(message.dispatchTime));
        } else {
          queue.poll();
          if (queue.isEmpty()) {
            condition.signalAll();
          }
          return message.message;
        }
      }
    } catch (InterruptedException e) {
      throw UncheckedException.throwAsUncheckedException(e);
    } finally {
      lock.unlock();
    }
  }
 private boolean awaitStop(long timeoutMs) {
   lock.lock();
   try {
     LOGGER.debug("waiting for daemon to stop or be idle for {}ms", timeoutMs);
     while (true) {
       try {
         switch (state) {
           case Running:
             if (isBusy()) {
               LOGGER.debug(DaemonMessages.DAEMON_BUSY);
               condition.await();
             } else if (hasBeenIdleFor(timeoutMs)) {
               LOGGER.debug("Daemon has been idle for requested period.");
               stop();
               return false;
             } else {
               Date waitUntil = new Date(lastActivityAt + timeoutMs);
               LOGGER.debug(DaemonMessages.DAEMON_IDLE + waitUntil);
               condition.awaitUntil(waitUntil);
             }
             break;
           case Broken:
             throw new IllegalStateException("This daemon is in a broken state.");
           case StopRequested:
             LOGGER.debug("Daemon is stopping, sleeping until state changes.");
             condition.await();
             break;
           case Stopped:
             LOGGER.debug("Daemon has stopped.");
             return true;
         }
       } catch (InterruptedException e) {
         throw UncheckedException.throwAsUncheckedException(e);
       }
     }
   } finally {
     lock.unlock();
   }
 }