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.1 by dl, Sun Aug 31 19:24:54 2003 UTC vs.
Revision 1.55 by jsr166, Mon Jun 27 20:37:32 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.*;
12 <
13 < public class DelayQueueTest extends TestCase {
14 <
15 <    private static final int N = 10;
16 <    private static final long SHORT_DELAY_MS = 100;
17 <    private static final long MEDIUM_DELAY_MS = 1000;
18 <    private static final long LONG_DELAY_MS = 10000;
19 <    private static final int NOCAP = Integer.MAX_VALUE;
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 <    // Most Q/BQ tests use Pseudodelays, where delays are all elapsed
29 <    // (so, no blocking solely for delays) but are still ordered
43 >    private static final int NOCAP = Integer.MAX_VALUE;
44  
45 <    static class PDelay implements Delayed {
45 >    /**
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 {
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;
38 <            if (i > j) return 1;
39 <            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 +        public int compareTo(Delayed y) {
59 +            return compareTo((PDelay)y);
60 +        }
61 +        public boolean equals(Object other) {
62 +            return (other instanceof PDelay) &&
63 +                this.pseudodelay == ((PDelay)other).pseudodelay;
64 +        }
65 +        public long getDelay(TimeUnit ignore) {
66 +            return Integer.MIN_VALUE + pseudodelay;
67 +        }
68 +        public String toString() {
69 +            return String.valueOf(pseudodelay);
70 +        }
71 +    }
72  
73 <        public int compareTo(PDelay y) {
74 <            int i = pseudodelay;
75 <            int j = ((PDelay)y).pseudodelay;
73 >    /**
74 >     * Delayed implementation that actually delays
75 >     */
76 >    static class NanoDelay implements Delayed {
77 >        long trigger;
78 >        NanoDelay(long i) {
79 >            trigger = System.nanoTime() + i;
80 >        }
81 >        public int compareTo(NanoDelay y) {
82 >            long i = 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(Delayed y) {
90 +            return compareTo((NanoDelay)y);
91 +        }
92 +
93          public boolean equals(Object other) {
94 <            return ((PDelay)other).pseudodelay == pseudodelay;
94 >            return equals((NanoDelay)other);
95          }
96 <        public boolean equals(PDelay other) {
97 <            return ((PDelay)other).pseudodelay == pseudodelay;
96 >        public boolean equals(NanoDelay other) {
97 >            return other.trigger == trigger;
98          }
99  
100 <
101 <        public long getDelay(TimeUnit ignore) {
102 <            return pseudodelay;
100 >        public long getDelay(TimeUnit unit) {
101 >            long n = trigger - System.nanoTime();
102 >            return unit.convert(n, TimeUnit.NANOSECONDS);
103          }
104 <        public int intValue() {
105 <            return pseudodelay;
104 >
105 >        public long getTriggerTime() {
106 >            return trigger;
107          }
108  
109          public String toString() {
110 <            return String.valueOf(pseudodelay);
110 >            return String.valueOf(trigger);
111          }
112      }
113  
70
71
72
114      /**
115       * Create a queue of given size containing consecutive
116       * PDelays 0 ... n.
117       */
118 <    private DelayQueue fullQueue(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 <
131 <    public void testConstructor1(){
130 >
131 >    /**
132 >     * A new queue has unbounded capacity
133 >     */
134 >    public void testConstructor1() {
135          assertEquals(NOCAP, new DelayQueue().remainingCapacity());
136      }
137  
138 <    public void testConstructor3(){
139 <
138 >    /**
139 >     * Initializing from null Collection throws NPE
140 >     */
141 >    public void testConstructor3() {
142          try {
143              DelayQueue q = new DelayQueue(null);
144 <            fail("Cannot make from null collection");
145 <        }
100 <        catch (NullPointerException success) {}
144 >            shouldThrow();
145 >        } catch (NullPointerException success) {}
146      }
147  
148 <    public void testConstructor4(){
148 >    /**
149 >     * Initializing from Collection of null elements throws NPE
150 >     */
151 >    public void testConstructor4() {
152          try {
153 <            PDelay[] ints = new PDelay[N];
153 >            PDelay[] ints = new PDelay[SIZE];
154              DelayQueue q = new DelayQueue(Arrays.asList(ints));
155 <            fail("Cannot make with null elements");
156 <        }
109 <        catch (NullPointerException success) {}
155 >            shouldThrow();
156 >        } catch (NullPointerException success) {}
157      }
158  
159 <    public void testConstructor5(){
159 >    /**
160 >     * Initializing from Collection with some null elements throws NPE
161 >     */
162 >    public void testConstructor5() {
163          try {
164 <            PDelay[] ints = new PDelay[N];
165 <            for (int i = 0; i < N-1; ++i)
164 >            PDelay[] ints = new PDelay[SIZE];
165 >            for (int i = 0; i < SIZE-1; ++i)
166                  ints[i] = new PDelay(i);
167              DelayQueue q = new DelayQueue(Arrays.asList(ints));
168 <            fail("Cannot make with null elements");
169 <        }
120 <        catch (NullPointerException success) {}
168 >            shouldThrow();
169 >        } catch (NullPointerException success) {}
170      }
171  
172 <    public void testConstructor6(){
173 <        try {
174 <            PDelay[] ints = new PDelay[N];
175 <            for (int i = 0; i < N; ++i)
176 <                ints[i] = new PDelay(i);
177 <            DelayQueue q = new DelayQueue(Arrays.asList(ints));
178 <            for (int i = 0; i < N; ++i)
179 <                assertEquals(ints[i], q.poll());
180 <        }
181 <        finally {}
172 >    /**
173 >     * Queue contains all elements of collection used to initialize
174 >     */
175 >    public void testConstructor6() {
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 +     * isEmpty is true before add, false after
186 +     */
187      public void testEmpty() {
188          DelayQueue q = new DelayQueue();
189          assertTrue(q.isEmpty());
# Line 144 | Line 196 | public class DelayQueueTest extends Test
196          assertTrue(q.isEmpty());
197      }
198  
199 <    public void testRemainingCapacity(){
200 <        DelayQueue q = fullQueue(N);
201 <        for (int i = 0; i < N; ++i) {
199 >    /**
200 >     * remainingCapacity does not change when elements added or removed,
201 >     * but size does
202 >     */
203 >    public void testRemainingCapacity() {
204 >        DelayQueue q = populatedQueue(SIZE);
205 >        for (int i = 0; i < SIZE; ++i) {
206              assertEquals(NOCAP, q.remainingCapacity());
207 <            assertEquals(N-i, q.size());
207 >            assertEquals(SIZE-i, q.size());
208              q.remove();
209          }
210 <        for (int i = 0; i < N; ++i) {
210 >        for (int i = 0; i < SIZE; ++i) {
211              assertEquals(NOCAP, q.remainingCapacity());
212              assertEquals(i, q.size());
213              q.add(new PDelay(i));
214          }
215      }
216  
217 <    public void testOfferNull(){
218 <        try {
219 <            DelayQueue q = new DelayQueue();
164 <            q.offer(null);
165 <            fail("should throw NPE");
166 <        } catch (NullPointerException success) { }  
167 <    }
168 <
217 >    /**
218 >     * offer non-null succeeds
219 >     */
220      public void testOffer() {
221          DelayQueue q = new DelayQueue();
222          assertTrue(q.offer(new PDelay(0)));
223          assertTrue(q.offer(new PDelay(1)));
224      }
225  
226 <    public void testAdd(){
226 >    /**
227 >     * add succeeds
228 >     */
229 >    public void testAdd() {
230          DelayQueue q = new DelayQueue();
231 <        for (int i = 0; i < N; ++i) {
231 >        for (int i = 0; i < SIZE; ++i) {
232              assertEquals(i, q.size());
233              assertTrue(q.add(new PDelay(i)));
234          }
235      }
236  
237 <    public void testAddAll1(){
238 <        try {
239 <            DelayQueue q = new DelayQueue();
240 <            q.addAll(null);
187 <            fail("Cannot add null collection");
188 <        }
189 <        catch (NullPointerException success) {}
190 <    }
191 <    public void testAddAll2(){
237 >    /**
238 >     * addAll(this) throws IAE
239 >     */
240 >    public void testAddAllSelf() {
241          try {
242 <            DelayQueue q = new DelayQueue();
243 <            PDelay[] ints = new PDelay[N];
244 <            q.addAll(Arrays.asList(ints));
245 <            fail("Cannot add null elements");
197 <        }
198 <        catch (NullPointerException success) {}
242 >            DelayQueue q = populatedQueue(SIZE);
243 >            q.addAll(q);
244 >            shouldThrow();
245 >        } catch (IllegalArgumentException success) {}
246      }
247 <    public void testAddAll3(){
247 >
248 >    /**
249 >     * addAll of a collection with any null elements throws NPE after
250 >     * possibly adding some elements
251 >     */
252 >    public void testAddAll3() {
253          try {
254              DelayQueue q = new DelayQueue();
255 <            PDelay[] ints = new PDelay[N];
256 <            for (int i = 0; i < N-1; ++i)
255 >            PDelay[] ints = new PDelay[SIZE];
256 >            for (int i = 0; i < SIZE-1; ++i)
257                  ints[i] = new PDelay(i);
258              q.addAll(Arrays.asList(ints));
259 <            fail("Cannot add null elements");
260 <        }
209 <        catch (NullPointerException success) {}
259 >            shouldThrow();
260 >        } catch (NullPointerException success) {}
261      }
262  
263 <    public void testAddAll5(){
264 <        try {
265 <            PDelay[] empty = new PDelay[0];
266 <            PDelay[] ints = new PDelay[N];
267 <            for (int i = N-1; i >= 0; --i)
268 <                ints[i] = new PDelay(i);
269 <            DelayQueue q = new DelayQueue();
270 <            assertFalse(q.addAll(Arrays.asList(empty)));
271 <            assertTrue(q.addAll(Arrays.asList(ints)));
272 <            for (int i = 0; i < N; ++i)
273 <                assertEquals(ints[i], q.poll());
274 <        }
275 <        finally {}
263 >    /**
264 >     * Queue contains all elements of successful addAll
265 >     */
266 >    public void testAddAll5() {
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 <     public void testPutNull() {
279 <        try {
280 <            DelayQueue q = new DelayQueue();
281 <            q.put(null);
282 <            fail("put should throw NPE");
283 <        }
284 <        catch (NullPointerException success){
285 <        }  
286 <     }
236 <
237 <     public void testPut() {
238 <         try {
239 <             DelayQueue q = new DelayQueue();
240 <             for (int i = 0; i < N; ++i) {
241 <                 PDelay I = new PDelay(i);
242 <                 q.put(I);
243 <                 assertTrue(q.contains(I));
244 <             }
245 <             assertEquals(N, q.size());
246 <         }
247 <         finally {
278 >    /**
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());
289      }
290  
291 <    public void testPutWithTake() {
291 >    /**
292 >     * put doesn't block waiting for take
293 >     */
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;
263 <                        q.put(new PDelay(0));
264 <                        ++added;
265 <                        assertTrue(added == 4);
266 <                    } finally {
267 <                    }
268 <                }
269 <            });
270 <        try {
271 <            t.start();
272 <            Thread.sleep(SHORT_DELAY_MS);
273 <            q.take();
274 <            t.interrupt();
275 <            t.join();
276 <        } catch (Exception e){
277 <            fail("Unexpected exception");
278 <        }
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 <    public void testTimedOffer() {
308 >    /**
309 >     * timed offer does not time out
310 >     */
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 <                        assertTrue(q.offer(new PDelay(0), SHORT_DELAY_MS/2, TimeUnit.MILLISECONDS));
319 <                        assertTrue(q.offer(new PDelay(0), LONG_DELAY_MS, TimeUnit.MILLISECONDS));
290 <                    } finally { }
291 <                }
292 <            });
293 <        
294 <        try {
295 <            t.start();
296 <            Thread.sleep(SHORT_DELAY_MS);
297 <            t.interrupt();
298 <            t.join();
299 <        } catch (Exception e){
300 <            fail("Unexpected exception");
301 <        }
302 <    }
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 <    public void testTake(){
305 <        try {
306 <            DelayQueue q = fullQueue(N);
307 <            for (int i = 0; i < N; ++i) {
308 <                assertEquals(new PDelay(i), ((PDelay)q.take()));
309 <            }
310 <        } catch (InterruptedException e){
311 <            fail("Unexpected exception");
312 <        }  
321 >        awaitTermination(t);
322      }
323  
324 <    public void testTakeFromEmpty() {
325 <        final DelayQueue q = new DelayQueue();
326 <        Thread t = new Thread(new Runnable() {
327 <                public void run(){
328 <                    try {
329 <                        q.take();
330 <                        fail("Should block");
322 <                    } catch (InterruptedException success){ }                
323 <                }
324 <            });
325 <        try {
326 <            t.start();
327 <            Thread.sleep(SHORT_DELAY_MS);
328 <            t.interrupt();
329 <            t.join();
330 <        } catch (Exception e){
331 <            fail("Unexpected exception");
324 >    /**
325 >     * take retrieves elements in priority order
326 >     */
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 <    public void testBlockingTake(){
335 <        Thread t = new Thread(new Runnable() {
336 <                public void run() {
337 <                    try {
338 <                        DelayQueue q = fullQueue(N);
339 <                        for (int i = 0; i < N; ++i) {
340 <                            assertEquals(new PDelay(i), ((PDelay)q.take()));
341 <                        }
342 <                        q.take();
343 <                        fail("take should block");
344 <                    } catch (InterruptedException success){
346 <                    }  
347 <                }});
348 <        t.start();
349 <        try {
350 <           Thread.sleep(SHORT_DELAY_MS);
351 <           t.interrupt();
352 <           t.join();
353 <        }
354 <        catch (InterruptedException ie) {
355 <            fail("Unexpected exception");
356 <        }
357 <    }
334 >    /**
335 >     * Take removes existing elements until empty, then blocks interruptibly
336 >     */
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 >                }
345  
346 +                Thread.currentThread().interrupt();
347 +                try {
348 +                    q.take();
349 +                    shouldThrow();
350 +                } catch (InterruptedException success) {}
351 +                assertFalse(Thread.interrupted());
352  
353 <    public void testPoll(){
354 <        DelayQueue q = fullQueue(N);
355 <        for (int i = 0; i < N; ++i) {
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 >     * 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 <    public void testTimedPoll0() {
379 <        try {
380 <            DelayQueue q = fullQueue(N);
381 <            for (int i = 0; i < N; ++i) {
382 <                assertEquals(new PDelay(i), ((PDelay)q.poll(0, TimeUnit.MILLISECONDS)));
383 <            }
384 <            assertNull(q.poll(0, TimeUnit.MILLISECONDS));
385 <        } catch (InterruptedException e){
386 <            fail("Unexpected exception");
377 <        }  
378 >    /**
379 >     * timed poll with zero timeout succeeds when non-empty, else times out
380 >     */
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 <    public void testTimedPoll() {
390 <        try {
391 <            DelayQueue q = fullQueue(N);
392 <            for (int i = 0; i < N; ++i) {
393 <                assertEquals(new PDelay(i), ((PDelay)q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS)));
394 <            }
395 <            assertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
396 <        } catch (InterruptedException e){
397 <            fail("Unexpected exception");
398 <        }  
399 <    }
400 <
401 <    public void testInterruptedTimedPoll(){
402 <        Thread t = new Thread(new Runnable() {
394 <                public void run() {
395 <                    try {
396 <                        DelayQueue q = fullQueue(N);
397 <                        for (int i = 0; i < N; ++i) {
398 <                            assertEquals(new PDelay(i), ((PDelay)q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS)));
399 <                        }
400 <                        assertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
401 <                    } catch (InterruptedException success){
402 <                    }  
403 <                }});
404 <        t.start();
405 <        try {
406 <           Thread.sleep(SHORT_DELAY_MS);
407 <           t.interrupt();
408 <           t.join();
409 <        }
410 <        catch (InterruptedException ie) {
411 <            fail("Unexpected exception");
412 <        }
389 >    /**
390 >     * timed poll with nonzero timeout succeeds when non-empty, else times out
391 >     */
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 <    public void testTimedPollWithOffer(){
406 <        final DelayQueue q = new DelayQueue();
407 <        Thread t = new Thread(new Runnable() {
408 <                public void run(){
409 <                    try {
410 <                        assertNull(q.poll(SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
411 <                        q.poll(LONG_DELAY_MS, TimeUnit.MILLISECONDS);
412 <                        q.poll(LONG_DELAY_MS, TimeUnit.MILLISECONDS);
413 <                        fail("Should block");
414 <                    } catch (InterruptedException success) { }                
405 >    /**
406 >     * Interrupted timed poll throws InterruptedException instead of
407 >     * returning timeout status
408 >     */
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                  }
426            });
427        try {
428            t.start();
429            Thread.sleep(SHORT_DELAY_MS * 2);
430            assertTrue(q.offer(new PDelay(0), SHORT_DELAY_MS, TimeUnit.MILLISECONDS));
431            t.interrupt();
432            t.join();
433        } catch (Exception e){
434            fail("Unexpected exception");
435        }
436    }  
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 <    public void testPeek(){
440 <        DelayQueue q = fullQueue(N);
441 <        for (int i = 0; i < N; ++i) {
439 >    /**
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 <    public void testElement(){
456 <        DelayQueue q = fullQueue(N);
457 <        for (int i = 0; i < N; ++i) {
455 >    /**
456 >     * element returns next element, or throws NSEE if empty
457 >     */
458 >    public void testElement() {
459 >        DelayQueue q = populatedQueue(SIZE);
460 >        for (int i = 0; i < SIZE; ++i) {
461              assertEquals(new PDelay(i), ((PDelay)q.element()));
462              q.poll();
463          }
464          try {
465              q.element();
466 <            fail("no such element");
467 <        }
460 <        catch (NoSuchElementException success) {}
466 >            shouldThrow();
467 >        } catch (NoSuchElementException success) {}
468      }
469  
470 <    public void testRemove(){
471 <        DelayQueue q = fullQueue(N);
472 <        for (int i = 0; i < N; ++i) {
470 >    /**
471 >     * remove removes next element, or throws NSEE if empty
472 >     */
473 >    public void testRemove() {
474 >        DelayQueue q = populatedQueue(SIZE);
475 >        for (int i = 0; i < SIZE; ++i) {
476              assertEquals(new PDelay(i), ((PDelay)q.remove()));
477          }
478          try {
479              q.remove();
480 <            fail("remove should throw");
481 <        } catch (NoSuchElementException success){
472 <        }  
480 >            shouldThrow();
481 >        } catch (NoSuchElementException success) {}
482      }
483  
484 <    public void testRemoveElement(){
485 <        DelayQueue q = fullQueue(N);
486 <        for (int i = 1; i < N; i+=2) {
484 >    /**
485 >     * remove(x) removes x and returns true if present
486 >     */
487 >    public void testRemoveElement() {
488 >        DelayQueue q = populatedQueue(SIZE);
489 >        for (int i = 1; i < SIZE; i+=2) {
490              assertTrue(q.remove(new PDelay(i)));
491          }
492 <        for (int i = 0; i < N; i+=2) {
492 >        for (int i = 0; i < SIZE; i+=2) {
493              assertTrue(q.remove(new PDelay(i)));
494              assertFalse(q.remove(new PDelay(i+1)));
495          }
496 <        assert(q.isEmpty());
496 >        assertTrue(q.isEmpty());
497      }
498 <        
499 <    public void testContains(){
500 <        DelayQueue q = fullQueue(N);
501 <        for (int i = 0; i < N; ++i) {
498 >
499 >    /**
500 >     * contains(x) reports true when elements added but not yet removed
501 >     */
502 >    public void testContains() {
503 >        DelayQueue q = populatedQueue(SIZE);
504 >        for (int i = 0; i < SIZE; ++i) {
505              assertTrue(q.contains(new PDelay(i)));
506              q.poll();
507              assertFalse(q.contains(new PDelay(i)));
508          }
509      }
510  
511 <    public void testClear(){
512 <        DelayQueue q = fullQueue(N);
511 >    /**
512 >     * clear removes all elements
513 >     */
514 >    public void testClear() {
515 >        DelayQueue q = populatedQueue(SIZE);
516          q.clear();
517          assertTrue(q.isEmpty());
518          assertEquals(0, q.size());
519          assertEquals(NOCAP, q.remainingCapacity());
520 <        q.add(new PDelay(1));
520 >        PDelay x = new PDelay(1);
521 >        q.add(x);
522          assertFalse(q.isEmpty());
523 +        assertTrue(q.contains(x));
524          q.clear();
525          assertTrue(q.isEmpty());
526      }
527  
528 <    public void testContainsAll(){
529 <        DelayQueue q = fullQueue(N);
528 >    /**
529 >     * containsAll(c) is true when c contains a subset of elements
530 >     */
531 >    public void testContainsAll() {
532 >        DelayQueue q = populatedQueue(SIZE);
533          DelayQueue p = new DelayQueue();
534 <        for (int i = 0; i < N; ++i) {
534 >        for (int i = 0; i < SIZE; ++i) {
535              assertTrue(q.containsAll(p));
536              assertFalse(p.containsAll(q));
537              p.add(new PDelay(i));
# Line 516 | Line 539 | public class DelayQueueTest extends Test
539          assertTrue(p.containsAll(q));
540      }
541  
542 <    public void testRetainAll(){
543 <        DelayQueue q = fullQueue(N);
544 <        DelayQueue p = fullQueue(N);
545 <        for (int i = 0; i < N; ++i) {
542 >    /**
543 >     * retainAll(c) retains only those elements of c and reports true if changed
544 >     */
545 >    public void testRetainAll() {
546 >        DelayQueue q = populatedQueue(SIZE);
547 >        DelayQueue p = populatedQueue(SIZE);
548 >        for (int i = 0; i < SIZE; ++i) {
549              boolean changed = q.retainAll(p);
550              if (i == 0)
551                  assertFalse(changed);
# Line 527 | Line 553 | public class DelayQueueTest extends Test
553                  assertTrue(changed);
554  
555              assertTrue(q.containsAll(p));
556 <            assertEquals(N-i, q.size());
556 >            assertEquals(SIZE-i, q.size());
557              p.remove();
558          }
559      }
560  
561 <    public void testRemoveAll(){
562 <        for (int i = 1; i < N; ++i) {
563 <            DelayQueue q = fullQueue(N);
564 <            DelayQueue p = fullQueue(i);
561 >    /**
562 >     * removeAll(c) removes only those elements of c and reports true if changed
563 >     */
564 >    public void testRemoveAll() {
565 >        for (int i = 1; i < SIZE; ++i) {
566 >            DelayQueue q = populatedQueue(SIZE);
567 >            DelayQueue p = populatedQueue(i);
568              assertTrue(q.removeAll(p));
569 <            assertEquals(N-i, q.size());
569 >            assertEquals(SIZE-i, q.size());
570              for (int j = 0; j < i; ++j) {
571                  PDelay I = (PDelay)(p.remove());
572                  assertFalse(q.contains(I));
# Line 545 | Line 574 | public class DelayQueueTest extends Test
574          }
575      }
576  
577 <    /*
578 <    public void testEqualsAndHashCode(){
579 <        DelayQueue q1 = fullQueue(N);
580 <        DelayQueue q2 = fullQueue(N);
581 <        assertTrue(q1.equals(q2));
582 <        assertTrue(q2.equals(q1));
554 <        assertEquals(q1.hashCode(), q2.hashCode());
555 <        q1.remove();
556 <        assertFalse(q1.equals(q2));
557 <        assertFalse(q2.equals(q1));
558 <        assertFalse(q1.hashCode() == q2.hashCode());
559 <        q2.remove();
560 <        assertTrue(q1.equals(q2));
561 <        assertTrue(q2.equals(q1));
562 <        assertEquals(q1.hashCode(), q2.hashCode());
563 <    }
564 <    */
565 <
566 <    public void testToArray(){
567 <        DelayQueue q = fullQueue(N);
568 <        Object[] o = q.toArray();
577 >    /**
578 >     * toArray contains all elements
579 >     */
580 >    public void testToArray() throws InterruptedException {
581 >        DelayQueue q = populatedQueue(SIZE);
582 >        Object[] o = q.toArray();
583          Arrays.sort(o);
584 <        try {
585 <        for(int i = 0; i < o.length; i++)
572 <            assertEquals(o[i], q.take());
573 <        } catch (InterruptedException e){
574 <            fail("Unexpected exception");
575 <        }    
584 >        for (int i = 0; i < o.length; i++)
585 >            assertSame(o[i], q.take());
586      }
587  
588 <    public void testToArray2(){
589 <        DelayQueue q = fullQueue(N);
590 <        PDelay[] ints = new PDelay[N];
591 <        ints = (PDelay[])q.toArray(ints);
588 >    /**
589 >     * toArray(a) contains all elements
590 >     */
591 >    public void testToArray2() {
592 >        DelayQueue<PDelay> q = populatedQueue(SIZE);
593 >        PDelay[] ints = new PDelay[SIZE];
594 >        PDelay[] array = q.toArray(ints);
595 >        assertSame(ints, array);
596          Arrays.sort(ints);
597 <        try {
598 <            for(int i = 0; i < ints.length; i++)
599 <                assertEquals(ints[i], q.take());
600 <        } catch (InterruptedException e){
601 <            fail("Unexpected exception");
602 <        }    
603 <    }
604 <    
605 <    public void testIterator(){
606 <        DelayQueue q = fullQueue(N);
597 >        for (int i = 0; i < ints.length; i++)
598 >            assertSame(ints[i], q.remove());
599 >    }
600 >
601 >    /**
602 >     * toArray(incompatible array type) throws ArrayStoreException
603 >     */
604 >    public void testToArray1_BadArg() {
605 >        DelayQueue q = populatedQueue(SIZE);
606 >        try {
607 >            q.toArray(new String[10]);
608 >            shouldThrow();
609 >        } catch (ArrayStoreException success) {}
610 >    }
611 >
612 >    /**
613 >     * iterator iterates through all elements
614 >     */
615 >    public void testIterator() {
616 >        DelayQueue q = populatedQueue(SIZE);
617          int i = 0;
618 <        Iterator it = q.iterator();
619 <        while(it.hasNext()) {
618 >        Iterator it = q.iterator();
619 >        while (it.hasNext()) {
620              assertTrue(q.contains(it.next()));
621              ++i;
622          }
623 <        assertEquals(i, N);
623 >        assertEquals(i, SIZE);
624      }
625  
626 <    public void testIteratorRemove () {
627 <
626 >    /**
627 >     * iterator.remove removes current element
628 >     */
629 >    public void testIteratorRemove() {
630          final DelayQueue q = new DelayQueue();
605
631          q.add(new PDelay(2));
632          q.add(new PDelay(1));
633          q.add(new PDelay(3));
609
634          Iterator it = q.iterator();
635          it.next();
636          it.remove();
613
637          it = q.iterator();
638          assertEquals(it.next(), new PDelay(2));
639          assertEquals(it.next(), new PDelay(3));
640          assertFalse(it.hasNext());
641      }
642  
643 <
644 <    public void testToString(){
645 <        DelayQueue q = fullQueue(N);
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 < N; ++i) {
650 <            assertTrue(s.indexOf(String.valueOf(i)) >= 0);
651 <        }
627 <    }        
649 >        for (Object e : q)
650 >            assertTrue(s.contains(e.toString()));
651 >    }
652  
653 +    /**
654 +     * timed poll transfers elements across Executor tasks
655 +     */
656      public void testPollInExecutor() {
630
657          final DelayQueue q = new DelayQueue();
658 <
658 >        final CheckedBarrier threadsStarted = new CheckedBarrier(2);
659          ExecutorService executor = Executors.newFixedThreadPool(2);
660 +        executor.execute(new CheckedRunnable() {
661 +            public void realRun() throws InterruptedException {
662 +                assertNull(q.poll());
663 +                threadsStarted.await();
664 +                assertTrue(null != q.poll(LONG_DELAY_MS, MILLISECONDS));
665 +                checkEmpty(q);
666 +            }});
667 +
668 +        executor.execute(new CheckedRunnable() {
669 +            public void realRun() throws InterruptedException {
670 +                threadsStarted.await();
671 +                q.put(new PDelay(1));
672 +            }});
673  
674 <        executor.execute(new Runnable() {
636 <            public void run() {
637 <                assertNull("poll should fail", q.poll());
638 <                try {
639 <                    assertTrue(null != q.poll(MEDIUM_DELAY_MS * 2, TimeUnit.MILLISECONDS));
640 <                    assertTrue(q.isEmpty());
641 <                }
642 <                catch (InterruptedException e) {
643 <                    fail("should not be interrupted");
644 <                }
645 <            }
646 <        });
647 <
648 <        executor.execute(new Runnable() {
649 <            public void run() {
650 <                try {
651 <                    Thread.sleep(MEDIUM_DELAY_MS);
652 <                    q.put(new PDelay(1));
653 <                }
654 <                catch (InterruptedException e) {
655 <                    fail("should not be interrupted");
656 <                }
657 <            }
658 <        });
659 <        
660 <        executor.shutdown();
661 <
674 >        joinPool(executor);
675      }
676  
677 <    static class NanoDelay implements Delayed {
678 <        long trigger;
679 <        NanoDelay(long i) {
680 <            trigger = System.nanoTime() + i;
681 <        }
682 <        public int compareTo(Object y) {
683 <            long i = trigger;
684 <            long j = ((NanoDelay)y).trigger;
685 <            if (i < j) return -1;
686 <            if (i > j) return 1;
687 <            return 0;
688 <        }
689 <
690 <        public int compareTo(NanoDelay y) {
691 <            long i = trigger;
692 <            long j = ((NanoDelay)y).trigger;
680 <            if (i < j) return -1;
681 <            if (i > j) return 1;
682 <            return 0;
683 <        }
684 <
685 <        public boolean equals(Object other) {
686 <            return ((NanoDelay)other).trigger == trigger;
687 <        }
688 <        public boolean equals(NanoDelay other) {
689 <            return ((NanoDelay)other).trigger == trigger;
677 >    /**
678 >     * Delayed actions do not occur until their delay elapses
679 >     */
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 >        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 <        public long getDelay(TimeUnit unit) {
698 <            long n = trigger - System.nanoTime();
699 <            return unit.convert(n, TimeUnit.NANOSECONDS);
700 <        }
697 >    /**
698 >     * peek of a non-empty queue returns non-null even if not expired
699 >     */
700 >    public void testPeekDelayed() {
701 >        DelayQueue q = new DelayQueue();
702 >        q.add(new NanoDelay(Long.MAX_VALUE));
703 >        assertNotNull(q.peek());
704 >    }
705  
706 <        public long getTriggerTime() {
707 <            return trigger;
708 <        }
706 >    /**
707 >     * poll of a non-empty queue returns null if no expired elements.
708 >     */
709 >    public void testPollDelayed() {
710 >        DelayQueue q = new DelayQueue();
711 >        q.add(new NanoDelay(Long.MAX_VALUE));
712 >        assertNull(q.poll());
713 >    }
714  
715 <        public String toString() {
716 <            return String.valueOf(trigger);
717 <        }
715 >    /**
716 >     * timed poll of a non-empty queue returns null if no expired elements.
717 >     */
718 >    public void testTimedPollDelayed() throws InterruptedException {
719 >        DelayQueue q = new DelayQueue();
720 >        q.add(new NanoDelay(LONG_DELAY_MS * 1000000L));
721 >        assertNull(q.poll(timeoutMillis(), MILLISECONDS));
722      }
723  
724 <    public void testDelay() {
724 >    /**
725 >     * drainTo(c) empties queue into another collection c
726 >     */
727 >    public void testDrainTo() {
728          DelayQueue q = new DelayQueue();
729 <        NanoDelay[] elements = new NanoDelay[N];
730 <        for (int i = 0; i < N; ++i) {
731 <            elements[i] = new NanoDelay(1000000000L + 1000000L * (N - i));
732 <        }
733 <        for (int i = 0; i < N; ++i) {
734 <            q.add(elements[i]);
735 <        }
729 >        PDelay[] elems = new PDelay[SIZE];
730 >        for (int i = 0; i < SIZE; ++i) {
731 >            elems[i] = new PDelay(i);
732 >            q.add(elems[i]);
733 >        }
734 >        ArrayList l = new ArrayList();
735 >        q.drainTo(l);
736 >        assertEquals(q.size(), 0);
737 >        for (int i = 0; i < SIZE; ++i)
738 >            assertEquals(l.get(i), elems[i]);
739 >        q.add(elems[0]);
740 >        q.add(elems[1]);
741 >        assertFalse(q.isEmpty());
742 >        assertTrue(q.contains(elems[0]));
743 >        assertTrue(q.contains(elems[1]));
744 >        l.clear();
745 >        q.drainTo(l);
746 >        assertEquals(q.size(), 0);
747 >        assertEquals(l.size(), 2);
748 >        for (int i = 0; i < 2; ++i)
749 >            assertEquals(l.get(i), elems[i]);
750 >    }
751  
752 <        try {
753 <            long last = 0;
754 <            for (int i = 0; i < N; ++i) {
755 <                NanoDelay e = (NanoDelay)(q.take());
756 <                long tt = e.getTriggerTime();
757 <                assertTrue(tt <= System.nanoTime());
758 <                if (i != 0)
759 <                    assertTrue(tt >= last);
760 <                last = tt;
761 <            }
762 <        }
763 <        catch(InterruptedException ie) {
764 <            fail("Unexpected Exception");
752 >    /**
753 >     * drainTo empties queue
754 >     */
755 >    public void testDrainToWithActivePut() throws InterruptedException {
756 >        final DelayQueue q = populatedQueue(SIZE);
757 >        Thread t = new Thread(new CheckedRunnable() {
758 >            public void realRun() {
759 >                q.put(new PDelay(SIZE+1));
760 >            }});
761 >
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 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);
781          }
782      }
783  

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines