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.46 by jsr166, Thu Nov 18 18:49:18 2010 UTC vs.
Revision 1.56 by jsr166, Fri Jul 15 18:49:31 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   */
8  
9   import junit.framework.*;
10 < import java.util.*;
10 > import java.util.Arrays;
11 > import java.util.ArrayList;
12 > import java.util.Iterator;
13 > import java.util.NoSuchElementException;
14 > import java.util.concurrent.BlockingQueue;
15 > import java.util.concurrent.CountDownLatch;
16 > import java.util.concurrent.Delayed;
17 > import java.util.concurrent.DelayQueue;
18 > import java.util.concurrent.Executors;
19 > import java.util.concurrent.ExecutorService;
20 > import java.util.concurrent.TimeUnit;
21   import static java.util.concurrent.TimeUnit.MILLISECONDS;
12 import java.util.concurrent.*;
22  
23   public class DelayQueueTest extends JSR166TestCase {
24 +
25 +    public static class Generic extends BlockingQueueTest {
26 +        protected BlockingQueue emptyCollection() {
27 +            return new DelayQueue();
28 +        }
29 +        protected PDelay makeElement(int i) {
30 +            return new PDelay(i);
31 +        }
32 +    }
33 +
34      public static void main(String[] args) {
35          junit.textui.TestRunner.run(suite());
36      }
37  
38      public static Test suite() {
39 <        return new TestSuite(DelayQueueTest.class);
39 >        return newTestSuite(DelayQueueTest.class,
40 >                            new Generic().testSuite());
41      }
42  
43      private static final int NOCAP = Integer.MAX_VALUE;
# Line 29 | Line 49 | public class DelayQueueTest extends JSR1
49       */
50      static class PDelay implements Delayed {
51          int pseudodelay;
52 <        PDelay(int i) { pseudodelay = Integer.MIN_VALUE + i; }
53 <        public int compareTo(PDelay y) {
54 <            int i = pseudodelay;
55 <            int j = y.pseudodelay;
56 <            if (i < j) return -1;
37 <            if (i > j) return 1;
38 <            return 0;
52 >        PDelay(int i) { pseudodelay = i; }
53 >        public int compareTo(PDelay other) {
54 >            int a = this.pseudodelay;
55 >            int b = other.pseudodelay;
56 >            return (a < b) ? -1 : (a > b) ? 1 : 0;
57          }
40
58          public int compareTo(Delayed y) {
59              return compareTo((PDelay)y);
60          }
44
61          public boolean equals(Object other) {
62 <            return equals((PDelay)other);
63 <        }
48 <        public boolean equals(PDelay other) {
49 <            return other.pseudodelay == pseudodelay;
62 >            return (other instanceof PDelay) &&
63 >                this.pseudodelay == ((PDelay)other).pseudodelay;
64          }
51
52
65          public long getDelay(TimeUnit ignore) {
66 <            return pseudodelay;
55 <        }
56 <        public int intValue() {
57 <            return pseudodelay;
66 >            return Integer.MIN_VALUE + pseudodelay;
67          }
59
68          public String toString() {
69              return String.valueOf(pseudodelay);
70          }
71      }
72  
65
73      /**
74       * Delayed implementation that actually delays
75       */
# Line 104 | Line 111 | public class DelayQueueTest extends JSR1
111          }
112      }
113  
107
114      /**
115       * Create a queue of given size containing consecutive
116       * PDelays 0 ... n.
# Line 209 | Line 215 | public class DelayQueueTest extends JSR1
215      }
216  
217      /**
212     * offer(null) throws NPE
213     */
214    public void testOfferNull() {
215        try {
216            DelayQueue q = new DelayQueue();
217            q.offer(null);
218            shouldThrow();
219        } catch (NullPointerException success) {}
220    }
221
222    /**
223     * add(null) throws NPE
224     */
225    public void testAddNull() {
226        try {
227            DelayQueue q = new DelayQueue();
228            q.add(null);
229            shouldThrow();
230        } catch (NullPointerException success) {}
231    }
232
233    /**
218       * offer non-null succeeds
219       */
220      public void testOffer() {
# Line 251 | Line 235 | public class DelayQueueTest extends JSR1
235      }
236  
237      /**
254     * addAll(null) throws NPE
255     */
256    public void testAddAll1() {
257        try {
258            DelayQueue q = new DelayQueue();
259            q.addAll(null);
260            shouldThrow();
261        } catch (NullPointerException success) {}
262    }
263
264
265    /**
238       * addAll(this) throws IAE
239       */
240      public void testAddAllSelf() {
# Line 274 | Line 246 | public class DelayQueueTest extends JSR1
246      }
247  
248      /**
277     * addAll of a collection with null elements throws NPE
278     */
279    public void testAddAll2() {
280        try {
281            DelayQueue q = new DelayQueue();
282            PDelay[] ints = new PDelay[SIZE];
283            q.addAll(Arrays.asList(ints));
284            shouldThrow();
285        } catch (NullPointerException success) {}
286    }
287
288    /**
249       * addAll of a collection with any null elements throws NPE after
250       * possibly adding some elements
251       */
# Line 316 | Line 276 | public class DelayQueueTest extends JSR1
276      }
277  
278      /**
319     * put(null) throws NPE
320     */
321     public void testPutNull() {
322        try {
323            DelayQueue q = new DelayQueue();
324            q.put(null);
325            shouldThrow();
326        } catch (NullPointerException success) {}
327     }
328
329    /**
279       * all elements successfully put are contained
280       */
281 <     public void testPut() {
282 <         DelayQueue q = new DelayQueue();
283 <         for (int i = 0; i < SIZE; ++i) {
284 <             PDelay I = new PDelay(i);
285 <             q.put(I);
286 <             assertTrue(q.contains(I));
287 <         }
288 <         assertEquals(SIZE, q.size());
281 >    public void testPut() {
282 >        DelayQueue q = new DelayQueue();
283 >        for (int i = 0; i < SIZE; ++i) {
284 >            PDelay I = new PDelay(i);
285 >            q.put(I);
286 >            assertTrue(q.contains(I));
287 >        }
288 >        assertEquals(SIZE, q.size());
289      }
290  
291      /**
# Line 344 | Line 293 | public class DelayQueueTest extends JSR1
293       */
294      public void testPutWithTake() throws InterruptedException {
295          final DelayQueue q = new DelayQueue();
296 <        Thread t = new Thread(new CheckedRunnable() {
296 >        Thread t = newStartedThread(new CheckedRunnable() {
297              public void realRun() {
298                  q.put(new PDelay(0));
299                  q.put(new PDelay(0));
# Line 352 | Line 301 | public class DelayQueueTest extends JSR1
301                  q.put(new PDelay(0));
302              }});
303  
304 <        t.start();
305 <        Thread.sleep(SHORT_DELAY_MS);
357 <        q.take();
358 <        t.interrupt();
359 <        t.join();
304 >        awaitTermination(t);
305 >        assertEquals(4, q.size());
306      }
307  
308      /**
# Line 364 | Line 310 | public class DelayQueueTest extends JSR1
310       */
311      public void testTimedOffer() throws InterruptedException {
312          final DelayQueue q = new DelayQueue();
313 <        Thread t = new Thread(new CheckedRunnable() {
313 >        Thread t = newStartedThread(new CheckedRunnable() {
314              public void realRun() throws InterruptedException {
315                  q.put(new PDelay(0));
316                  q.put(new PDelay(0));
# Line 372 | Line 318 | public class DelayQueueTest extends JSR1
318                  assertTrue(q.offer(new PDelay(0), LONG_DELAY_MS, MILLISECONDS));
319              }});
320  
321 <        t.start();
376 <        Thread.sleep(SMALL_DELAY_MS);
377 <        t.interrupt();
378 <        t.join();
321 >        awaitTermination(t);
322      }
323  
324      /**
# Line 389 | Line 332 | public class DelayQueueTest extends JSR1
332      }
333  
334      /**
392     * take blocks interruptibly when empty
393     */
394    public void testTakeFromEmptyBlocksInterruptibly()
395            throws InterruptedException {
396        final BlockingQueue q = new DelayQueue();
397        final CountDownLatch threadStarted = new CountDownLatch(1);
398        Thread t = newStartedThread(new CheckedRunnable() {
399            public void realRun() {
400                long t0 = System.nanoTime();
401                threadStarted.countDown();
402                try {
403                    q.take();
404                    shouldThrow();
405                } catch (InterruptedException success) {}
406                assertTrue(millisElapsedSince(t0) >= SHORT_DELAY_MS);
407            }});
408        threadStarted.await();
409        Thread.sleep(SHORT_DELAY_MS);
410        assertTrue(t.isAlive());
411        t.interrupt();
412        awaitTermination(t, MEDIUM_DELAY_MS);
413        assertFalse(t.isAlive());
414    }
415
416    /**
335       * Take removes existing elements until empty, then blocks interruptibly
336       */
337      public void testBlockingTake() throws InterruptedException {
338          final DelayQueue q = populatedQueue(SIZE);
339 <        Thread t = new Thread(new CheckedRunnable() {
339 >        final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
340 >        Thread t = newStartedThread(new CheckedRunnable() {
341              public void realRun() throws InterruptedException {
342                  for (int i = 0; i < SIZE; ++i) {
343                      assertEquals(new PDelay(i), ((PDelay)q.take()));
344                  }
345 +
346 +                Thread.currentThread().interrupt();
347 +                try {
348 +                    q.take();
349 +                    shouldThrow();
350 +                } catch (InterruptedException success) {}
351 +                assertFalse(Thread.interrupted());
352 +
353 +                pleaseInterrupt.countDown();
354                  try {
355                      q.take();
356                      shouldThrow();
357                  } catch (InterruptedException success) {}
358 +                assertFalse(Thread.interrupted());
359              }});
360  
361 <        t.start();
362 <        Thread.sleep(SHORT_DELAY_MS);
361 >        await(pleaseInterrupt);
362 >        assertThreadStaysAlive(t);
363          t.interrupt();
364 <        t.join();
364 >        awaitTermination(t);
365      }
366  
438
367      /**
368       * poll succeeds unless empty
369       */
# Line 464 | Line 392 | public class DelayQueueTest extends JSR1
392      public void testTimedPoll() throws InterruptedException {
393          DelayQueue q = populatedQueue(SIZE);
394          for (int i = 0; i < SIZE; ++i) {
395 <            assertEquals(new PDelay(i), ((PDelay)q.poll(SHORT_DELAY_MS, MILLISECONDS)));
396 <        }
397 <        assertNull(q.poll(SHORT_DELAY_MS, MILLISECONDS));
395 >            long startTime = System.nanoTime();
396 >            assertEquals(new PDelay(i), ((PDelay)q.poll(LONG_DELAY_MS, MILLISECONDS)));
397 >            assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
398 >        }
399 >        long startTime = System.nanoTime();
400 >        assertNull(q.poll(timeoutMillis(), MILLISECONDS));
401 >        assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
402 >        checkEmpty(q);
403      }
404  
405      /**
# Line 474 | Line 407 | public class DelayQueueTest extends JSR1
407       * returning timeout status
408       */
409      public void testInterruptedTimedPoll() throws InterruptedException {
410 <        Thread t = new Thread(new CheckedRunnable() {
410 >        final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
411 >        Thread t = newStartedThread(new CheckedRunnable() {
412              public void realRun() throws InterruptedException {
413                  DelayQueue q = populatedQueue(SIZE);
414                  for (int i = 0; i < SIZE; ++i) {
415                      assertEquals(new PDelay(i), ((PDelay)q.poll(SHORT_DELAY_MS, MILLISECONDS)));
416                  }
483                try {
484                    q.poll(SMALL_DELAY_MS, MILLISECONDS);
485                    shouldThrow();
486                } catch (InterruptedException success) {}
487            }});
488
489        t.start();
490        Thread.sleep(SHORT_DELAY_MS);
491        t.interrupt();
492        t.join();
493    }
494
495    /**
496     * timed poll before a delayed offer fails; after offer succeeds;
497     * on interruption throws
498     */
499    public void testTimedPollWithOffer() throws InterruptedException {
500        final DelayQueue q = new DelayQueue();
501        final PDelay pdelay = new PDelay(0);
502        final CheckedBarrier barrier = new CheckedBarrier(2);
503        Thread t = new Thread(new CheckedRunnable() {
504            public void realRun() throws InterruptedException {
505                assertNull(q.poll(SHORT_DELAY_MS, MILLISECONDS));
506
507                barrier.await();
508                assertSame(pdelay, q.poll(MEDIUM_DELAY_MS, MILLISECONDS));
417  
418                  Thread.currentThread().interrupt();
419                  try {
420 <                    q.poll(SHORT_DELAY_MS, MILLISECONDS);
420 >                    q.poll(LONG_DELAY_MS, MILLISECONDS);
421                      shouldThrow();
422                  } catch (InterruptedException success) {}
423 +                assertFalse(Thread.interrupted());
424  
425 <                barrier.await();
425 >                pleaseInterrupt.countDown();
426                  try {
427 <                    q.poll(MEDIUM_DELAY_MS, MILLISECONDS);
427 >                    q.poll(LONG_DELAY_MS, MILLISECONDS);
428                      shouldThrow();
429                  } catch (InterruptedException success) {}
430 +                assertFalse(Thread.interrupted());
431              }});
432  
433 <        t.start();
434 <        barrier.await();
525 <        assertTrue(q.offer(pdelay, SHORT_DELAY_MS, MILLISECONDS));
526 <        barrier.await();
527 <        sleep(SHORT_DELAY_MS);
433 >        await(pleaseInterrupt);
434 >        assertThreadStaysAlive(t);
435          t.interrupt();
436 <        t.join();
436 >        awaitTermination(t);
437      }
438  
532
439      /**
440       * peek returns next element, or null if empty
441       */
# Line 576 | Line 482 | public class DelayQueueTest extends JSR1
482      }
483  
484      /**
579     * remove(x) removes x and returns true if present
580     */
581    public void testRemoveElement() {
582        DelayQueue q = populatedQueue(SIZE);
583        for (int i = 1; i < SIZE; i+=2) {
584            assertTrue(q.remove(new PDelay(i)));
585        }
586        for (int i = 0; i < SIZE; i+=2) {
587            assertTrue(q.remove(new PDelay(i)));
588            assertFalse(q.remove(new PDelay(i+1)));
589        }
590        assertTrue(q.isEmpty());
591    }
592
593    /**
485       * contains(x) reports true when elements added but not yet removed
486       */
487      public void testContains() {
# Line 692 | Line 583 | public class DelayQueueTest extends JSR1
583              assertSame(ints[i], q.remove());
584      }
585  
695
696    /**
697     * toArray(null) throws NullPointerException
698     */
699    public void testToArray_NullArg() {
700        DelayQueue q = populatedQueue(SIZE);
701        try {
702            q.toArray(null);
703            shouldThrow();
704        } catch (NullPointerException success) {}
705    }
706
586      /**
587       * toArray(incompatible array type) throws ArrayStoreException
588       */
# Line 746 | Line 625 | public class DelayQueueTest extends JSR1
625          assertFalse(it.hasNext());
626      }
627  
749
628      /**
629       * toString contains toStrings of elements
630       */
631      public void testToString() {
632          DelayQueue q = populatedQueue(SIZE);
633          String s = q.toString();
634 <        for (int i = 0; i < SIZE; ++i) {
635 <            assertTrue(s.indexOf(String.valueOf(Integer.MIN_VALUE+i)) >= 0);
758 <        }
634 >        for (Object e : q)
635 >            assertTrue(s.contains(e.toString()));
636      }
637  
638      /**
639 <     * offer transfers elements across Executor tasks
639 >     * timed poll transfers elements across Executor tasks
640       */
641      public void testPollInExecutor() {
642          final DelayQueue q = new DelayQueue();
643 +        final CheckedBarrier threadsStarted = new CheckedBarrier(2);
644          ExecutorService executor = Executors.newFixedThreadPool(2);
645          executor.execute(new CheckedRunnable() {
646              public void realRun() throws InterruptedException {
647                  assertNull(q.poll());
648 <                assertTrue(null != q.poll(MEDIUM_DELAY_MS, MILLISECONDS));
649 <                assertTrue(q.isEmpty());
648 >                threadsStarted.await();
649 >                assertTrue(null != q.poll(LONG_DELAY_MS, MILLISECONDS));
650 >                checkEmpty(q);
651              }});
652  
653          executor.execute(new CheckedRunnable() {
654              public void realRun() throws InterruptedException {
655 <                Thread.sleep(SHORT_DELAY_MS);
655 >                threadsStarted.await();
656                  q.put(new PDelay(1));
657              }});
658  
659          joinPool(executor);
660      }
661  
783
662      /**
663       * Delayed actions do not occur until their delay elapses
664       */
# Line 810 | Line 688 | public class DelayQueueTest extends JSR1
688          assertNotNull(q.peek());
689      }
690  
813
691      /**
692       * poll of a non-empty queue returns null if no expired elements.
693       */
# Line 826 | Line 703 | public class DelayQueueTest extends JSR1
703      public void testTimedPollDelayed() throws InterruptedException {
704          DelayQueue q = new DelayQueue();
705          q.add(new NanoDelay(LONG_DELAY_MS * 1000000L));
706 <        assertNull(q.poll(SHORT_DELAY_MS, MILLISECONDS));
830 <    }
831 <
832 <    /**
833 <     * drainTo(null) throws NPE
834 <     */
835 <    public void testDrainToNull() {
836 <        DelayQueue q = populatedQueue(SIZE);
837 <        try {
838 <            q.drainTo(null);
839 <            shouldThrow();
840 <        } catch (NullPointerException success) {}
841 <    }
842 <
843 <    /**
844 <     * drainTo(this) throws IAE
845 <     */
846 <    public void testDrainToSelf() {
847 <        DelayQueue q = populatedQueue(SIZE);
848 <        try {
849 <            q.drainTo(q);
850 <            shouldThrow();
851 <        } catch (IllegalArgumentException success) {}
706 >        assertNull(q.poll(timeoutMillis(), MILLISECONDS));
707      }
708  
709      /**
# Line 898 | Line 753 | public class DelayQueueTest extends JSR1
753      }
754  
755      /**
901     * drainTo(null, n) throws NPE
902     */
903    public void testDrainToNullN() {
904        DelayQueue q = populatedQueue(SIZE);
905        try {
906            q.drainTo(null, 0);
907            shouldThrow();
908        } catch (NullPointerException success) {}
909    }
910
911    /**
912     * drainTo(this, n) throws IAE
913     */
914    public void testDrainToSelfN() {
915        DelayQueue q = populatedQueue(SIZE);
916        try {
917            q.drainTo(q, 0);
918            shouldThrow();
919        } catch (IllegalArgumentException success) {}
920    }
921
922    /**
756       * drainTo(c, n) empties first min(n, size) elements of queue into c
757       */
758      public void testDrainToN() {
# Line 933 | Line 766 | public class DelayQueueTest extends JSR1
766          }
767      }
768  
936
769   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines