Beispiel #1
0
 /** poll succeeds unless empty */
 public void testPoll() {
   DelayQueue q = populatedQueue(SIZE);
   for (int i = 0; i < SIZE; ++i) {
     assertEquals(new PDelay(i), q.poll());
   }
   assertNull(q.poll());
 }
Beispiel #2
0
 /** timed poll with zero timeout succeeds when non-empty, else times out */
 public void testTimedPoll0() throws InterruptedException {
   DelayQueue q = populatedQueue(SIZE);
   for (int i = 0; i < SIZE; ++i) {
     assertEquals(new PDelay(i), q.poll(0, MILLISECONDS));
   }
   assertNull(q.poll(0, MILLISECONDS));
 }
Beispiel #3
0
 /** add succeeds */
 public void testAdd() {
   DelayQueue q = new DelayQueue();
   for (int i = 0; i < SIZE; ++i) {
     assertEquals(i, q.size());
     assertTrue(q.add(new PDelay(i)));
   }
 }
Beispiel #4
0
 /** @see java.lang.Thread#run() */
 @Override
 public void run() {
   while (!stopRequested || (stopRequested && leaseQueue.size() > 0)) {
     Lease lease = null;
     try {
       lease = leaseQueue.poll(leaseCheckFrequency, TimeUnit.MILLISECONDS);
     } catch (InterruptedException e) {
       continue;
     } catch (ConcurrentModificationException e) {
       continue;
     } catch (Throwable e) {
       LOG.fatal("Unexpected exception killed leases thread", e);
       break;
     }
     if (lease == null) {
       continue;
     }
     // A lease expired.  Run the expired code before removing from queue
     // since its presence in queue is used to see if lease exists still.
     if (lease.getListener() == null) {
       LOG.error("lease listener is null for lease " + lease.getLeaseName());
     } else {
       lease.getListener().leaseExpired();
     }
     synchronized (leaseQueue) {
       leases.remove(lease.getLeaseName());
     }
   }
   close();
 }
Beispiel #5
0
 /** toArray(incompatible array type) throws ArrayStoreException */
 public void testToArray1_BadArg() {
   DelayQueue q = populatedQueue(SIZE);
   try {
     q.toArray(new String[10]);
     shouldThrow();
   } catch (ArrayStoreException success) {
   }
 }
Beispiel #6
0
 /** addAll(this) throws IAE */
 public void testAddAllSelf() {
   DelayQueue q = populatedQueue(SIZE);
   try {
     q.addAll(q);
     shouldThrow();
   } catch (IllegalArgumentException success) {
   }
 }
Beispiel #7
0
 /** contains(x) reports true when elements added but not yet removed */
 public void testContains() {
   DelayQueue q = populatedQueue(SIZE);
   for (int i = 0; i < SIZE; ++i) {
     assertTrue(q.contains(new PDelay(i)));
     q.poll();
     assertFalse(q.contains(new PDelay(i)));
   }
 }
Beispiel #8
0
 /** toArray(a) contains all elements */
 public void testToArray2() {
   DelayQueue<PDelay> q = populatedQueue(SIZE);
   PDelay[] ints = new PDelay[SIZE];
   PDelay[] array = q.toArray(ints);
   assertSame(ints, array);
   Arrays.sort(ints);
   for (int i = 0; i < ints.length; i++) assertSame(ints[i], q.remove());
 }
Beispiel #9
0
 /** all elements successfully put are contained */
 public void testPut() {
   DelayQueue q = new DelayQueue();
   for (int i = 0; i < SIZE; ++i) {
     PDelay x = new PDelay(i);
     q.put(x);
     assertTrue(q.contains(x));
   }
   assertEquals(SIZE, q.size());
 }
Beispiel #10
0
 /** Queue contains all elements of successful addAll */
 public void testAddAll5() {
   PDelay[] empty = new PDelay[0];
   PDelay[] ints = new PDelay[SIZE];
   for (int i = SIZE - 1; i >= 0; --i) ints[i] = new PDelay(i);
   DelayQueue q = new DelayQueue();
   assertFalse(q.addAll(Arrays.asList(empty)));
   assertTrue(q.addAll(Arrays.asList(ints)));
   for (int i = 0; i < SIZE; ++i) assertEquals(ints[i], q.poll());
 }
Beispiel #11
0
 /**
  * addAll of a collection with any null elements throws NPE after possibly adding some elements
  */
 public void testAddAll3() {
   DelayQueue q = new DelayQueue();
   PDelay[] a = new PDelay[SIZE];
   for (int i = 0; i < SIZE - 1; ++i) a[i] = new PDelay(i);
   try {
     q.addAll(Arrays.asList(a));
     shouldThrow();
   } catch (NullPointerException success) {
   }
 }
Beispiel #12
0
 public static void main(String[] args) {
   Random r = new Random();
   DelayQueue<Student> students = new DelayQueue<Student>();
   ExecutorService exec = Executors.newCachedThreadPool();
   for (int i = 0; i < STUDENT_SIZE; i++) {
     students.put(new Student("学生" + (i + 1), 3000 + r.nextInt(9000)));
   }
   students.put(new Student.EndExam(12000, exec)); // 1200为考试结束时间
   exec.execute(new Teacher(students, exec));
 }
Beispiel #13
0
 /** drainTo(c, n) empties first min(n, size) elements of queue into c */
 public void testDrainToN() {
   for (int i = 0; i < SIZE + 2; ++i) {
     DelayQueue q = populatedQueue(SIZE);
     ArrayList l = new ArrayList();
     q.drainTo(l, i);
     int k = (i < SIZE) ? i : SIZE;
     assertEquals(SIZE - k, q.size());
     assertEquals(k, l.size());
   }
 }
Beispiel #14
0
 /**
  * Shut down this Leases instance. All pending leases will be destroyed, without any cancellation
  * calls.
  */
 public void close() {
   LOG.info(Thread.currentThread().getName() + " closing leases");
   this.stopRequested = true;
   synchronized (leaseQueue) {
     leaseQueue.clear();
     leases.clear();
     leaseQueue.notifyAll();
   }
   LOG.info(Thread.currentThread().getName() + " closed leases");
 }
Beispiel #15
0
 public static void main(String[] args) {
   Random rand = new Random(47);
   ExecutorService exec = Executors.newCachedThreadPool();
   DelayQueue<DelayedTask> queue = new DelayQueue<DelayedTask>();
   // Fill with tasks that have random delays:
   for (int i = 0; i < 20; i++) queue.put(new DelayedTask(rand.nextInt(5000)));
   // Set the stopping point
   queue.add(new DelayedTask.EndSentinel(5000, exec));
   exec.execute(new DelayedTaskConsumer(queue));
 }
Beispiel #16
0
 /** remove removes next element, or throws NSEE if empty */
 public void testRemove() {
   DelayQueue q = populatedQueue(SIZE);
   for (int i = 0; i < SIZE; ++i) {
     assertEquals(new PDelay(i), q.remove());
   }
   try {
     q.remove();
     shouldThrow();
   } catch (NoSuchElementException success) {
   }
 }
 public void recovery(AlarmRule alarmRule) {
   Pipeline pipeline = pipelineService.findById(alarmRule.getPipelineId());
   AlarmRecoveryDelayed delayed =
       new AlarmRecoveryDelayed(pipeline.getChannelId(), alarmRule.getId(), false, checkTime);
   // 做异步处理,避免并发时重复执行recovery
   synchronized (queue) {
     if (!queue.contains(delayed)) {
       queue.add(delayed);
     }
   }
 }
Beispiel #18
0
 /** iterator iterates through all elements */
 public void testIterator() {
   DelayQueue q = populatedQueue(SIZE);
   int i = 0;
   Iterator it = q.iterator();
   while (it.hasNext()) {
     assertTrue(q.contains(it.next()));
     ++i;
   }
   assertEquals(i, SIZE);
   assertIteratorExhausted(it);
 }
Beispiel #19
0
 /** timed poll with nonzero timeout succeeds when non-empty, else times out */
 public void testTimedPoll() throws InterruptedException {
   DelayQueue q = populatedQueue(SIZE);
   for (int i = 0; i < SIZE; ++i) {
     long startTime = System.nanoTime();
     assertEquals(new PDelay(i), q.poll(LONG_DELAY_MS, MILLISECONDS));
     assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
   }
   long startTime = System.nanoTime();
   assertNull(q.poll(timeoutMillis(), MILLISECONDS));
   assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
   checkEmpty(q);
 }
Beispiel #20
0
 /**
  * Renew a lease
  *
  * @param leaseName name of lease
  * @throws org.apache.hadoop.hbase.exceptions.LeaseException
  */
 public void renewLease(final String leaseName) throws LeaseException {
   synchronized (leaseQueue) {
     Lease lease = leases.get(leaseName);
     // We need to check to see if the remove is successful as the poll in the run()
     // method could have completed between the get and the remove which will result
     // in a corrupt leaseQueue.
     if (lease == null || !leaseQueue.remove(lease)) {
       throw new LeaseException("lease '" + leaseName + "' does not exist or has already expired");
     }
     lease.resetExpirationTime();
     leaseQueue.add(lease);
   }
 }
Beispiel #21
0
 /** clear removes all elements */
 public void testClear() {
   DelayQueue q = populatedQueue(SIZE);
   q.clear();
   assertTrue(q.isEmpty());
   assertEquals(0, q.size());
   assertEquals(Integer.MAX_VALUE, q.remainingCapacity());
   PDelay x = new PDelay(1);
   q.add(x);
   assertFalse(q.isEmpty());
   assertTrue(q.contains(x));
   q.clear();
   assertTrue(q.isEmpty());
 }
Beispiel #22
0
 /** iterator.remove removes current element */
 public void testIteratorRemove() {
   final DelayQueue q = new DelayQueue();
   q.add(new PDelay(2));
   q.add(new PDelay(1));
   q.add(new PDelay(3));
   Iterator it = q.iterator();
   it.next();
   it.remove();
   it = q.iterator();
   assertEquals(new PDelay(2), it.next());
   assertEquals(new PDelay(3), it.next());
   assertFalse(it.hasNext());
 }
Beispiel #23
0
  /** Delayed actions do not occur until their delay elapses */
  public void testDelay() throws InterruptedException {
    DelayQueue<NanoDelay> q = new DelayQueue<NanoDelay>();
    for (int i = 0; i < SIZE; ++i) q.add(new NanoDelay(1000000L * (SIZE - i)));

    long last = 0;
    for (int i = 0; i < SIZE; ++i) {
      NanoDelay e = q.take();
      long tt = e.getTriggerTime();
      assertTrue(System.nanoTime() - tt >= 0);
      if (i != 0) assertTrue(tt >= last);
      last = tt;
    }
    assertTrue(q.isEmpty());
  }
 public DelayedReply messageArrived(CellMessage envelope, PoolMgrGetUpdatedHandler message) {
   SerializablePoolManagerHandler handler = this.handler;
   UpdateRequest request = new UpdateRequest(envelope, message);
   requests.add(request);
   if (message.getVersion().equals(handler.getVersion())) {
     delays.put(request);
     UpdateRequest expired;
     while ((expired = delays.poll()) != null) {
       requests.remove(expired);
     }
   } else if (requests.remove(request)) {
     request.send(handler);
   }
   return request;
 }
Beispiel #25
0
  public static void main(String[] args) throws InterruptedException {
    DelayQueue queue = new DelayQueue();

    DelayedObj element1 = new DelayedObj("1", 100);
    DelayedObj element2 = new DelayedObj("0", 1000);

    queue.put(element1);
    queue.put(element2);

    DelayedObj relement1 = (DelayedObj) queue.take();
    DelayedObj relement2 = (DelayedObj) queue.take();

    System.out.println(relement1.getLevel());
    System.out.println(relement2.getLevel());
  }
Beispiel #26
0
  /** @param args */
  public static void main(String[] args) throws Exception {

    /*
     * Delayed queue to store the events
     */
    DelayQueue<Event> queue = new DelayQueue<>();

    /*
     * An array to store the Thread objects that execute the tasks
     */
    Thread threads[] = new Thread[5];

    /*
     * Create the five tasks
     */
    for (int i = 0; i < threads.length; i++) {
      Task task = new Task(i + 1, queue);
      threads[i] = new Thread(task);
    }

    /*
     * Execute the five tasks
     */
    for (int i = 0; i < threads.length; i++) {
      threads[i].start();
    }

    /*
     * Wait for the finalization of the five tasks
     */
    for (int i = 0; i < threads.length; i++) {
      threads[i].join();
    }

    /*
     * Write the results to the console
     */
    do {
      int counter = 0;
      Event event;
      do {
        event = queue.poll();
        if (event != null) counter++;
      } while (event != null);
      System.out.printf("At %s you have read %d events\n", new Date(), counter);
      TimeUnit.MILLISECONDS.sleep(500);
    } while (queue.size() > 0);
  }
 public void recovery(AlarmRule alarmRule, long alarmCount) {
   if (alarmCount >= alarmRule.getRecoveryThresold()) {
     synchronized (queue) {
       // 做异步处理,避免并发时重复执行recovery
       Pipeline pipeline = pipelineService.findById(alarmRule.getPipelineId());
       // 超过2倍阀值,强制停止一下通道释放一下内存
       boolean needStop = (alarmCount >= alarmRule.getRecoveryThresold() + 1); // recovery的下一次启用修复
       AlarmRecoveryDelayed delayed =
           new AlarmRecoveryDelayed(
               pipeline.getChannelId(), alarmRule.getId(), needStop, checkTime);
       if (!queue.contains(delayed)) {
         queue.add(delayed);
       }
     }
   }
 }
 /** Stop processing the tasks */
 public synchronized void stop() {
   log.info("Stopping task manager. Task count " + taskHolderDelayQueue.size());
   for (TaskProcessor taskProcessor : taskProcessorQueue) {
     taskProcessor.deactivate();
   }
   taskProcessorQueue.clear();
 }
Beispiel #29
0
  /** put doesn't block waiting for take */
  public void testPutWithTake() throws InterruptedException {
    final DelayQueue q = new DelayQueue();
    Thread t =
        newStartedThread(
            new CheckedRunnable() {
              public void realRun() {
                q.put(new PDelay(0));
                q.put(new PDelay(0));
                q.put(new PDelay(0));
                q.put(new PDelay(0));
              }
            });

    awaitTermination(t);
    assertEquals(4, q.size());
  }
 public void shutdown() {
   if (null != executorService) {
     executorService.shutdown();
   }
   if (null != taskQueue) {
     taskQueue.clear();
   }
 }