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.4 by dl, Sat Sep 20 18:20:07 2003 UTC vs.
Revision 1.56 by jsr166, Fri Jul 15 18:49:31 2011 UTC

# Line 1 | Line 1
1   /*
2 < * Written by members of JCP JSR-166 Expert Group and released to the
3 < * public domain. Use, modify, and redistribute this code in any way
4 < * without acknowledgement. Other contributors include Andrew Wright,
5 < * Jeffrey Hayes, Pat Fischer, Mike Judd.
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/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.*;
11 < import java.util.concurrent.*;
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;
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());  
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;
44  
45      /**
46 <     * A delayed implmentation for testing.
47 <     * Most Q/BQ tests use Pseudodelays, where delays are all elapsed
46 >     * A delayed implementation for testing.
47 >     * Most tests use Pseudodelays, where delays are all elapsed
48       * (so, no blocking solely for delays) but are still ordered
49 <     */
50 <    static class PDelay implements Delayed {
49 >     */
50 >    static class PDelay implements Delayed {
51          int pseudodelay;
52 <        PDelay(int i) { pseudodelay = Integer.MIN_VALUE + i; }
53 <        public int compareTo(Object y) {
54 <            int i = pseudodelay;
55 <            int j = ((PDelay)y).pseudodelay;
56 <            if (i < j) return -1;
35 <            if (i > j) return 1;
36 <            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          }
58 <
59 <        public int compareTo(PDelay y) {
40 <            int i = pseudodelay;
41 <            int j = ((PDelay)y).pseudodelay;
42 <            if (i < j) return -1;
43 <            if (i > j) return 1;
44 <            return 0;
58 >        public int compareTo(Delayed y) {
59 >            return compareTo((PDelay)y);
60          }
46
61          public boolean equals(Object other) {
62 <            return ((PDelay)other).pseudodelay == pseudodelay;
63 <        }
50 <        public boolean equals(PDelay other) {
51 <            return ((PDelay)other).pseudodelay == pseudodelay;
62 >            return (other instanceof PDelay) &&
63 >                this.pseudodelay == ((PDelay)other).pseudodelay;
64          }
53
54
65          public long getDelay(TimeUnit ignore) {
66 <            return pseudodelay;
57 <        }
58 <        public int intValue() {
59 <            return pseudodelay;
66 >            return Integer.MIN_VALUE + pseudodelay;
67          }
61
68          public String toString() {
69              return String.valueOf(pseudodelay);
70          }
71      }
72  
67
73      /**
74       * Delayed implementation that actually delays
75       */
76 <    static class NanoDelay implements Delayed {
76 >    static class NanoDelay implements Delayed {
77          long trigger;
78 <        NanoDelay(long i) {
78 >        NanoDelay(long i) {
79              trigger = System.nanoTime() + i;
80          }
81 <        public int compareTo(Object y) {
81 >        public int compareTo(NanoDelay y) {
82              long i = trigger;
83 <            long j = ((NanoDelay)y).trigger;
83 >            long j = y.trigger;
84              if (i < j) return -1;
85              if (i > j) return 1;
86              return 0;
87          }
88  
89 <        public int compareTo(NanoDelay y) {
90 <            long i = trigger;
86 <            long j = ((NanoDelay)y).trigger;
87 <            if (i < j) return -1;
88 <            if (i > j) return 1;
89 <            return 0;
89 >        public int compareTo(Delayed y) {
90 >            return compareTo((NanoDelay)y);
91          }
92  
93          public boolean equals(Object other) {
94 <            return ((NanoDelay)other).trigger == trigger;
94 >            return equals((NanoDelay)other);
95          }
96          public boolean equals(NanoDelay other) {
97 <            return ((NanoDelay)other).trigger == trigger;
97 >            return other.trigger == trigger;
98          }
99  
100          public long getDelay(TimeUnit unit) {
# Line 110 | Line 111 | public class DelayQueueTest extends JSR1
111          }
112      }
113  
113
114      /**
115       * Create a queue of given size containing consecutive
116       * PDelays 0 ... n.
117       */
118 <    private DelayQueue populatedQueue(int n) {
119 <        DelayQueue q = new DelayQueue();
118 >    private DelayQueue<PDelay> populatedQueue(int n) {
119 >        DelayQueue<PDelay> q = new DelayQueue<PDelay>();
120          assertTrue(q.isEmpty());
121 <        for(int i = n-1; i >= 0; i-=2)
122 <            assertTrue(q.offer(new PDelay(i)));
123 <        for(int i = (n & 1); i < n; i+=2)
124 <            assertTrue(q.offer(new PDelay(i)));
121 >        for (int i = n-1; i >= 0; i-=2)
122 >            assertTrue(q.offer(new PDelay(i)));
123 >        for (int i = (n & 1); i < n; i+=2)
124 >            assertTrue(q.offer(new PDelay(i)));
125          assertFalse(q.isEmpty());
126          assertEquals(NOCAP, q.remainingCapacity());
127 <        assertEquals(n, q.size());
127 >        assertEquals(n, q.size());
128          return q;
129      }
130 <
130 >
131      /**
132 <     *
132 >     * A new queue has unbounded capacity
133       */
134      public void testConstructor1() {
135          assertEquals(NOCAP, new DelayQueue().remainingCapacity());
136      }
137  
138      /**
139 <     *
139 >     * Initializing from null Collection throws NPE
140       */
141      public void testConstructor3() {
142          try {
143              DelayQueue q = new DelayQueue(null);
144              shouldThrow();
145 <        }
146 <        catch (NullPointerException success) {}
145 >        } catch (NullPointerException success) {}
146      }
147  
148      /**
149 <     *
149 >     * Initializing from Collection of null elements throws NPE
150       */
151      public void testConstructor4() {
152          try {
153              PDelay[] ints = new PDelay[SIZE];
154              DelayQueue q = new DelayQueue(Arrays.asList(ints));
155              shouldThrow();
156 <        }
158 <        catch (NullPointerException success) {}
156 >        } catch (NullPointerException success) {}
157      }
158  
159      /**
160 <     *
160 >     * Initializing from Collection with some null elements throws NPE
161       */
162      public void testConstructor5() {
163          try {
# Line 168 | Line 166 | public class DelayQueueTest extends JSR1
166                  ints[i] = new PDelay(i);
167              DelayQueue q = new DelayQueue(Arrays.asList(ints));
168              shouldThrow();
169 <        }
172 <        catch (NullPointerException success) {}
169 >        } catch (NullPointerException success) {}
170      }
171  
172      /**
173 <     *
173 >     * Queue contains all elements of collection used to initialize
174       */
175      public void testConstructor6() {
176 <        try {
177 <            PDelay[] ints = new PDelay[SIZE];
178 <            for (int i = 0; i < SIZE; ++i)
179 <                ints[i] = new PDelay(i);
180 <            DelayQueue q = new DelayQueue(Arrays.asList(ints));
181 <            for (int i = 0; i < SIZE; ++i)
185 <                assertEquals(ints[i], q.poll());
186 <        }
187 <        finally {}
176 >        PDelay[] ints = new PDelay[SIZE];
177 >        for (int i = 0; i < SIZE; ++i)
178 >            ints[i] = new PDelay(i);
179 >        DelayQueue q = new DelayQueue(Arrays.asList(ints));
180 >        for (int i = 0; i < SIZE; ++i)
181 >            assertEquals(ints[i], q.poll());
182      }
183  
184      /**
185 <     *
185 >     * isEmpty is true before add, false after
186       */
187      public void testEmpty() {
188          DelayQueue q = new DelayQueue();
# Line 203 | Line 197 | public class DelayQueueTest extends JSR1
197      }
198  
199      /**
200 <     *
200 >     * remainingCapacity does not change when elements added or removed,
201 >     * but size does
202       */
203      public void testRemainingCapacity() {
204          DelayQueue q = populatedQueue(SIZE);
# Line 220 | Line 215 | public class DelayQueueTest extends JSR1
215      }
216  
217      /**
218 <     *
224 <     */
225 <    public void testOfferNull() {
226 <        try {
227 <            DelayQueue q = new DelayQueue();
228 <            q.offer(null);
229 <            shouldThrow();
230 <        } catch (NullPointerException success) { }  
231 <    }
232 <
233 <    /**
234 <     *
218 >     * offer non-null succeeds
219       */
220      public void testOffer() {
221          DelayQueue q = new DelayQueue();
# Line 240 | Line 224 | public class DelayQueueTest extends JSR1
224      }
225  
226      /**
227 <     *
227 >     * add succeeds
228       */
229      public void testAdd() {
230          DelayQueue q = new DelayQueue();
# Line 251 | Line 235 | public class DelayQueueTest extends JSR1
235      }
236  
237      /**
238 <     *
255 <     */
256 <    public void testAddAll1() {
257 <        try {
258 <            DelayQueue q = new DelayQueue();
259 <            q.addAll(null);
260 <            shouldThrow();
261 <        }
262 <        catch (NullPointerException success) {}
263 <    }
264 <    /**
265 <     *
238 >     * addAll(this) throws IAE
239       */
240 <    public void testAddAll2() {
240 >    public void testAddAllSelf() {
241          try {
242 <            DelayQueue q = new DelayQueue();
243 <            PDelay[] ints = new PDelay[SIZE];
271 <            q.addAll(Arrays.asList(ints));
242 >            DelayQueue q = populatedQueue(SIZE);
243 >            q.addAll(q);
244              shouldThrow();
245 <        }
274 <        catch (NullPointerException success) {}
245 >        } catch (IllegalArgumentException success) {}
246      }
247 +
248      /**
249 <     *
249 >     * addAll of a collection with any null elements throws NPE after
250 >     * possibly adding some elements
251       */
252      public void testAddAll3() {
253          try {
# Line 284 | Line 257 | public class DelayQueueTest extends JSR1
257                  ints[i] = new PDelay(i);
258              q.addAll(Arrays.asList(ints));
259              shouldThrow();
260 <        }
288 <        catch (NullPointerException success) {}
260 >        } catch (NullPointerException success) {}
261      }
262  
263      /**
264 <     *
264 >     * Queue contains all elements of successful addAll
265       */
266      public void testAddAll5() {
267 <        try {
268 <            PDelay[] empty = new PDelay[0];
269 <            PDelay[] ints = new PDelay[SIZE];
270 <            for (int i = SIZE-1; i >= 0; --i)
271 <                ints[i] = new PDelay(i);
272 <            DelayQueue q = new DelayQueue();
273 <            assertFalse(q.addAll(Arrays.asList(empty)));
274 <            assertTrue(q.addAll(Arrays.asList(ints)));
275 <            for (int i = 0; i < SIZE; ++i)
304 <                assertEquals(ints[i], q.poll());
305 <        }
306 <        finally {}
267 >        PDelay[] empty = new PDelay[0];
268 >        PDelay[] ints = new PDelay[SIZE];
269 >        for (int i = SIZE-1; i >= 0; --i)
270 >            ints[i] = new PDelay(i);
271 >        DelayQueue q = new DelayQueue();
272 >        assertFalse(q.addAll(Arrays.asList(empty)));
273 >        assertTrue(q.addAll(Arrays.asList(ints)));
274 >        for (int i = 0; i < SIZE; ++i)
275 >            assertEquals(ints[i], q.poll());
276      }
277  
278      /**
279 <     *
311 <     */
312 <     public void testPutNull() {
313 <        try {
314 <            DelayQueue q = new DelayQueue();
315 <            q.put(null);
316 <            shouldThrow();
317 <        }
318 <        catch (NullPointerException success){
319 <        }  
320 <     }
321 <
322 <    /**
323 <     *
279 >     * all elements successfully put are contained
280       */
281 <     public void testPut() {
282 <         try {
283 <             DelayQueue q = new DelayQueue();
284 <             for (int i = 0; i < SIZE; ++i) {
285 <                 PDelay I = new PDelay(i);
286 <                 q.put(I);
331 <                 assertTrue(q.contains(I));
332 <             }
333 <             assertEquals(SIZE, q.size());
334 <         }
335 <         finally {
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      /**
292 <     *
292 >     * put doesn't block waiting for take
293       */
294 <    public void testPutWithTake() {
294 >    public void testPutWithTake() throws InterruptedException {
295          final DelayQueue q = new DelayQueue();
296 <        Thread t = new Thread(new Runnable() {
297 <                public void run() {
298 <                    int added = 0;
299 <                    try {
300 <                        q.put(new PDelay(0));
301 <                        ++added;
302 <                        q.put(new PDelay(0));
303 <                        ++added;
304 <                        q.put(new PDelay(0));
305 <                        ++added;
354 <                        q.put(new PDelay(0));
355 <                        ++added;
356 <                        threadAssertTrue(added == 4);
357 <                    } finally {
358 <                    }
359 <                }
360 <            });
361 <        try {
362 <            t.start();
363 <            Thread.sleep(SHORT_DELAY_MS);
364 <            q.take();
365 <            t.interrupt();
366 <            t.join();
367 <        } catch (Exception e){
368 <            unexpectedException();
369 <        }
296 >        Thread t = newStartedThread(new CheckedRunnable() {
297 >            public void realRun() {
298 >                q.put(new PDelay(0));
299 >                q.put(new PDelay(0));
300 >                q.put(new PDelay(0));
301 >                q.put(new PDelay(0));
302 >            }});
303 >
304 >        awaitTermination(t);
305 >        assertEquals(4, q.size());
306      }
307  
308      /**
309 <     *
309 >     * timed offer does not time out
310       */
311 <    public void testTimedOffer() {
311 >    public void testTimedOffer() throws InterruptedException {
312          final DelayQueue q = new DelayQueue();
313 <        Thread t = new Thread(new Runnable() {
314 <                public void run() {
315 <                    try {
316 <                        q.put(new PDelay(0));
317 <                        q.put(new PDelay(0));
318 <                        threadAssertTrue(q.offer(new PDelay(0), SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
319 <                        threadAssertTrue(q.offer(new PDelay(0), LONG_DELAY_MS, TimeUnit.MILLISECONDS));
320 <                    } finally { }
321 <                }
386 <            });
387 <        
388 <        try {
389 <            t.start();
390 <            Thread.sleep(SMALL_DELAY_MS);
391 <            t.interrupt();
392 <            t.join();
393 <        } catch (Exception e){
394 <            unexpectedException();
395 <        }
313 >        Thread t = newStartedThread(new CheckedRunnable() {
314 >            public void realRun() throws InterruptedException {
315 >                q.put(new PDelay(0));
316 >                q.put(new PDelay(0));
317 >                assertTrue(q.offer(new PDelay(0), SHORT_DELAY_MS, MILLISECONDS));
318 >                assertTrue(q.offer(new PDelay(0), LONG_DELAY_MS, MILLISECONDS));
319 >            }});
320 >
321 >        awaitTermination(t);
322      }
323  
324      /**
325 <     *
325 >     * take retrieves elements in priority order
326       */
327 <    public void testTake() {
328 <        try {
329 <            DelayQueue q = populatedQueue(SIZE);
330 <            for (int i = 0; i < SIZE; ++i) {
331 <                assertEquals(new PDelay(i), ((PDelay)q.take()));
406 <            }
407 <        } catch (InterruptedException e){
408 <            unexpectedException();
409 <        }  
327 >    public void testTake() throws InterruptedException {
328 >        DelayQueue q = populatedQueue(SIZE);
329 >        for (int i = 0; i < SIZE; ++i) {
330 >            assertEquals(new PDelay(i), ((PDelay)q.take()));
331 >        }
332      }
333  
334      /**
335 <     *
335 >     * Take removes existing elements until empty, then blocks interruptibly
336       */
337 <    public void testTakeFromEmpty() {
338 <        final DelayQueue q = new DelayQueue();
339 <        Thread t = new Thread(new Runnable() {
340 <                public void run() {
341 <                    try {
342 <                        q.take();
343 <                        threadShouldThrow();
422 <                    } catch (InterruptedException success){ }                
337 >    public void testBlockingTake() throws InterruptedException {
338 >        final DelayQueue q = populatedQueue(SIZE);
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                  }
424            });
425        try {
426            t.start();
427            Thread.sleep(SHORT_DELAY_MS);
428            t.interrupt();
429            t.join();
430        } catch (Exception e){
431            unexpectedException();
432        }
433    }
345  
346 <    /**
347 <     *
348 <     */
349 <    public void testBlockingTake() {
350 <        Thread t = new Thread(new Runnable() {
351 <                public void run() {
352 <                    try {
353 <                        DelayQueue q = populatedQueue(SIZE);
354 <                        for (int i = 0; i < SIZE; ++i) {
355 <                            threadAssertEquals(new PDelay(i), ((PDelay)q.take()));
356 <                        }
357 <                        q.take();
358 <                        threadShouldThrow();
359 <                    } catch (InterruptedException success){
449 <                    }  
450 <                }});
451 <        t.start();
452 <        try {
453 <           Thread.sleep(SHORT_DELAY_MS);
454 <           t.interrupt();
455 <           t.join();
456 <        }
457 <        catch (InterruptedException ie) {
458 <            unexpectedException();
459 <        }
460 <    }
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 +        await(pleaseInterrupt);
362 +        assertThreadStaysAlive(t);
363 +        t.interrupt();
364 +        awaitTermination(t);
365 +    }
366  
367      /**
368 <     *
368 >     * poll succeeds unless empty
369       */
370      public void testPoll() {
371          DelayQueue q = populatedQueue(SIZE);
372          for (int i = 0; i < SIZE; ++i) {
373              assertEquals(new PDelay(i), ((PDelay)q.poll()));
374          }
375 <        assertNull(q.poll());
375 >        assertNull(q.poll());
376      }
377  
378      /**
379 <     *
379 >     * timed poll with zero timeout succeeds when non-empty, else times out
380       */
381 <    public void testTimedPoll0() {
382 <        try {
383 <            DelayQueue q = populatedQueue(SIZE);
384 <            for (int i = 0; i < SIZE; ++i) {
385 <                assertEquals(new PDelay(i), ((PDelay)q.poll(0, TimeUnit.MILLISECONDS)));
386 <            }
483 <            assertNull(q.poll(0, TimeUnit.MILLISECONDS));
484 <        } catch (InterruptedException e){
485 <            unexpectedException();
486 <        }  
381 >    public void testTimedPoll0() throws InterruptedException {
382 >        DelayQueue q = populatedQueue(SIZE);
383 >        for (int i = 0; i < SIZE; ++i) {
384 >            assertEquals(new PDelay(i), ((PDelay)q.poll(0, MILLISECONDS)));
385 >        }
386 >        assertNull(q.poll(0, MILLISECONDS));
387      }
388  
389      /**
390 <     *
390 >     * timed poll with nonzero timeout succeeds when non-empty, else times out
391       */
392 <    public void testTimedPoll() {
393 <        try {
394 <            DelayQueue q = populatedQueue(SIZE);
395 <            for (int i = 0; i < SIZE; ++i) {
396 <                assertEquals(new PDelay(i), ((PDelay)q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS)));
397 <            }
498 <            assertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
499 <        } catch (InterruptedException e){
500 <            unexpectedException();
501 <        }  
502 <    }
503 <
504 <    /**
505 <     *
506 <     */
507 <    public void testInterruptedTimedPoll() {
508 <        Thread t = new Thread(new Runnable() {
509 <                public void run() {
510 <                    try {
511 <                        DelayQueue q = populatedQueue(SIZE);
512 <                        for (int i = 0; i < SIZE; ++i) {
513 <                            threadAssertEquals(new PDelay(i), ((PDelay)q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS)));
514 <                        }
515 <                        threadAssertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
516 <                    } catch (InterruptedException success){
517 <                    }  
518 <                }});
519 <        t.start();
520 <        try {
521 <           Thread.sleep(SHORT_DELAY_MS);
522 <           t.interrupt();
523 <           t.join();
524 <        }
525 <        catch (InterruptedException ie) {
526 <            unexpectedException();
392 >    public void testTimedPoll() throws InterruptedException {
393 >        DelayQueue q = populatedQueue(SIZE);
394 >        for (int i = 0; i < SIZE; ++i) {
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      /**
406 <     *
406 >     * Interrupted timed poll throws InterruptedException instead of
407 >     * returning timeout status
408       */
409 <    public void testTimedPollWithOffer() {
410 <        final DelayQueue q = new DelayQueue();
411 <        Thread t = new Thread(new Runnable() {
412 <                public void run() {
413 <                    try {
414 <                        threadAssertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
415 <                        q.poll(LONG_DELAY_MS, TimeUnit.MILLISECONDS);
540 <                        q.poll(LONG_DELAY_MS, TimeUnit.MILLISECONDS);
541 <                        threadFail("Should block");
542 <                    } catch (InterruptedException success) { }                
409 >    public void testInterruptedTimedPoll() throws InterruptedException {
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                  }
544            });
545        try {
546            t.start();
547            Thread.sleep(SMALL_DELAY_MS);
548            assertTrue(q.offer(new PDelay(0), SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
549            t.interrupt();
550            t.join();
551        } catch (Exception e){
552            unexpectedException();
553        }
554    }  
417  
418 +                Thread.currentThread().interrupt();
419 +                try {
420 +                    q.poll(LONG_DELAY_MS, MILLISECONDS);
421 +                    shouldThrow();
422 +                } catch (InterruptedException success) {}
423 +                assertFalse(Thread.interrupted());
424 +
425 +                pleaseInterrupt.countDown();
426 +                try {
427 +                    q.poll(LONG_DELAY_MS, MILLISECONDS);
428 +                    shouldThrow();
429 +                } catch (InterruptedException success) {}
430 +                assertFalse(Thread.interrupted());
431 +            }});
432 +
433 +        await(pleaseInterrupt);
434 +        assertThreadStaysAlive(t);
435 +        t.interrupt();
436 +        awaitTermination(t);
437 +    }
438  
439      /**
440 <     *
440 >     * peek returns next element, or null if empty
441       */
442      public void testPeek() {
443          DelayQueue q = populatedQueue(SIZE);
444          for (int i = 0; i < SIZE; ++i) {
445              assertEquals(new PDelay(i), ((PDelay)q.peek()));
446 <            q.poll();
447 <            assertTrue(q.peek() == null ||
448 <                       i != ((PDelay)q.peek()).intValue());
446 >            assertEquals(new PDelay(i), ((PDelay)q.poll()));
447 >            if (q.isEmpty())
448 >                assertNull(q.peek());
449 >            else
450 >                assertFalse(new PDelay(i).equals(q.peek()));
451          }
452 <        assertNull(q.peek());
452 >        assertNull(q.peek());
453      }
454  
455      /**
456 <     *
456 >     * element returns next element, or throws NSEE if empty
457       */
458      public void testElement() {
459          DelayQueue q = populatedQueue(SIZE);
# Line 580 | Line 464 | public class DelayQueueTest extends JSR1
464          try {
465              q.element();
466              shouldThrow();
467 <        }
584 <        catch (NoSuchElementException success) {}
467 >        } catch (NoSuchElementException success) {}
468      }
469  
470      /**
471 <     *
471 >     * remove removes next element, or throws NSEE if empty
472       */
473      public void testRemove() {
474          DelayQueue q = populatedQueue(SIZE);
# Line 595 | Line 478 | public class DelayQueueTest extends JSR1
478          try {
479              q.remove();
480              shouldThrow();
481 <        } catch (NoSuchElementException success){
599 <        }  
481 >        } catch (NoSuchElementException success) {}
482      }
483  
484      /**
485 <     *
604 <     */
605 <    public void testRemoveElement() {
606 <        DelayQueue q = populatedQueue(SIZE);
607 <        for (int i = 1; i < SIZE; i+=2) {
608 <            assertTrue(q.remove(new PDelay(i)));
609 <        }
610 <        for (int i = 0; i < SIZE; i+=2) {
611 <            assertTrue(q.remove(new PDelay(i)));
612 <            assertFalse(q.remove(new PDelay(i+1)));
613 <        }
614 <        assertTrue(q.isEmpty());
615 <    }
616 <        
617 <    /**
618 <     *
485 >     * contains(x) reports true when elements added but not yet removed
486       */
487      public void testContains() {
488          DelayQueue q = populatedQueue(SIZE);
# Line 627 | Line 494 | public class DelayQueueTest extends JSR1
494      }
495  
496      /**
497 <     *
497 >     * clear removes all elements
498       */
499      public void testClear() {
500          DelayQueue q = populatedQueue(SIZE);
# Line 635 | Line 502 | public class DelayQueueTest extends JSR1
502          assertTrue(q.isEmpty());
503          assertEquals(0, q.size());
504          assertEquals(NOCAP, q.remainingCapacity());
505 <        q.add(new PDelay(1));
505 >        PDelay x = new PDelay(1);
506 >        q.add(x);
507          assertFalse(q.isEmpty());
508 +        assertTrue(q.contains(x));
509          q.clear();
510          assertTrue(q.isEmpty());
511      }
512  
513      /**
514 <     *
514 >     * containsAll(c) is true when c contains a subset of elements
515       */
516      public void testContainsAll() {
517          DelayQueue q = populatedQueue(SIZE);
# Line 656 | Line 525 | public class DelayQueueTest extends JSR1
525      }
526  
527      /**
528 <     *
528 >     * retainAll(c) retains only those elements of c and reports true if changed
529       */
530      public void testRetainAll() {
531          DelayQueue q = populatedQueue(SIZE);
# Line 675 | Line 544 | public class DelayQueueTest extends JSR1
544      }
545  
546      /**
547 <     *
547 >     * removeAll(c) removes only those elements of c and reports true if changed
548       */
549      public void testRemoveAll() {
550          for (int i = 1; i < SIZE; ++i) {
# Line 691 | Line 560 | public class DelayQueueTest extends JSR1
560      }
561  
562      /**
563 <     *
563 >     * toArray contains all elements
564       */
565 <    public void testToArray() {
565 >    public void testToArray() throws InterruptedException {
566          DelayQueue q = populatedQueue(SIZE);
567 <        Object[] o = q.toArray();
567 >        Object[] o = q.toArray();
568          Arrays.sort(o);
569 <        try {
570 <        for(int i = 0; i < o.length; i++)
702 <            assertEquals(o[i], q.take());
703 <        } catch (InterruptedException e){
704 <            unexpectedException();
705 <        }    
569 >        for (int i = 0; i < o.length; i++)
570 >            assertSame(o[i], q.take());
571      }
572  
573      /**
574 <     *
574 >     * toArray(a) contains all elements
575       */
576      public void testToArray2() {
577 <        DelayQueue q = populatedQueue(SIZE);
578 <        PDelay[] ints = new PDelay[SIZE];
579 <        ints = (PDelay[])q.toArray(ints);
577 >        DelayQueue<PDelay> q = populatedQueue(SIZE);
578 >        PDelay[] ints = new PDelay[SIZE];
579 >        PDelay[] array = q.toArray(ints);
580 >        assertSame(ints, array);
581          Arrays.sort(ints);
582 <        try {
583 <            for(int i = 0; i < ints.length; i++)
584 <                assertEquals(ints[i], q.take());
585 <        } catch (InterruptedException e){
586 <            unexpectedException();
587 <        }    
582 >        for (int i = 0; i < ints.length; i++)
583 >            assertSame(ints[i], q.remove());
584 >    }
585 >
586 >    /**
587 >     * toArray(incompatible array type) throws ArrayStoreException
588 >     */
589 >    public void testToArray1_BadArg() {
590 >        DelayQueue q = populatedQueue(SIZE);
591 >        try {
592 >            q.toArray(new String[10]);
593 >            shouldThrow();
594 >        } catch (ArrayStoreException success) {}
595      }
596 <    
596 >
597      /**
598 <     *
598 >     * iterator iterates through all elements
599       */
600      public void testIterator() {
601          DelayQueue q = populatedQueue(SIZE);
602          int i = 0;
603 <        Iterator it = q.iterator();
604 <        while(it.hasNext()) {
603 >        Iterator it = q.iterator();
604 >        while (it.hasNext()) {
605              assertTrue(q.contains(it.next()));
606              ++i;
607          }
# Line 736 | Line 609 | public class DelayQueueTest extends JSR1
609      }
610  
611      /**
612 <     *
612 >     * iterator.remove removes current element
613       */
614 <    public void testIteratorRemove () {
742 <
614 >    public void testIteratorRemove() {
615          final DelayQueue q = new DelayQueue();
744
616          q.add(new PDelay(2));
617          q.add(new PDelay(1));
618          q.add(new PDelay(3));
748
619          Iterator it = q.iterator();
620          it.next();
621          it.remove();
752
622          it = q.iterator();
623          assertEquals(it.next(), new PDelay(2));
624          assertEquals(it.next(), new PDelay(3));
625          assertFalse(it.hasNext());
626      }
627  
759
628      /**
629 <     *
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);
636 <        }
769 <    }        
634 >        for (Object e : q)
635 >            assertTrue(s.contains(e.toString()));
636 >    }
637  
638      /**
639 <     *
639 >     * timed poll transfers elements across Executor tasks
640       */
641      public void testPollInExecutor() {
775
642          final DelayQueue q = new DelayQueue();
643 <
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 +                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 +                threadsStarted.await();
656 +                q.put(new PDelay(1));
657 +            }});
658  
780        executor.execute(new Runnable() {
781            public void run() {
782                threadAssertNull(q.poll());
783                try {
784                    threadAssertTrue(null != q.poll(MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS));
785                    threadAssertTrue(q.isEmpty());
786                }
787                catch (InterruptedException e) {
788                    threadUnexpectedException();
789                }
790            }
791        });
792
793        executor.execute(new Runnable() {
794            public void run() {
795                try {
796                    Thread.sleep(SHORT_DELAY_MS);
797                    q.put(new PDelay(1));
798                }
799                catch (InterruptedException e) {
800                    threadUnexpectedException();
801                }
802            }
803        });
804        
659          joinPool(executor);
660 +    }
661  
662 +    /**
663 +     * Delayed actions do not occur until their delay elapses
664 +     */
665 +    public void testDelay() throws InterruptedException {
666 +        DelayQueue<NanoDelay> q = new DelayQueue<NanoDelay>();
667 +        for (int i = 0; i < SIZE; ++i)
668 +            q.add(new NanoDelay(1000000L * (SIZE - i)));
669 +
670 +        long last = 0;
671 +        for (int i = 0; i < SIZE; ++i) {
672 +            NanoDelay e = q.take();
673 +            long tt = e.getTriggerTime();
674 +            assertTrue(System.nanoTime() - tt >= 0);
675 +            if (i != 0)
676 +                assertTrue(tt >= last);
677 +            last = tt;
678 +        }
679 +        assertTrue(q.isEmpty());
680      }
681  
682 +    /**
683 +     * peek of a non-empty queue returns non-null even if not expired
684 +     */
685 +    public void testPeekDelayed() {
686 +        DelayQueue q = new DelayQueue();
687 +        q.add(new NanoDelay(Long.MAX_VALUE));
688 +        assertNotNull(q.peek());
689 +    }
690  
691      /**
692 <     *
692 >     * poll of a non-empty queue returns null if no expired elements.
693       */
694 <    public void testDelay() {
694 >    public void testPollDelayed() {
695          DelayQueue q = new DelayQueue();
696 <        NanoDelay[] elements = new NanoDelay[SIZE];
697 <        for (int i = 0; i < SIZE; ++i) {
698 <            elements[i] = new NanoDelay(1000000000L + 1000000L * (SIZE - i));
699 <        }
696 >        q.add(new NanoDelay(Long.MAX_VALUE));
697 >        assertNull(q.poll());
698 >    }
699 >
700 >    /**
701 >     * timed poll of a non-empty queue returns null if no expired elements.
702 >     */
703 >    public void testTimedPollDelayed() throws InterruptedException {
704 >        DelayQueue q = new DelayQueue();
705 >        q.add(new NanoDelay(LONG_DELAY_MS * 1000000L));
706 >        assertNull(q.poll(timeoutMillis(), MILLISECONDS));
707 >    }
708 >
709 >    /**
710 >     * drainTo(c) empties queue into another collection c
711 >     */
712 >    public void testDrainTo() {
713 >        DelayQueue q = new DelayQueue();
714 >        PDelay[] elems = new PDelay[SIZE];
715          for (int i = 0; i < SIZE; ++i) {
716 <            q.add(elements[i]);
716 >            elems[i] = new PDelay(i);
717 >            q.add(elems[i]);
718          }
719 +        ArrayList l = new ArrayList();
720 +        q.drainTo(l);
721 +        assertEquals(q.size(), 0);
722 +        for (int i = 0; i < SIZE; ++i)
723 +            assertEquals(l.get(i), elems[i]);
724 +        q.add(elems[0]);
725 +        q.add(elems[1]);
726 +        assertFalse(q.isEmpty());
727 +        assertTrue(q.contains(elems[0]));
728 +        assertTrue(q.contains(elems[1]));
729 +        l.clear();
730 +        q.drainTo(l);
731 +        assertEquals(q.size(), 0);
732 +        assertEquals(l.size(), 2);
733 +        for (int i = 0; i < 2; ++i)
734 +            assertEquals(l.get(i), elems[i]);
735 +    }
736  
737 <        try {
738 <            long last = 0;
739 <            for (int i = 0; i < SIZE; ++i) {
740 <                NanoDelay e = (NanoDelay)(q.take());
741 <                long tt = e.getTriggerTime();
742 <                assertTrue(tt <= System.nanoTime());
743 <                if (i != 0)
744 <                    assertTrue(tt >= last);
745 <                last = tt;
746 <            }
747 <        }
748 <        catch(InterruptedException ie) {
749 <            unexpectedException();
737 >    /**
738 >     * drainTo empties queue
739 >     */
740 >    public void testDrainToWithActivePut() throws InterruptedException {
741 >        final DelayQueue q = populatedQueue(SIZE);
742 >        Thread t = new Thread(new CheckedRunnable() {
743 >            public void realRun() {
744 >                q.put(new PDelay(SIZE+1));
745 >            }});
746 >
747 >        t.start();
748 >        ArrayList l = new ArrayList();
749 >        q.drainTo(l);
750 >        assertTrue(l.size() >= SIZE);
751 >        t.join();
752 >        assertTrue(q.size() + l.size() >= SIZE);
753 >    }
754 >
755 >    /**
756 >     * drainTo(c, n) empties first min(n, size) elements of queue into c
757 >     */
758 >    public void testDrainToN() {
759 >        for (int i = 0; i < SIZE + 2; ++i) {
760 >            DelayQueue q = populatedQueue(SIZE);
761 >            ArrayList l = new ArrayList();
762 >            q.drainTo(l, i);
763 >            int k = (i < SIZE) ? i : SIZE;
764 >            assertEquals(q.size(), SIZE-k);
765 >            assertEquals(l.size(), k);
766          }
767      }
768  

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines