ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/DelayQueueTest.java
(Generate patch)

Comparing jsr166/src/test/tck/DelayQueueTest.java (file contents):
Revision 1.24 by jsr166, Sat Nov 21 22:00:46 2009 UTC vs.
Revision 1.50 by jsr166, Fri May 27 20:07:24 2011 UTC

# Line 1 | Line 1
1   /*
2   * Written by Doug Lea with assistance from members of JCP JSR-166
3   * Expert Group and released to the public domain, as explained at
4 < * http://creativecommons.org/licenses/publicdomain
4 > * http://creativecommons.org/publicdomain/zero/1.0/
5   * Other contributors include Andrew Wright, Jeffrey Hayes,
6   * Pat Fisher, Mike Judd.
7   */
# Line 13 | Line 13 | import java.util.concurrent.*;
13  
14   public class DelayQueueTest extends JSR166TestCase {
15      public static void main(String[] args) {
16 <        junit.textui.TestRunner.run (suite());
16 >        junit.textui.TestRunner.run(suite());
17      }
18  
19      public static Test suite() {
# Line 24 | Line 24 | public class DelayQueueTest extends JSR1
24  
25      /**
26       * A delayed implementation for testing.
27 <     * Most  tests use Pseudodelays, where delays are all elapsed
27 >     * Most tests use Pseudodelays, where delays are all elapsed
28       * (so, no blocking solely for delays) but are still ordered
29       */
30      static class PDelay implements Delayed {
# Line 32 | Line 32 | public class DelayQueueTest extends JSR1
32          PDelay(int i) { pseudodelay = Integer.MIN_VALUE + i; }
33          public int compareTo(PDelay y) {
34              int i = pseudodelay;
35 <            int j = ((PDelay)y).pseudodelay;
35 >            int j = y.pseudodelay;
36              if (i < j) return -1;
37              if (i > j) return 1;
38              return 0;
39          }
40  
41          public int compareTo(Delayed y) {
42 <            int i = pseudodelay;
43 <            int j = ((PDelay)y).pseudodelay;
44 <            if (i < j) return -1;
45 <            if (i > j) return 1;
46 <            return 0;
42 >            return compareTo((PDelay)y);
43          }
44  
45          public boolean equals(Object other) {
46 <            return ((PDelay)other).pseudodelay == pseudodelay;
46 >            return equals((PDelay)other);
47          }
48          public boolean equals(PDelay other) {
49 <            return ((PDelay)other).pseudodelay == pseudodelay;
49 >            return other.pseudodelay == pseudodelay;
50          }
51  
56
52          public long getDelay(TimeUnit ignore) {
53              return pseudodelay;
54          }
# Line 66 | Line 61 | public class DelayQueueTest extends JSR1
61          }
62      }
63  
69
64      /**
65       * Delayed implementation that actually delays
66       */
# Line 77 | Line 71 | public class DelayQueueTest extends JSR1
71          }
72          public int compareTo(NanoDelay y) {
73              long i = trigger;
74 <            long j = ((NanoDelay)y).trigger;
74 >            long j = y.trigger;
75              if (i < j) return -1;
76              if (i > j) return 1;
77              return 0;
78          }
79  
80          public int compareTo(Delayed y) {
81 <            long i = trigger;
88 <            long j = ((NanoDelay)y).trigger;
89 <            if (i < j) return -1;
90 <            if (i > j) return 1;
91 <            return 0;
81 >            return compareTo((NanoDelay)y);
82          }
83  
84          public boolean equals(Object other) {
85 <            return ((NanoDelay)other).trigger == trigger;
85 >            return equals((NanoDelay)other);
86          }
87          public boolean equals(NanoDelay other) {
88 <            return ((NanoDelay)other).trigger == trigger;
88 >            return other.trigger == trigger;
89          }
90  
91          public long getDelay(TimeUnit unit) {
# Line 112 | Line 102 | public class DelayQueueTest extends JSR1
102          }
103      }
104  
115
105      /**
106       * Create a queue of given size containing consecutive
107       * PDelays 0 ... n.
108       */
109 <    private DelayQueue populatedQueue(int n) {
110 <        DelayQueue q = new DelayQueue();
109 >    private DelayQueue<PDelay> populatedQueue(int n) {
110 >        DelayQueue<PDelay> q = new DelayQueue<PDelay>();
111          assertTrue(q.isEmpty());
112          for (int i = n-1; i >= 0; i-=2)
113              assertTrue(q.offer(new PDelay(i)));
# Line 199 | Line 188 | public class DelayQueueTest extends JSR1
188      }
189  
190      /**
191 <     * remainingCapacity does not change when elementa added or removed,
191 >     * remainingCapacity does not change when elements added or removed,
192       * but size does
193       */
194      public void testRemainingCapacity() {
# Line 269 | Line 258 | public class DelayQueueTest extends JSR1
258          } catch (NullPointerException success) {}
259      }
260  
272
261      /**
262       * addAll(this) throws IAE
263       */
# Line 292 | Line 280 | public class DelayQueueTest extends JSR1
280              shouldThrow();
281          } catch (NullPointerException success) {}
282      }
283 +
284      /**
285       * addAll of a collection with any null elements throws NPE after
286       * possibly adding some elements
# Line 325 | Line 314 | public class DelayQueueTest extends JSR1
314      /**
315       * put(null) throws NPE
316       */
317 <     public void testPutNull() {
317 >    public void testPutNull() {
318          try {
319              DelayQueue q = new DelayQueue();
320              q.put(null);
321              shouldThrow();
322          } catch (NullPointerException success) {}
323 <     }
323 >    }
324  
325      /**
326       * all elements successfully put are contained
327       */
328 <     public void testPut() {
329 <         DelayQueue q = new DelayQueue();
330 <         for (int i = 0; i < SIZE; ++i) {
331 <             PDelay I = new PDelay(i);
332 <             q.put(I);
333 <             assertTrue(q.contains(I));
334 <         }
335 <         assertEquals(SIZE, q.size());
328 >    public void testPut() {
329 >        DelayQueue q = new DelayQueue();
330 >        for (int i = 0; i < SIZE; ++i) {
331 >            PDelay I = new PDelay(i);
332 >            q.put(I);
333 >            assertTrue(q.contains(I));
334 >        }
335 >        assertEquals(SIZE, q.size());
336      }
337  
338      /**
# Line 351 | Line 340 | public class DelayQueueTest extends JSR1
340       */
341      public void testPutWithTake() throws InterruptedException {
342          final DelayQueue q = new DelayQueue();
343 <        Thread t = new Thread(new CheckedRunnable() {
343 >        Thread t = newStartedThread(new CheckedRunnable() {
344              public void realRun() {
345                  q.put(new PDelay(0));
346                  q.put(new PDelay(0));
# Line 359 | Line 348 | public class DelayQueueTest extends JSR1
348                  q.put(new PDelay(0));
349              }});
350  
351 <        t.start();
352 <        Thread.sleep(SHORT_DELAY_MS);
364 <        q.take();
365 <        t.interrupt();
366 <        t.join();
351 >        awaitTermination(t);
352 >        assertEquals(4, q.size());
353      }
354  
355      /**
# Line 371 | Line 357 | public class DelayQueueTest extends JSR1
357       */
358      public void testTimedOffer() throws InterruptedException {
359          final DelayQueue q = new DelayQueue();
360 <        Thread t = new Thread(new CheckedRunnable() {
360 >        Thread t = newStartedThread(new CheckedRunnable() {
361              public void realRun() throws InterruptedException {
362                  q.put(new PDelay(0));
363                  q.put(new PDelay(0));
# Line 379 | Line 365 | public class DelayQueueTest extends JSR1
365                  assertTrue(q.offer(new PDelay(0), LONG_DELAY_MS, MILLISECONDS));
366              }});
367  
368 <        t.start();
383 <        Thread.sleep(SMALL_DELAY_MS);
384 <        t.interrupt();
385 <        t.join();
368 >        awaitTermination(t);
369      }
370  
371      /**
# Line 398 | Line 381 | public class DelayQueueTest extends JSR1
381      /**
382       * take blocks interruptibly when empty
383       */
384 <    public void testTakeFromEmpty() throws InterruptedException {
385 <        final DelayQueue q = new DelayQueue();
386 <        Thread t = new ThreadShouldThrow(InterruptedException.class) {
387 <            public void realRun() throws InterruptedException {
388 <                q.take();
389 <            }};
384 >    public void testTakeFromEmptyBlocksInterruptibly()
385 >            throws InterruptedException {
386 >        final BlockingQueue q = new DelayQueue();
387 >        final CountDownLatch threadStarted = new CountDownLatch(1);
388 >        Thread t = newStartedThread(new CheckedRunnable() {
389 >            public void realRun() {
390 >                threadStarted.countDown();
391 >                try {
392 >                    q.take();
393 >                    shouldThrow();
394 >                } catch (InterruptedException success) {}
395 >                assertFalse(Thread.interrupted());
396 >            }});
397  
398 <        t.start();
399 <        Thread.sleep(SHORT_DELAY_MS);
398 >        await(threadStarted);
399 >        assertThreadStaysAlive(t);
400          t.interrupt();
401 <        t.join();
401 >        awaitTermination(t);
402      }
403  
404      /**
405       * Take removes existing elements until empty, then blocks interruptibly
406       */
407      public void testBlockingTake() throws InterruptedException {
408 <        Thread t = new ThreadShouldThrow(InterruptedException.class) {
408 >        final DelayQueue q = populatedQueue(SIZE);
409 >        final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
410 >        Thread t = newStartedThread(new CheckedRunnable() {
411              public void realRun() throws InterruptedException {
420                DelayQueue q = populatedQueue(SIZE);
412                  for (int i = 0; i < SIZE; ++i) {
413 <                    threadAssertEquals(new PDelay(i), ((PDelay)q.take()));
413 >                    assertEquals(new PDelay(i), ((PDelay)q.take()));
414                  }
424                q.take();
425            }};
415  
416 <        t.start();
417 <        Thread.sleep(SHORT_DELAY_MS);
416 >                Thread.currentThread().interrupt();
417 >                try {
418 >                    q.take();
419 >                    shouldThrow();
420 >                } catch (InterruptedException success) {}
421 >                assertFalse(Thread.interrupted());
422 >
423 >                pleaseInterrupt.countDown();
424 >                try {
425 >                    q.take();
426 >                    shouldThrow();
427 >                } catch (InterruptedException success) {}
428 >                assertFalse(Thread.interrupted());
429 >            }});
430 >
431 >        await(pleaseInterrupt);
432 >        assertThreadStaysAlive(t);
433          t.interrupt();
434 <        t.join();
434 >        awaitTermination(t);
435      }
436  
433
437      /**
438       * poll succeeds unless empty
439       */
# Line 443 | Line 446 | public class DelayQueueTest extends JSR1
446      }
447  
448      /**
449 <     * timed pool with zero timeout succeeds when non-empty, else times out
449 >     * timed poll with zero timeout succeeds when non-empty, else times out
450       */
451      public void testTimedPoll0() throws InterruptedException {
452          DelayQueue q = populatedQueue(SIZE);
# Line 454 | Line 457 | public class DelayQueueTest extends JSR1
457      }
458  
459      /**
460 <     * timed pool with nonzero timeout succeeds when non-empty, else times out
460 >     * timed poll with nonzero timeout succeeds when non-empty, else times out
461       */
462      public void testTimedPoll() throws InterruptedException {
463          DelayQueue q = populatedQueue(SIZE);
# Line 469 | Line 472 | public class DelayQueueTest extends JSR1
472       * returning timeout status
473       */
474      public void testInterruptedTimedPoll() throws InterruptedException {
475 <        Thread t = new Thread(new CheckedRunnable() {
475 >        final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
476 >        Thread t = newStartedThread(new CheckedRunnable() {
477              public void realRun() throws InterruptedException {
478                  DelayQueue q = populatedQueue(SIZE);
479                  for (int i = 0; i < SIZE; ++i) {
480                      assertEquals(new PDelay(i), ((PDelay)q.poll(SHORT_DELAY_MS, MILLISECONDS)));
481                  }
482 +
483 +                Thread.currentThread().interrupt();
484 +                try {
485 +                    q.poll(LONG_DELAY_MS, MILLISECONDS);
486 +                    shouldThrow();
487 +                } catch (InterruptedException success) {}
488 +                assertFalse(Thread.interrupted());
489 +
490 +                pleaseInterrupt.countDown();
491                  try {
492 <                    q.poll(SMALL_DELAY_MS, MILLISECONDS);
492 >                    q.poll(LONG_DELAY_MS, MILLISECONDS);
493                      shouldThrow();
494                  } catch (InterruptedException success) {}
495 +                assertFalse(Thread.interrupted());
496              }});
497  
498 <        t.start();
499 <        Thread.sleep(SHORT_DELAY_MS);
498 >        await(pleaseInterrupt);
499 >        assertThreadStaysAlive(t);
500          t.interrupt();
501 <        t.join();
501 >        awaitTermination(t);
502      }
503  
504      /**
505 <     *  timed poll before a delayed offer fails; after offer succeeds;
506 <     *  on interruption throws
505 >     * timed poll before a delayed offer fails; after offer succeeds;
506 >     * on interruption throws
507       */
508      public void testTimedPollWithOffer() throws InterruptedException {
509          final DelayQueue q = new DelayQueue();
510          final PDelay pdelay = new PDelay(0);
511 <        Thread t = new Thread(new CheckedRunnable() {
511 >        final CheckedBarrier barrier = new CheckedBarrier(2);
512 >        Thread t = newStartedThread(new CheckedRunnable() {
513              public void realRun() throws InterruptedException {
514                  assertNull(q.poll(SHORT_DELAY_MS, MILLISECONDS));
515 +
516 +                barrier.await();
517                  assertSame(pdelay, q.poll(LONG_DELAY_MS, MILLISECONDS));
518 +
519 +                Thread.currentThread().interrupt();
520                  try {
521                      q.poll(LONG_DELAY_MS, MILLISECONDS);
522                      shouldThrow();
523                  } catch (InterruptedException success) {}
524 +                assertFalse(Thread.interrupted());
525 +
526 +                barrier.await();
527 +                try {
528 +                    q.poll(LONG_DELAY_MS, MILLISECONDS);
529 +                    shouldThrow();
530 +                } catch (InterruptedException success) {}
531 +                assertFalse(Thread.interrupted());
532              }});
533  
534 <        t.start();
535 <        Thread.sleep(SMALL_DELAY_MS);
536 <        assertTrue(q.offer(pdelay, SHORT_DELAY_MS, MILLISECONDS));
534 >        barrier.await();
535 >        long startTime = System.nanoTime();
536 >        assertTrue(q.offer(pdelay, LONG_DELAY_MS, MILLISECONDS));
537 >        assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
538 >
539 >        barrier.await();
540 >        assertThreadStaysAlive(t);
541          t.interrupt();
542 <        t.join();
542 >        awaitTermination(t);
543      }
544  
514
545      /**
546       * peek returns next element, or null if empty
547       */
# Line 519 | Line 549 | public class DelayQueueTest extends JSR1
549          DelayQueue q = populatedQueue(SIZE);
550          for (int i = 0; i < SIZE; ++i) {
551              assertEquals(new PDelay(i), ((PDelay)q.peek()));
552 <            q.poll();
552 >            assertEquals(new PDelay(i), ((PDelay)q.poll()));
553              if (q.isEmpty())
554                  assertNull(q.peek());
555              else
556 <                assertTrue(i != ((PDelay)q.peek()).intValue());
556 >                assertFalse(new PDelay(i).equals(q.peek()));
557          }
558          assertNull(q.peek());
559      }
# Line 658 | Line 688 | public class DelayQueueTest extends JSR1
688          Object[] o = q.toArray();
689          Arrays.sort(o);
690          for (int i = 0; i < o.length; i++)
691 <            assertEquals(o[i], q.take());
691 >            assertSame(o[i], q.take());
692      }
693  
694      /**
695       * toArray(a) contains all elements
696       */
697 <    public void testToArray2() throws InterruptedException {
698 <        DelayQueue q = populatedQueue(SIZE);
697 >    public void testToArray2() {
698 >        DelayQueue<PDelay> q = populatedQueue(SIZE);
699          PDelay[] ints = new PDelay[SIZE];
700 <        ints = (PDelay[])q.toArray(ints);
700 >        PDelay[] array = q.toArray(ints);
701 >        assertSame(ints, array);
702          Arrays.sort(ints);
703          for (int i = 0; i < ints.length; i++)
704 <            assertEquals(ints[i], q.take());
704 >            assertSame(ints[i], q.remove());
705      }
706  
676
707      /**
708 <     * toArray(null) throws NPE
708 >     * toArray(null) throws NullPointerException
709       */
710 <    public void testToArray_BadArg() {
710 >    public void testToArray_NullArg() {
711 >        DelayQueue q = populatedQueue(SIZE);
712          try {
713 <            DelayQueue q = populatedQueue(SIZE);
683 <            Object o[] = q.toArray(null);
713 >            q.toArray(null);
714              shouldThrow();
715          } catch (NullPointerException success) {}
716      }
717  
718      /**
719 <     * toArray with incompatible array type throws CCE
719 >     * toArray(incompatible array type) throws ArrayStoreException
720       */
721      public void testToArray1_BadArg() {
722 +        DelayQueue q = populatedQueue(SIZE);
723          try {
724 <            DelayQueue q = populatedQueue(SIZE);
694 <            Object o[] = q.toArray(new String[10] );
724 >            q.toArray(new String[10]);
725              shouldThrow();
726          } catch (ArrayStoreException success) {}
727      }
# Line 713 | Line 743 | public class DelayQueueTest extends JSR1
743      /**
744       * iterator.remove removes current element
745       */
746 <    public void testIteratorRemove () {
746 >    public void testIteratorRemove() {
747          final DelayQueue q = new DelayQueue();
748          q.add(new PDelay(2));
749          q.add(new PDelay(1));
# Line 727 | Line 757 | public class DelayQueueTest extends JSR1
757          assertFalse(it.hasNext());
758      }
759  
730
760      /**
761       * toString contains toStrings of elements
762       */
# Line 735 | Line 764 | public class DelayQueueTest extends JSR1
764          DelayQueue q = populatedQueue(SIZE);
765          String s = q.toString();
766          for (int i = 0; i < SIZE; ++i) {
767 <            assertTrue(s.indexOf(String.valueOf(Integer.MIN_VALUE+i)) >= 0);
767 >            assertTrue(s.contains(String.valueOf(Integer.MIN_VALUE+i)));
768          }
769      }
770  
771      /**
772 <     * offer transfers elements across Executor tasks
772 >     * timed poll transfers elements across Executor tasks
773       */
774      public void testPollInExecutor() {
775          final DelayQueue q = new DelayQueue();
776 +        final CheckedBarrier threadsStarted = new CheckedBarrier(2);
777          ExecutorService executor = Executors.newFixedThreadPool(2);
778          executor.execute(new CheckedRunnable() {
779              public void realRun() throws InterruptedException {
780 <                threadAssertNull(q.poll());
781 <                threadAssertTrue(null != q.poll(MEDIUM_DELAY_MS, MILLISECONDS));
782 <                threadAssertTrue(q.isEmpty());
780 >                assertNull(q.poll());
781 >                threadsStarted.await();
782 >                assertTrue(null != q.poll(LONG_DELAY_MS, MILLISECONDS));
783 >                checkEmpty(q);
784              }});
785  
786          executor.execute(new CheckedRunnable() {
787              public void realRun() throws InterruptedException {
788 <                Thread.sleep(SHORT_DELAY_MS);
788 >                threadsStarted.await();
789                  q.put(new PDelay(1));
790              }});
791  
792          joinPool(executor);
762
793      }
794  
765
795      /**
796       * Delayed actions do not occur until their delay elapses
797       */
798      public void testDelay() throws InterruptedException {
799 <        DelayQueue q = new DelayQueue();
800 <        NanoDelay[] elements = new NanoDelay[SIZE];
801 <        for (int i = 0; i < SIZE; ++i) {
773 <            elements[i] = new NanoDelay(1000000000L + 1000000L * (SIZE - i));
774 <        }
775 <        for (int i = 0; i < SIZE; ++i) {
776 <            q.add(elements[i]);
777 <        }
799 >        DelayQueue<NanoDelay> q = new DelayQueue<NanoDelay>();
800 >        for (int i = 0; i < SIZE; ++i)
801 >            q.add(new NanoDelay(1000000L * (SIZE - i)));
802  
803          long last = 0;
804          for (int i = 0; i < SIZE; ++i) {
805 <            NanoDelay e = (NanoDelay)(q.take());
805 >            NanoDelay e = q.take();
806              long tt = e.getTriggerTime();
807 <            assertTrue(tt <= System.nanoTime());
807 >            assertTrue(System.nanoTime() - tt >= 0);
808              if (i != 0)
809                  assertTrue(tt >= last);
810              last = tt;
811          }
812 +        assertTrue(q.isEmpty());
813      }
814  
815      /**
# Line 793 | Line 818 | public class DelayQueueTest extends JSR1
818      public void testPeekDelayed() {
819          DelayQueue q = new DelayQueue();
820          q.add(new NanoDelay(Long.MAX_VALUE));
821 <        assert(q.peek() != null);
821 >        assertNotNull(q.peek());
822      }
823  
799
824      /**
825       * poll of a non-empty queue returns null if no expired elements.
826       */
# Line 906 | Line 930 | public class DelayQueueTest extends JSR1
930      }
931  
932      /**
933 <     * drainTo(c, n) empties first max {n, size} elements of queue into c
933 >     * drainTo(c, n) empties first min(n, size) elements of queue into c
934       */
935      public void testDrainToN() {
936          for (int i = 0; i < SIZE + 2; ++i) {
937              DelayQueue q = populatedQueue(SIZE);
938              ArrayList l = new ArrayList();
939              q.drainTo(l, i);
940 <            int k = (i < SIZE)? i : SIZE;
940 >            int k = (i < SIZE) ? i : SIZE;
941              assertEquals(q.size(), SIZE-k);
942              assertEquals(l.size(), k);
943          }
944      }
945  
922
946   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines