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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines