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.16 by jsr166, Mon Nov 16 04:57:10 2009 UTC vs.
Revision 1.78 by jsr166, Sun Oct 16 20:44:18 2016 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.*;
11 < import java.util.concurrent.*;
9 > import static java.util.concurrent.TimeUnit.MILLISECONDS;
10 >
11 > import java.util.ArrayList;
12 > import java.util.Arrays;
13 > import java.util.Collection;
14 > import java.util.Iterator;
15 > import java.util.NoSuchElementException;
16 > import java.util.concurrent.BlockingQueue;
17 > import java.util.concurrent.CountDownLatch;
18 > import java.util.concurrent.Delayed;
19 > import java.util.concurrent.DelayQueue;
20 > import java.util.concurrent.Executors;
21 > import java.util.concurrent.ExecutorService;
22 > import java.util.concurrent.TimeUnit;
23 >
24 > import junit.framework.Test;
25  
26   public class DelayQueueTest extends JSR166TestCase {
27 +
28 +    public static class Generic extends BlockingQueueTest {
29 +        protected BlockingQueue emptyCollection() {
30 +            return new DelayQueue();
31 +        }
32 +        protected PDelay makeElement(int i) {
33 +            return new PDelay(i);
34 +        }
35 +    }
36 +
37      public static void main(String[] args) {
38 <        junit.textui.TestRunner.run (suite());
38 >        main(suite(), args);
39      }
40  
41      public static Test suite() {
42 <        return new TestSuite(DelayQueueTest.class);
42 >        return newTestSuite(DelayQueueTest.class,
43 >                            new Generic().testSuite());
44      }
45  
22    private static final int NOCAP = Integer.MAX_VALUE;
23
46      /**
47       * A delayed implementation for testing.
48 <     * Most  tests use Pseudodelays, where delays are all elapsed
48 >     * Most tests use Pseudodelays, where delays are all elapsed
49       * (so, no blocking solely for delays) but are still ordered
50       */
51      static class PDelay implements Delayed {
52          int pseudodelay;
53 <        PDelay(int i) { pseudodelay = Integer.MIN_VALUE + i; }
54 <        public int compareTo(PDelay y) {
55 <            int i = pseudodelay;
56 <            int j = ((PDelay)y).pseudodelay;
57 <            if (i < j) return -1;
36 <            if (i > j) return 1;
37 <            return 0;
53 >        PDelay(int i) { pseudodelay = i; }
54 >        public int compareTo(PDelay other) {
55 >            int a = this.pseudodelay;
56 >            int b = other.pseudodelay;
57 >            return (a < b) ? -1 : (a > b) ? 1 : 0;
58          }
39
59          public int compareTo(Delayed y) {
60 <            int i = pseudodelay;
42 <            int j = ((PDelay)y).pseudodelay;
43 <            if (i < j) return -1;
44 <            if (i > j) return 1;
45 <            return 0;
60 >            return compareTo((PDelay)y);
61          }
47
62          public boolean equals(Object other) {
63 <            return ((PDelay)other).pseudodelay == pseudodelay;
64 <        }
51 <        public boolean equals(PDelay other) {
52 <            return ((PDelay)other).pseudodelay == pseudodelay;
63 >            return (other instanceof PDelay) &&
64 >                this.pseudodelay == ((PDelay)other).pseudodelay;
65          }
66 <
67 <
66 >        // suppress [overrides] javac warning
67 >        public int hashCode() { return pseudodelay; }
68          public long getDelay(TimeUnit ignore) {
69 <            return pseudodelay;
69 >            return Integer.MIN_VALUE + pseudodelay;
70          }
59        public int intValue() {
60            return pseudodelay;
61        }
62
71          public String toString() {
72              return String.valueOf(pseudodelay);
73          }
74      }
75  
68
76      /**
77       * Delayed implementation that actually delays
78       */
# Line 76 | Line 83 | public class DelayQueueTest extends JSR1
83          }
84          public int compareTo(NanoDelay y) {
85              long i = trigger;
86 <            long j = ((NanoDelay)y).trigger;
86 >            long j = y.trigger;
87              if (i < j) return -1;
88              if (i > j) return 1;
89              return 0;
90          }
91  
92          public int compareTo(Delayed y) {
93 <            long i = trigger;
87 <            long j = ((NanoDelay)y).trigger;
88 <            if (i < j) return -1;
89 <            if (i > j) return 1;
90 <            return 0;
93 >            return compareTo((NanoDelay)y);
94          }
95  
96          public boolean equals(Object other) {
97 <            return ((NanoDelay)other).trigger == trigger;
98 <        }
96 <        public boolean equals(NanoDelay other) {
97 <            return ((NanoDelay)other).trigger == trigger;
97 >            return (other instanceof NanoDelay) &&
98 >                this.trigger == ((NanoDelay)other).trigger;
99          }
100  
101 +        // suppress [overrides] javac warning
102 +        public int hashCode() { return (int) trigger; }
103 +
104          public long getDelay(TimeUnit unit) {
105              long n = trigger - System.nanoTime();
106              return unit.convert(n, TimeUnit.NANOSECONDS);
# Line 111 | Line 115 | public class DelayQueueTest extends JSR1
115          }
116      }
117  
114
118      /**
119 <     * Create a queue of given size containing consecutive
120 <     * PDelays 0 ... n.
119 >     * Returns a new queue of given size containing consecutive
120 >     * PDelays 0 ... n - 1.
121       */
122 <    private DelayQueue populatedQueue(int n) {
123 <        DelayQueue q = new DelayQueue();
122 >    private DelayQueue<PDelay> populatedQueue(int n) {
123 >        DelayQueue<PDelay> q = new DelayQueue<PDelay>();
124          assertTrue(q.isEmpty());
125 <        for (int i = n-1; i >= 0; i-=2)
126 <            assertTrue(q.offer(new PDelay(i)));
127 <        for (int i = (n & 1); i < n; i+=2)
128 <            assertTrue(q.offer(new PDelay(i)));
125 >        for (int i = n - 1; i >= 0; i -= 2)
126 >            assertTrue(q.offer(new PDelay(i)));
127 >        for (int i = (n & 1); i < n; i += 2)
128 >            assertTrue(q.offer(new PDelay(i)));
129          assertFalse(q.isEmpty());
130 <        assertEquals(NOCAP, q.remainingCapacity());
131 <        assertEquals(n, q.size());
130 >        assertEquals(Integer.MAX_VALUE, q.remainingCapacity());
131 >        assertEquals(n, q.size());
132 >        assertEquals(new PDelay(0), q.peek());
133          return q;
134      }
135  
# Line 133 | Line 137 | public class DelayQueueTest extends JSR1
137       * A new queue has unbounded capacity
138       */
139      public void testConstructor1() {
140 <        assertEquals(NOCAP, new DelayQueue().remainingCapacity());
140 >        assertEquals(Integer.MAX_VALUE, new DelayQueue().remainingCapacity());
141      }
142  
143      /**
# Line 141 | Line 145 | public class DelayQueueTest extends JSR1
145       */
146      public void testConstructor3() {
147          try {
148 <            DelayQueue q = new DelayQueue(null);
148 >            new DelayQueue(null);
149              shouldThrow();
150 <        }
147 <        catch (NullPointerException success) {}
150 >        } catch (NullPointerException success) {}
151      }
152  
153      /**
# Line 152 | Line 155 | public class DelayQueueTest extends JSR1
155       */
156      public void testConstructor4() {
157          try {
158 <            PDelay[] ints = new PDelay[SIZE];
156 <            DelayQueue q = new DelayQueue(Arrays.asList(ints));
158 >            new DelayQueue(Arrays.asList(new PDelay[SIZE]));
159              shouldThrow();
160 <        }
159 <        catch (NullPointerException success) {}
160 >        } catch (NullPointerException success) {}
161      }
162  
163      /**
164       * Initializing from Collection with some null elements throws NPE
165       */
166      public void testConstructor5() {
167 +        PDelay[] a = new PDelay[SIZE];
168 +        for (int i = 0; i < SIZE - 1; ++i)
169 +            a[i] = new PDelay(i);
170          try {
171 <            PDelay[] ints = new PDelay[SIZE];
168 <            for (int i = 0; i < SIZE-1; ++i)
169 <                ints[i] = new PDelay(i);
170 <            DelayQueue q = new DelayQueue(Arrays.asList(ints));
171 >            new DelayQueue(Arrays.asList(a));
172              shouldThrow();
173 <        }
173 <        catch (NullPointerException success) {}
173 >        } catch (NullPointerException success) {}
174      }
175  
176      /**
177       * Queue contains all elements of collection used to initialize
178       */
179      public void testConstructor6() {
180 <        try {
181 <            PDelay[] ints = new PDelay[SIZE];
182 <            for (int i = 0; i < SIZE; ++i)
183 <                ints[i] = new PDelay(i);
184 <            DelayQueue q = new DelayQueue(Arrays.asList(ints));
185 <            for (int i = 0; i < SIZE; ++i)
186 <                assertEquals(ints[i], q.poll());
187 <        }
188 <        finally {}
180 >        PDelay[] ints = new PDelay[SIZE];
181 >        for (int i = 0; i < SIZE; ++i)
182 >            ints[i] = new PDelay(i);
183 >        DelayQueue q = new DelayQueue(Arrays.asList(ints));
184 >        for (int i = 0; i < SIZE; ++i)
185 >            assertEquals(ints[i], q.poll());
186      }
187  
188      /**
# Line 194 | Line 191 | public class DelayQueueTest extends JSR1
191      public void testEmpty() {
192          DelayQueue q = new DelayQueue();
193          assertTrue(q.isEmpty());
194 <        assertEquals(NOCAP, q.remainingCapacity());
194 >        assertEquals(Integer.MAX_VALUE, q.remainingCapacity());
195          q.add(new PDelay(1));
196          assertFalse(q.isEmpty());
197          q.add(new PDelay(2));
# Line 204 | Line 201 | public class DelayQueueTest extends JSR1
201      }
202  
203      /**
204 <     * remainingCapacity does not change when elementa added or removed,
208 <     * but size does
204 >     * remainingCapacity() always returns Integer.MAX_VALUE
205       */
206      public void testRemainingCapacity() {
207 <        DelayQueue q = populatedQueue(SIZE);
207 >        BlockingQueue q = populatedQueue(SIZE);
208          for (int i = 0; i < SIZE; ++i) {
209 <            assertEquals(NOCAP, q.remainingCapacity());
210 <            assertEquals(SIZE-i, q.size());
211 <            q.remove();
209 >            assertEquals(Integer.MAX_VALUE, q.remainingCapacity());
210 >            assertEquals(SIZE - i, q.size());
211 >            assertTrue(q.remove() instanceof PDelay);
212          }
213          for (int i = 0; i < SIZE; ++i) {
214 <            assertEquals(NOCAP, q.remainingCapacity());
214 >            assertEquals(Integer.MAX_VALUE, q.remainingCapacity());
215              assertEquals(i, q.size());
216 <            q.add(new PDelay(i));
216 >            assertTrue(q.add(new PDelay(i)));
217          }
218      }
219  
220      /**
225     * offer(null) throws NPE
226     */
227    public void testOfferNull() {
228        try {
229            DelayQueue q = new DelayQueue();
230            q.offer(null);
231            shouldThrow();
232        } catch (NullPointerException success) { }
233    }
234
235    /**
236     * add(null) throws NPE
237     */
238    public void testAddNull() {
239        try {
240            DelayQueue q = new DelayQueue();
241            q.add(null);
242            shouldThrow();
243        } catch (NullPointerException success) { }
244    }
245
246    /**
221       * offer non-null succeeds
222       */
223      public void testOffer() {
# Line 264 | Line 238 | public class DelayQueueTest extends JSR1
238      }
239  
240      /**
267     * addAll(null) throws NPE
268     */
269    public void testAddAll1() {
270        try {
271            DelayQueue q = new DelayQueue();
272            q.addAll(null);
273            shouldThrow();
274        }
275        catch (NullPointerException success) {}
276    }
277
278
279    /**
241       * addAll(this) throws IAE
242       */
243      public void testAddAllSelf() {
244 +        DelayQueue q = populatedQueue(SIZE);
245          try {
284            DelayQueue q = populatedQueue(SIZE);
246              q.addAll(q);
247              shouldThrow();
248 <        }
288 <        catch (IllegalArgumentException success) {}
248 >        } catch (IllegalArgumentException success) {}
249      }
250  
251      /**
292     * addAll of a collection with null elements throws NPE
293     */
294    public void testAddAll2() {
295        try {
296            DelayQueue q = new DelayQueue();
297            PDelay[] ints = new PDelay[SIZE];
298            q.addAll(Arrays.asList(ints));
299            shouldThrow();
300        }
301        catch (NullPointerException success) {}
302    }
303    /**
252       * addAll of a collection with any null elements throws NPE after
253       * possibly adding some elements
254       */
255      public void testAddAll3() {
256 +        DelayQueue q = new DelayQueue();
257 +        PDelay[] a = new PDelay[SIZE];
258 +        for (int i = 0; i < SIZE - 1; ++i)
259 +            a[i] = new PDelay(i);
260          try {
261 <            DelayQueue q = new DelayQueue();
310 <            PDelay[] ints = new PDelay[SIZE];
311 <            for (int i = 0; i < SIZE-1; ++i)
312 <                ints[i] = new PDelay(i);
313 <            q.addAll(Arrays.asList(ints));
261 >            q.addAll(Arrays.asList(a));
262              shouldThrow();
263 <        }
316 <        catch (NullPointerException success) {}
263 >        } catch (NullPointerException success) {}
264      }
265  
266      /**
267       * Queue contains all elements of successful addAll
268       */
269      public void testAddAll5() {
270 <        try {
271 <            PDelay[] empty = new PDelay[0];
272 <            PDelay[] ints = new PDelay[SIZE];
273 <            for (int i = SIZE-1; i >= 0; --i)
274 <                ints[i] = new PDelay(i);
275 <            DelayQueue q = new DelayQueue();
276 <            assertFalse(q.addAll(Arrays.asList(empty)));
277 <            assertTrue(q.addAll(Arrays.asList(ints)));
278 <            for (int i = 0; i < SIZE; ++i)
332 <                assertEquals(ints[i], q.poll());
333 <        }
334 <        finally {}
270 >        PDelay[] empty = new PDelay[0];
271 >        PDelay[] ints = new PDelay[SIZE];
272 >        for (int i = SIZE - 1; i >= 0; --i)
273 >            ints[i] = new PDelay(i);
274 >        DelayQueue q = new DelayQueue();
275 >        assertFalse(q.addAll(Arrays.asList(empty)));
276 >        assertTrue(q.addAll(Arrays.asList(ints)));
277 >        for (int i = 0; i < SIZE; ++i)
278 >            assertEquals(ints[i], q.poll());
279      }
280  
281      /**
338     * put(null) throws NPE
339     */
340     public void testPutNull() {
341        try {
342            DelayQueue q = new DelayQueue();
343            q.put(null);
344            shouldThrow();
345        }
346        catch (NullPointerException success){
347        }
348     }
349
350    /**
282       * all elements successfully put are contained
283       */
284 <     public void testPut() {
285 <         try {
286 <             DelayQueue q = new DelayQueue();
287 <             for (int i = 0; i < SIZE; ++i) {
288 <                 PDelay I = new PDelay(i);
289 <                 q.put(I);
359 <                 assertTrue(q.contains(I));
360 <             }
361 <             assertEquals(SIZE, q.size());
362 <         }
363 <         finally {
284 >    public void testPut() {
285 >        DelayQueue q = new DelayQueue();
286 >        for (int i = 0; i < SIZE; ++i) {
287 >            PDelay x = new PDelay(i);
288 >            q.put(x);
289 >            assertTrue(q.contains(x));
290          }
291 +        assertEquals(SIZE, q.size());
292      }
293  
294      /**
295       * put doesn't block waiting for take
296       */
297 <    public void testPutWithTake() {
297 >    public void testPutWithTake() throws InterruptedException {
298          final DelayQueue q = new DelayQueue();
299 <        Thread t = new Thread(new Runnable() {
300 <                public void run() {
301 <                    int added = 0;
302 <                    try {
303 <                        q.put(new PDelay(0));
304 <                        ++added;
305 <                        q.put(new PDelay(0));
306 <                        ++added;
307 <                        q.put(new PDelay(0));
308 <                        ++added;
382 <                        q.put(new PDelay(0));
383 <                        ++added;
384 <                        threadAssertTrue(added == 4);
385 <                    } finally {
386 <                    }
387 <                }
388 <            });
389 <        try {
390 <            t.start();
391 <            Thread.sleep(SHORT_DELAY_MS);
392 <            q.take();
393 <            t.interrupt();
394 <            t.join();
395 <        } catch (Exception e){
396 <            unexpectedException();
397 <        }
299 >        Thread t = newStartedThread(new CheckedRunnable() {
300 >            public void realRun() {
301 >                q.put(new PDelay(0));
302 >                q.put(new PDelay(0));
303 >                q.put(new PDelay(0));
304 >                q.put(new PDelay(0));
305 >            }});
306 >
307 >        awaitTermination(t);
308 >        assertEquals(4, q.size());
309      }
310  
311      /**
312       * timed offer does not time out
313       */
314 <    public void testTimedOffer() {
314 >    public void testTimedOffer() throws InterruptedException {
315          final DelayQueue q = new DelayQueue();
316 <        Thread t = new Thread(new Runnable() {
317 <                public void run() {
318 <                    try {
319 <                        q.put(new PDelay(0));
320 <                        q.put(new PDelay(0));
321 <                        threadAssertTrue(q.offer(new PDelay(0), SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
322 <                        threadAssertTrue(q.offer(new PDelay(0), LONG_DELAY_MS, TimeUnit.MILLISECONDS));
412 <                    } finally { }
413 <                }
414 <            });
316 >        Thread t = newStartedThread(new CheckedRunnable() {
317 >            public void realRun() throws InterruptedException {
318 >                q.put(new PDelay(0));
319 >                q.put(new PDelay(0));
320 >                assertTrue(q.offer(new PDelay(0), SHORT_DELAY_MS, MILLISECONDS));
321 >                assertTrue(q.offer(new PDelay(0), LONG_DELAY_MS, MILLISECONDS));
322 >            }});
323  
324 <        try {
417 <            t.start();
418 <            Thread.sleep(SMALL_DELAY_MS);
419 <            t.interrupt();
420 <            t.join();
421 <        } catch (Exception e){
422 <            unexpectedException();
423 <        }
324 >        awaitTermination(t);
325      }
326  
327      /**
328       * take retrieves elements in priority order
329       */
330 <    public void testTake() {
331 <        try {
332 <            DelayQueue q = populatedQueue(SIZE);
333 <            for (int i = 0; i < SIZE; ++i) {
433 <                assertEquals(new PDelay(i), ((PDelay)q.take()));
434 <            }
435 <        } catch (InterruptedException e){
436 <            unexpectedException();
437 <        }
438 <    }
439 <
440 <    /**
441 <     * take blocks interruptibly when empty
442 <     */
443 <    public void testTakeFromEmpty() {
444 <        final DelayQueue q = new DelayQueue();
445 <        Thread t = new Thread(new Runnable() {
446 <                public void run() {
447 <                    try {
448 <                        q.take();
449 <                        threadShouldThrow();
450 <                    } catch (InterruptedException success){ }
451 <                }
452 <            });
453 <        try {
454 <            t.start();
455 <            Thread.sleep(SHORT_DELAY_MS);
456 <            t.interrupt();
457 <            t.join();
458 <        } catch (Exception e){
459 <            unexpectedException();
330 >    public void testTake() throws InterruptedException {
331 >        DelayQueue q = populatedQueue(SIZE);
332 >        for (int i = 0; i < SIZE; ++i) {
333 >            assertEquals(new PDelay(i), q.take());
334          }
335      }
336  
337      /**
338       * Take removes existing elements until empty, then blocks interruptibly
339       */
340 <    public void testBlockingTake() {
341 <        Thread t = new Thread(new Runnable() {
342 <                public void run() {
343 <                    try {
344 <                        DelayQueue q = populatedQueue(SIZE);
345 <                        for (int i = 0; i < SIZE; ++i) {
346 <                            threadAssertEquals(new PDelay(i), ((PDelay)q.take()));
347 <                        }
348 <                        q.take();
349 <                        threadShouldThrow();
350 <                    } catch (InterruptedException success){
351 <                    }
352 <                }});
353 <        t.start();
354 <        try {
481 <           Thread.sleep(SHORT_DELAY_MS);
482 <           t.interrupt();
483 <           t.join();
484 <        }
485 <        catch (InterruptedException ie) {
486 <            unexpectedException();
487 <        }
488 <    }
340 >    public void testBlockingTake() throws InterruptedException {
341 >        final DelayQueue q = populatedQueue(SIZE);
342 >        final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
343 >        Thread t = newStartedThread(new CheckedRunnable() {
344 >            public void realRun() throws InterruptedException {
345 >                for (int i = 0; i < SIZE; ++i) {
346 >                    assertEquals(new PDelay(i), ((PDelay)q.take()));
347 >                }
348 >
349 >                Thread.currentThread().interrupt();
350 >                try {
351 >                    q.take();
352 >                    shouldThrow();
353 >                } catch (InterruptedException success) {}
354 >                assertFalse(Thread.interrupted());
355  
356 +                pleaseInterrupt.countDown();
357 +                try {
358 +                    q.take();
359 +                    shouldThrow();
360 +                } catch (InterruptedException success) {}
361 +                assertFalse(Thread.interrupted());
362 +            }});
363 +
364 +        await(pleaseInterrupt);
365 +        assertThreadStaysAlive(t);
366 +        t.interrupt();
367 +        awaitTermination(t);
368 +    }
369  
370      /**
371       * poll succeeds unless empty
# Line 494 | Line 373 | public class DelayQueueTest extends JSR1
373      public void testPoll() {
374          DelayQueue q = populatedQueue(SIZE);
375          for (int i = 0; i < SIZE; ++i) {
376 <            assertEquals(new PDelay(i), ((PDelay)q.poll()));
376 >            assertEquals(new PDelay(i), q.poll());
377          }
378 <        assertNull(q.poll());
378 >        assertNull(q.poll());
379      }
380  
381      /**
382 <     * timed pool with zero timeout succeeds when non-empty, else times out
382 >     * timed poll with zero timeout succeeds when non-empty, else times out
383       */
384 <    public void testTimedPoll0() {
385 <        try {
386 <            DelayQueue q = populatedQueue(SIZE);
387 <            for (int i = 0; i < SIZE; ++i) {
388 <                assertEquals(new PDelay(i), ((PDelay)q.poll(0, TimeUnit.MILLISECONDS)));
389 <            }
511 <            assertNull(q.poll(0, TimeUnit.MILLISECONDS));
512 <        } catch (InterruptedException e){
513 <            unexpectedException();
514 <        }
384 >    public void testTimedPoll0() throws InterruptedException {
385 >        DelayQueue q = populatedQueue(SIZE);
386 >        for (int i = 0; i < SIZE; ++i) {
387 >            assertEquals(new PDelay(i), q.poll(0, MILLISECONDS));
388 >        }
389 >        assertNull(q.poll(0, MILLISECONDS));
390      }
391  
392      /**
393 <     * timed pool with nonzero timeout succeeds when non-empty, else times out
393 >     * timed poll with nonzero timeout succeeds when non-empty, else times out
394       */
395 <    public void testTimedPoll() {
396 <        try {
397 <            DelayQueue q = populatedQueue(SIZE);
398 <            for (int i = 0; i < SIZE; ++i) {
399 <                assertEquals(new PDelay(i), ((PDelay)q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS)));
400 <            }
401 <            assertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
402 <        } catch (InterruptedException e){
403 <            unexpectedException();
404 <        }
395 >    public void testTimedPoll() throws InterruptedException {
396 >        DelayQueue q = populatedQueue(SIZE);
397 >        for (int i = 0; i < SIZE; ++i) {
398 >            long startTime = System.nanoTime();
399 >            assertEquals(new PDelay(i), q.poll(LONG_DELAY_MS, MILLISECONDS));
400 >            assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
401 >        }
402 >        long startTime = System.nanoTime();
403 >        assertNull(q.poll(timeoutMillis(), MILLISECONDS));
404 >        assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
405 >        checkEmpty(q);
406      }
407  
408      /**
409       * Interrupted timed poll throws InterruptedException instead of
410       * returning timeout status
411       */
412 <    public void testInterruptedTimedPoll() {
413 <        Thread t = new Thread(new Runnable() {
414 <                public void run() {
415 <                    try {
416 <                        DelayQueue q = populatedQueue(SIZE);
417 <                        for (int i = 0; i < SIZE; ++i) {
418 <                            threadAssertEquals(new PDelay(i), ((PDelay)q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS)));
419 <                        }
420 <                        threadAssertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
545 <                    } catch (InterruptedException success){
546 <                    }
547 <                }});
548 <        t.start();
549 <        try {
550 <           Thread.sleep(SHORT_DELAY_MS);
551 <           t.interrupt();
552 <           t.join();
553 <        }
554 <        catch (InterruptedException ie) {
555 <            unexpectedException();
556 <        }
557 <    }
558 <
559 <    /**
560 <     *  timed poll before a delayed offer fails; after offer succeeds;
561 <     *  on interruption throws
562 <     */
563 <    public void testTimedPollWithOffer() {
564 <        final DelayQueue q = new DelayQueue();
565 <        Thread t = new Thread(new Runnable() {
566 <                public void run() {
567 <                    try {
568 <                        threadAssertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
569 <                        q.poll(LONG_DELAY_MS, TimeUnit.MILLISECONDS);
570 <                        q.poll(LONG_DELAY_MS, TimeUnit.MILLISECONDS);
571 <                        threadFail("Should block");
572 <                    } catch (InterruptedException success) { }
412 >    public void testInterruptedTimedPoll() throws InterruptedException {
413 >        final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
414 >        final DelayQueue q = populatedQueue(SIZE);
415 >        Thread t = newStartedThread(new CheckedRunnable() {
416 >            public void realRun() throws InterruptedException {
417 >                long startTime = System.nanoTime();
418 >                for (int i = 0; i < SIZE; ++i) {
419 >                    assertEquals(new PDelay(i),
420 >                                 ((PDelay)q.poll(LONG_DELAY_MS, MILLISECONDS)));
421                  }
574            });
575        try {
576            t.start();
577            Thread.sleep(SMALL_DELAY_MS);
578            assertTrue(q.offer(new PDelay(0), SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
579            t.interrupt();
580            t.join();
581        } catch (Exception e){
582            unexpectedException();
583        }
584    }
422  
423 +                Thread.currentThread().interrupt();
424 +                try {
425 +                    q.poll(LONG_DELAY_MS, MILLISECONDS);
426 +                    shouldThrow();
427 +                } catch (InterruptedException success) {}
428 +                assertFalse(Thread.interrupted());
429 +
430 +                pleaseInterrupt.countDown();
431 +                try {
432 +                    q.poll(LONG_DELAY_MS, MILLISECONDS);
433 +                    shouldThrow();
434 +                } catch (InterruptedException success) {}
435 +                assertFalse(Thread.interrupted());
436 +                assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
437 +            }});
438 +
439 +        await(pleaseInterrupt);
440 +        assertThreadStaysAlive(t);
441 +        t.interrupt();
442 +        awaitTermination(t);
443 +        checkEmpty(q);
444 +    }
445  
446      /**
447       * peek returns next element, or null if empty
# Line 590 | Line 449 | public class DelayQueueTest extends JSR1
449      public void testPeek() {
450          DelayQueue q = populatedQueue(SIZE);
451          for (int i = 0; i < SIZE; ++i) {
452 <            assertEquals(new PDelay(i), ((PDelay)q.peek()));
453 <            q.poll();
452 >            assertEquals(new PDelay(i), q.peek());
453 >            assertEquals(new PDelay(i), q.poll());
454              if (q.isEmpty())
455                  assertNull(q.peek());
456              else
457 <                assertTrue(i != ((PDelay)q.peek()).intValue());
457 >                assertFalse(new PDelay(i).equals(q.peek()));
458          }
459 <        assertNull(q.peek());
459 >        assertNull(q.peek());
460      }
461  
462      /**
# Line 606 | Line 465 | public class DelayQueueTest extends JSR1
465      public void testElement() {
466          DelayQueue q = populatedQueue(SIZE);
467          for (int i = 0; i < SIZE; ++i) {
468 <            assertEquals(new PDelay(i), ((PDelay)q.element()));
468 >            assertEquals(new PDelay(i), q.element());
469              q.poll();
470          }
471          try {
472              q.element();
473              shouldThrow();
474 <        }
616 <        catch (NoSuchElementException success) {}
474 >        } catch (NoSuchElementException success) {}
475      }
476  
477      /**
# Line 622 | Line 480 | public class DelayQueueTest extends JSR1
480      public void testRemove() {
481          DelayQueue q = populatedQueue(SIZE);
482          for (int i = 0; i < SIZE; ++i) {
483 <            assertEquals(new PDelay(i), ((PDelay)q.remove()));
483 >            assertEquals(new PDelay(i), q.remove());
484          }
485          try {
486              q.remove();
487              shouldThrow();
488 <        } catch (NoSuchElementException success){
631 <        }
632 <    }
633 <
634 <    /**
635 <     * remove(x) removes x and returns true if present
636 <     */
637 <    public void testRemoveElement() {
638 <        DelayQueue q = populatedQueue(SIZE);
639 <        for (int i = 1; i < SIZE; i+=2) {
640 <            assertTrue(q.remove(new PDelay(i)));
641 <        }
642 <        for (int i = 0; i < SIZE; i+=2) {
643 <            assertTrue(q.remove(new PDelay(i)));
644 <            assertFalse(q.remove(new PDelay(i+1)));
645 <        }
646 <        assertTrue(q.isEmpty());
488 >        } catch (NoSuchElementException success) {}
489      }
490  
491      /**
# Line 666 | Line 508 | public class DelayQueueTest extends JSR1
508          q.clear();
509          assertTrue(q.isEmpty());
510          assertEquals(0, q.size());
511 <        assertEquals(NOCAP, q.remainingCapacity());
511 >        assertEquals(Integer.MAX_VALUE, q.remainingCapacity());
512          PDelay x = new PDelay(1);
513          q.add(x);
514          assertFalse(q.isEmpty());
# Line 703 | Line 545 | public class DelayQueueTest extends JSR1
545                  assertTrue(changed);
546  
547              assertTrue(q.containsAll(p));
548 <            assertEquals(SIZE-i, q.size());
548 >            assertEquals(SIZE - i, q.size());
549              p.remove();
550          }
551      }
# Line 716 | Line 558 | public class DelayQueueTest extends JSR1
558              DelayQueue q = populatedQueue(SIZE);
559              DelayQueue p = populatedQueue(i);
560              assertTrue(q.removeAll(p));
561 <            assertEquals(SIZE-i, q.size());
561 >            assertEquals(SIZE - i, q.size());
562              for (int j = 0; j < i; ++j) {
563 <                PDelay I = (PDelay)(p.remove());
564 <                assertFalse(q.contains(I));
563 >                PDelay x = (PDelay)(p.remove());
564 >                assertFalse(q.contains(x));
565              }
566          }
567      }
# Line 727 | Line 569 | public class DelayQueueTest extends JSR1
569      /**
570       * toArray contains all elements
571       */
572 <    public void testToArray() {
572 >    public void testToArray() throws InterruptedException {
573          DelayQueue q = populatedQueue(SIZE);
574 <        Object[] o = q.toArray();
574 >        Object[] o = q.toArray();
575          Arrays.sort(o);
576 <        try {
577 <        for (int i = 0; i < o.length; i++)
736 <            assertEquals(o[i], q.take());
737 <        } catch (InterruptedException e){
738 <            unexpectedException();
739 <        }
576 >        for (int i = 0; i < o.length; i++)
577 >            assertSame(o[i], q.take());
578      }
579  
580      /**
581       * toArray(a) contains all elements
582       */
583      public void testToArray2() {
584 <        DelayQueue q = populatedQueue(SIZE);
585 <        PDelay[] ints = new PDelay[SIZE];
586 <        ints = (PDelay[])q.toArray(ints);
584 >        DelayQueue<PDelay> q = populatedQueue(SIZE);
585 >        PDelay[] ints = new PDelay[SIZE];
586 >        PDelay[] array = q.toArray(ints);
587 >        assertSame(ints, array);
588          Arrays.sort(ints);
589 <        try {
590 <            for (int i = 0; i < ints.length; i++)
752 <                assertEquals(ints[i], q.take());
753 <        } catch (InterruptedException e){
754 <            unexpectedException();
755 <        }
756 <    }
757 <
758 <
759 <    /**
760 <     * toArray(null) throws NPE
761 <     */
762 <    public void testToArray_BadArg() {
763 <        try {
764 <            DelayQueue q = populatedQueue(SIZE);
765 <            Object o[] = q.toArray(null);
766 <            shouldThrow();
767 <        } catch (NullPointerException success){}
589 >        for (int i = 0; i < ints.length; i++)
590 >            assertSame(ints[i], q.remove());
591      }
592  
593      /**
594 <     * toArray with incompatible array type throws CCE
594 >     * toArray(incompatible array type) throws ArrayStoreException
595       */
596      public void testToArray1_BadArg() {
597 <        try {
598 <            DelayQueue q = populatedQueue(SIZE);
599 <            Object o[] = q.toArray(new String[10] );
600 <            shouldThrow();
601 <        } catch (ArrayStoreException  success){}
597 >        DelayQueue q = populatedQueue(SIZE);
598 >        try {
599 >            q.toArray(new String[10]);
600 >            shouldThrow();
601 >        } catch (ArrayStoreException success) {}
602      }
603  
604      /**
# Line 784 | Line 607 | public class DelayQueueTest extends JSR1
607      public void testIterator() {
608          DelayQueue q = populatedQueue(SIZE);
609          int i = 0;
610 <        Iterator it = q.iterator();
610 >        Iterator it = q.iterator();
611          while (it.hasNext()) {
612              assertTrue(q.contains(it.next()));
613              ++i;
614          }
615          assertEquals(i, SIZE);
616 +        assertIteratorExhausted(it);
617 +    }
618 +
619 +    /**
620 +     * iterator of empty collection has no elements
621 +     */
622 +    public void testEmptyIterator() {
623 +        assertIteratorExhausted(new DelayQueue().iterator());
624      }
625  
626      /**
627       * iterator.remove removes current element
628       */
629 <    public void testIteratorRemove () {
629 >    public void testIteratorRemove() {
630          final DelayQueue q = new DelayQueue();
631          q.add(new PDelay(2));
632          q.add(new PDelay(1));
# Line 804 | Line 635 | public class DelayQueueTest extends JSR1
635          it.next();
636          it.remove();
637          it = q.iterator();
638 <        assertEquals(it.next(), new PDelay(2));
639 <        assertEquals(it.next(), new PDelay(3));
638 >        assertEquals(new PDelay(2), it.next());
639 >        assertEquals(new PDelay(3), it.next());
640          assertFalse(it.hasNext());
641      }
642  
812
643      /**
644       * toString contains toStrings of elements
645       */
646      public void testToString() {
647          DelayQueue q = populatedQueue(SIZE);
648          String s = q.toString();
649 <        for (int i = 0; i < SIZE; ++i) {
650 <            assertTrue(s.indexOf(String.valueOf(Integer.MIN_VALUE+i)) >= 0);
821 <        }
649 >        for (Object e : q)
650 >            assertTrue(s.contains(e.toString()));
651      }
652  
653      /**
654 <     * offer transfers elements across Executor tasks
654 >     * timed poll transfers elements across Executor tasks
655       */
656      public void testPollInExecutor() {
657          final DelayQueue q = new DelayQueue();
658 <        ExecutorService executor = Executors.newFixedThreadPool(2);
659 <        executor.execute(new Runnable() {
660 <            public void run() {
661 <                threadAssertNull(q.poll());
662 <                try {
663 <                    threadAssertTrue(null != q.poll(MEDIUM_DELAY_MS, TimeUnit.MILLISECONDS));
664 <                    threadAssertTrue(q.isEmpty());
665 <                }
666 <                catch (InterruptedException e) {
667 <                    threadUnexpectedException();
839 <                }
840 <            }
841 <        });
658 >        final CheckedBarrier threadsStarted = new CheckedBarrier(2);
659 >        final ExecutorService executor = Executors.newFixedThreadPool(2);
660 >        try (PoolCleaner cleaner = cleaner(executor)) {
661 >            executor.execute(new CheckedRunnable() {
662 >                public void realRun() throws InterruptedException {
663 >                    assertNull(q.poll());
664 >                    threadsStarted.await();
665 >                    assertNotNull(q.poll(LONG_DELAY_MS, MILLISECONDS));
666 >                    checkEmpty(q);
667 >                }});
668  
669 <        executor.execute(new Runnable() {
670 <            public void run() {
671 <                try {
846 <                    Thread.sleep(SHORT_DELAY_MS);
669 >            executor.execute(new CheckedRunnable() {
670 >                public void realRun() throws InterruptedException {
671 >                    threadsStarted.await();
672                      q.put(new PDelay(1));
673 <                }
674 <                catch (InterruptedException e) {
850 <                    threadUnexpectedException();
851 <                }
852 <            }
853 <        });
854 <        joinPool(executor);
855 <
673 >                }});
674 >        }
675      }
676  
858
677      /**
678       * Delayed actions do not occur until their delay elapses
679       */
680 <    public void testDelay() {
681 <        DelayQueue q = new DelayQueue();
682 <        NanoDelay[] elements = new NanoDelay[SIZE];
683 <        for (int i = 0; i < SIZE; ++i) {
866 <            elements[i] = new NanoDelay(1000000000L + 1000000L * (SIZE - i));
867 <        }
868 <        for (int i = 0; i < SIZE; ++i) {
869 <            q.add(elements[i]);
870 <        }
680 >    public void testDelay() throws InterruptedException {
681 >        DelayQueue<NanoDelay> q = new DelayQueue<NanoDelay>();
682 >        for (int i = 0; i < SIZE; ++i)
683 >            q.add(new NanoDelay(1000000L * (SIZE - i)));
684  
685 <        try {
686 <            long last = 0;
687 <            for (int i = 0; i < SIZE; ++i) {
688 <                NanoDelay e = (NanoDelay)(q.take());
689 <                long tt = e.getTriggerTime();
690 <                assertTrue(tt <= System.nanoTime());
691 <                if (i != 0)
692 <                    assertTrue(tt >= last);
880 <                last = tt;
881 <            }
882 <        }
883 <        catch (InterruptedException ie) {
884 <            unexpectedException();
685 >        long last = 0;
686 >        for (int i = 0; i < SIZE; ++i) {
687 >            NanoDelay e = q.take();
688 >            long tt = e.getTriggerTime();
689 >            assertTrue(System.nanoTime() - tt >= 0);
690 >            if (i != 0)
691 >                assertTrue(tt >= last);
692 >            last = tt;
693          }
694 +        assertTrue(q.isEmpty());
695      }
696  
697      /**
# Line 891 | Line 700 | public class DelayQueueTest extends JSR1
700      public void testPeekDelayed() {
701          DelayQueue q = new DelayQueue();
702          q.add(new NanoDelay(Long.MAX_VALUE));
703 <        assert(q.peek() != null);
703 >        assertNotNull(q.peek());
704      }
705  
897
706      /**
707       * poll of a non-empty queue returns null if no expired elements.
708       */
# Line 907 | Line 715 | public class DelayQueueTest extends JSR1
715      /**
716       * timed poll of a non-empty queue returns null if no expired elements.
717       */
718 <    public void testTimedPollDelayed() {
718 >    public void testTimedPollDelayed() throws InterruptedException {
719          DelayQueue q = new DelayQueue();
720          q.add(new NanoDelay(LONG_DELAY_MS * 1000000L));
721 <        try {
914 <            assertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
915 <        } catch (Exception ex) {
916 <            unexpectedException();
917 <        }
918 <    }
919 <
920 <    /**
921 <     * drainTo(null) throws NPE
922 <     */
923 <    public void testDrainToNull() {
924 <        DelayQueue q = populatedQueue(SIZE);
925 <        try {
926 <            q.drainTo(null);
927 <            shouldThrow();
928 <        } catch (NullPointerException success) {
929 <        }
930 <    }
931 <
932 <    /**
933 <     * drainTo(this) throws IAE
934 <     */
935 <    public void testDrainToSelf() {
936 <        DelayQueue q = populatedQueue(SIZE);
937 <        try {
938 <            q.drainTo(q);
939 <            shouldThrow();
940 <        } catch (IllegalArgumentException success) {
941 <        }
721 >        assertNull(q.poll(timeoutMillis(), MILLISECONDS));
722      }
723  
724      /**
# Line 953 | Line 733 | public class DelayQueueTest extends JSR1
733          }
734          ArrayList l = new ArrayList();
735          q.drainTo(l);
736 <        assertEquals(q.size(), 0);
736 >        assertEquals(0, q.size());
737          for (int i = 0; i < SIZE; ++i)
738 <            assertEquals(l.get(i), elems[i]);
738 >            assertEquals(elems[i], l.get(i));
739          q.add(elems[0]);
740          q.add(elems[1]);
741          assertFalse(q.isEmpty());
# Line 963 | Line 743 | public class DelayQueueTest extends JSR1
743          assertTrue(q.contains(elems[1]));
744          l.clear();
745          q.drainTo(l);
746 <        assertEquals(q.size(), 0);
747 <        assertEquals(l.size(), 2);
746 >        assertEquals(0, q.size());
747 >        assertEquals(2, l.size());
748          for (int i = 0; i < 2; ++i)
749 <            assertEquals(l.get(i), elems[i]);
749 >            assertEquals(elems[i], l.get(i));
750      }
751  
752      /**
753       * drainTo empties queue
754       */
755 <    public void testDrainToWithActivePut() {
755 >    public void testDrainToWithActivePut() throws InterruptedException {
756          final DelayQueue q = populatedQueue(SIZE);
757 <        Thread t = new Thread(new Runnable() {
758 <                public void run() {
759 <                    q.put(new PDelay(SIZE+1));
760 <                }
981 <            });
982 <        try {
983 <            t.start();
984 <            ArrayList l = new ArrayList();
985 <            q.drainTo(l);
986 <            assertTrue(l.size() >= SIZE);
987 <            t.join();
988 <            assertTrue(q.size() + l.size() >= SIZE);
989 <        } catch (Exception e){
990 <            unexpectedException();
991 <        }
992 <    }
757 >        Thread t = new Thread(new CheckedRunnable() {
758 >            public void realRun() {
759 >                q.put(new PDelay(SIZE + 1));
760 >            }});
761  
762 <    /**
763 <     * drainTo(null, n) throws NPE
764 <     */
765 <    public void testDrainToNullN() {
766 <        DelayQueue q = populatedQueue(SIZE);
767 <        try {
1000 <            q.drainTo(null, 0);
1001 <            shouldThrow();
1002 <        } catch (NullPointerException success) {
1003 <        }
1004 <    }
1005 <
1006 <    /**
1007 <     * drainTo(this, n) throws IAE
1008 <     */
1009 <    public void testDrainToSelfN() {
1010 <        DelayQueue q = populatedQueue(SIZE);
1011 <        try {
1012 <            q.drainTo(q, 0);
1013 <            shouldThrow();
1014 <        } catch (IllegalArgumentException success) {
1015 <        }
762 >        t.start();
763 >        ArrayList l = new ArrayList();
764 >        q.drainTo(l);
765 >        assertTrue(l.size() >= SIZE);
766 >        t.join();
767 >        assertTrue(q.size() + l.size() >= SIZE);
768      }
769  
770      /**
771 <     * drainTo(c, n) empties first max {n, size} elements of queue into c
771 >     * drainTo(c, n) empties first min(n, size) elements of queue into c
772       */
773      public void testDrainToN() {
774          for (int i = 0; i < SIZE + 2; ++i) {
775              DelayQueue q = populatedQueue(SIZE);
776              ArrayList l = new ArrayList();
777              q.drainTo(l, i);
778 <            int k = (i < SIZE)? i : SIZE;
779 <            assertEquals(q.size(), SIZE-k);
780 <            assertEquals(l.size(), k);
778 >            int k = (i < SIZE) ? i : SIZE;
779 >            assertEquals(SIZE - k, q.size());
780 >            assertEquals(k, l.size());
781          }
782      }
783  
784 <
784 >    /**
785 >     * remove(null), contains(null) always return false
786 >     */
787 >    public void testNeverContainsNull() {
788 >        Collection<?> q = populatedQueue(SIZE);
789 >        assertFalse(q.contains(null));
790 >        assertFalse(q.remove(null));
791 >    }
792   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines