ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/tck/ExecutorCompletionServiceTest.java
(Generate patch)

Comparing jsr166/src/test/tck/ExecutorCompletionServiceTest.java (file contents):
Revision 1.11 by jsr166, Wed Aug 25 00:07:03 2010 UTC vs.
Revision 1.27 by jsr166, Wed Aug 24 22:22:39 2016 UTC

# Line 1 | Line 1
1   /*
2   * Written by Doug Lea with assistance from members of JCP JSR-166
3   * Expert Group and released to the public domain, as explained at
4 < * http://creativecommons.org/licenses/publicdomain
4 > * http://creativecommons.org/publicdomain/zero/1.0/
5   * Other contributors include Andrew Wright, Jeffrey Hayes,
6   * Pat Fisher, Mike Judd.
7   */
8  
9
10 import junit.framework.*;
11 import java.util.*;
12 import java.util.concurrent.*;
9   import static java.util.concurrent.TimeUnit.MILLISECONDS;
10 < import java.util.concurrent.atomic.*;
11 < import java.math.BigInteger;
12 < import java.security.*;
10 >
11 > import java.util.concurrent.ArrayBlockingQueue;
12 > import java.util.concurrent.Callable;
13 > import java.util.concurrent.CompletionService;
14 > import java.util.concurrent.CountDownLatch;
15 > import java.util.concurrent.ExecutionException;
16 > import java.util.concurrent.ExecutorCompletionService;
17 > import java.util.concurrent.ExecutorService;
18 > import java.util.concurrent.Future;
19 > import java.util.concurrent.FutureTask;
20 > import java.util.concurrent.RunnableFuture;
21 > import java.util.concurrent.ThreadPoolExecutor;
22 > import java.util.concurrent.TimeUnit;
23 > import java.util.concurrent.atomic.AtomicBoolean;
24 >
25 > import junit.framework.Test;
26 > import junit.framework.TestSuite;
27  
28   public class ExecutorCompletionServiceTest extends JSR166TestCase {
29      public static void main(String[] args) {
30 <        junit.textui.TestRunner.run(suite());
30 >        main(suite(), args);
31      }
32      public static Test suite() {
33          return new TestSuite(ExecutorCompletionServiceTest.class);
34      }
35  
26
36      /**
37 <     * Creating a new ECS with null Executor throw NPE
37 >     * new ExecutorCompletionService(null) throws NullPointerException
38       */
39      public void testConstructorNPE() {
40          try {
41 <            ExecutorCompletionService ecs = new ExecutorCompletionService(null);
41 >            new ExecutorCompletionService(null);
42              shouldThrow();
43          } catch (NullPointerException success) {}
44      }
45  
46      /**
47 <     * Creating a new ECS with null queue throw NPE
47 >     * new ExecutorCompletionService(e, null) throws NullPointerException
48       */
49      public void testConstructorNPE2() {
50          try {
51 <            ExecutorService e = Executors.newCachedThreadPool();
43 <            ExecutorCompletionService ecs = new ExecutorCompletionService(e, null);
51 >            new ExecutorCompletionService(cachedThreadPool, null);
52              shouldThrow();
53          } catch (NullPointerException success) {}
54      }
55  
56      /**
57 <     * Submitting a null callable throws NPE
57 >     * ecs.submit(null) throws NullPointerException
58       */
59 <    public void testSubmitNPE() {
60 <        ExecutorService e = Executors.newCachedThreadPool();
53 <        ExecutorCompletionService ecs = new ExecutorCompletionService(e);
59 >    public void testSubmitNullCallable() {
60 >        CompletionService cs = new ExecutorCompletionService(cachedThreadPool);
61          try {
62 <            Callable c = null;
56 <            ecs.submit(c);
62 >            cs.submit((Callable) null);
63              shouldThrow();
64 <        } catch (NullPointerException success) {
59 <        } finally {
60 <            joinPool(e);
61 <        }
64 >        } catch (NullPointerException success) {}
65      }
66  
67      /**
68 <     * Submitting a null runnable throws NPE
68 >     * ecs.submit(null, val) throws NullPointerException
69       */
70 <    public void testSubmitNPE2() {
71 <        ExecutorService e = Executors.newCachedThreadPool();
69 <        ExecutorCompletionService ecs = new ExecutorCompletionService(e);
70 >    public void testSubmitNullRunnable() {
71 >        CompletionService cs = new ExecutorCompletionService(cachedThreadPool);
72          try {
73 <            Runnable r = null;
72 <            ecs.submit(r, Boolean.TRUE);
73 >            cs.submit((Runnable) null, Boolean.TRUE);
74              shouldThrow();
75 <        } catch (NullPointerException success) {
75 <        } finally {
76 <            joinPool(e);
77 <        }
75 >        } catch (NullPointerException success) {}
76      }
77  
78      /**
79       * A taken submitted task is completed
80       */
81 <    public void testTake() throws InterruptedException {
82 <        ExecutorService e = Executors.newCachedThreadPool();
83 <        ExecutorCompletionService ecs = new ExecutorCompletionService(e);
84 <        try {
85 <            Callable c = new StringTask();
86 <            ecs.submit(c);
87 <            Future f = ecs.take();
90 <            assertTrue(f.isDone());
91 <        } finally {
92 <            joinPool(e);
93 <        }
81 >    public void testTake()
82 >        throws InterruptedException, ExecutionException {
83 >        CompletionService cs = new ExecutorCompletionService(cachedThreadPool);
84 >        cs.submit(new StringTask());
85 >        Future f = cs.take();
86 >        assertTrue(f.isDone());
87 >        assertSame(TEST_STRING, f.get());
88      }
89  
90      /**
91       * Take returns the same future object returned by submit
92       */
93      public void testTake2() throws InterruptedException {
94 <        ExecutorService e = Executors.newCachedThreadPool();
95 <        ExecutorCompletionService ecs = new ExecutorCompletionService(e);
96 <        try {
97 <            Callable c = new StringTask();
98 <            Future f1 = ecs.submit(c);
99 <            Future f2 = ecs.take();
100 <            assertSame(f1, f2);
101 <        } finally {
102 <            joinPool(e);
94 >        CompletionService cs = new ExecutorCompletionService(cachedThreadPool);
95 >        Future f1 = cs.submit(new StringTask());
96 >        Future f2 = cs.take();
97 >        assertSame(f1, f2);
98 >    }
99 >
100 >    /**
101 >     * poll returns non-null when the returned task is completed
102 >     */
103 >    public void testPoll1()
104 >        throws InterruptedException, ExecutionException {
105 >        CompletionService cs = new ExecutorCompletionService(cachedThreadPool);
106 >        assertNull(cs.poll());
107 >        cs.submit(new StringTask());
108 >
109 >        long startTime = System.nanoTime();
110 >        Future f;
111 >        while ((f = cs.poll()) == null) {
112 >            if (millisElapsedSince(startTime) > LONG_DELAY_MS)
113 >                fail("timed out");
114 >            Thread.yield();
115 >        }
116 >        assertTrue(f.isDone());
117 >        assertSame(TEST_STRING, f.get());
118 >    }
119 >
120 >    /**
121 >     * timed poll returns non-null when the returned task is completed
122 >     */
123 >    public void testPoll2()
124 >        throws InterruptedException, ExecutionException {
125 >        CompletionService cs = new ExecutorCompletionService(cachedThreadPool);
126 >        assertNull(cs.poll());
127 >        cs.submit(new StringTask());
128 >
129 >        long startTime = System.nanoTime();
130 >        Future f;
131 >        while ((f = cs.poll(SHORT_DELAY_MS, MILLISECONDS)) == null) {
132 >            if (millisElapsedSince(startTime) > LONG_DELAY_MS)
133 >                fail("timed out");
134 >            Thread.yield();
135 >        }
136 >        assertTrue(f.isDone());
137 >        assertSame(TEST_STRING, f.get());
138 >    }
139 >
140 >    /**
141 >     * poll returns null before the returned task is completed
142 >     */
143 >    public void testPollReturnsNull()
144 >        throws InterruptedException, ExecutionException {
145 >        CompletionService cs = new ExecutorCompletionService(cachedThreadPool);
146 >        final CountDownLatch proceed = new CountDownLatch(1);
147 >        cs.submit(new Callable() { public String call() throws Exception {
148 >            proceed.await();
149 >            return TEST_STRING;
150 >        }});
151 >        assertNull(cs.poll());
152 >        assertNull(cs.poll(0L, MILLISECONDS));
153 >        assertNull(cs.poll(Long.MIN_VALUE, MILLISECONDS));
154 >        long startTime = System.nanoTime();
155 >        assertNull(cs.poll(timeoutMillis(), MILLISECONDS));
156 >        assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
157 >        proceed.countDown();
158 >        assertSame(TEST_STRING, cs.take().get());
159 >    }
160 >
161 >    /**
162 >     * successful and failed tasks are both returned
163 >     */
164 >    public void testTaskAssortment()
165 >        throws InterruptedException, ExecutionException {
166 >        CompletionService cs = new ExecutorCompletionService(cachedThreadPool);
167 >        ArithmeticException ex = new ArithmeticException();
168 >        for (int i = 0; i < 2; i++) {
169 >            cs.submit(new StringTask());
170 >            cs.submit(callableThrowing(ex));
171 >            cs.submit(runnableThrowing(ex), null);
172 >        }
173 >        int normalCompletions = 0;
174 >        int exceptionalCompletions = 0;
175 >        for (int i = 0; i < 3 * 2; i++) {
176 >            try {
177 >                if (cs.take().get() == TEST_STRING)
178 >                    normalCompletions++;
179 >            }
180 >            catch (ExecutionException expected) {
181 >                assertTrue(expected.getCause() instanceof ArithmeticException);
182 >                exceptionalCompletions++;
183 >            }
184          }
185 +        assertEquals(2 * 1, normalCompletions);
186 +        assertEquals(2 * 2, exceptionalCompletions);
187 +        assertNull(cs.poll());
188      }
189  
190      /**
191 <     * If poll returns non-null, the returned task is completed
192 <     */
193 <    public void testPoll1() throws InterruptedException {
194 <        ExecutorService e = Executors.newCachedThreadPool();
195 <        ExecutorCompletionService ecs = new ExecutorCompletionService(e);
196 <        try {
197 <            assertNull(ecs.poll());
198 <            Callable c = new StringTask();
199 <            ecs.submit(c);
200 <            Thread.sleep(SHORT_DELAY_MS);
201 <            for (;;) {
202 <                Future f = ecs.poll();
203 <                if (f != null) {
204 <                    assertTrue(f.isDone());
205 <                    break;
206 <                }
207 <            }
208 <        } finally {
209 <            joinPool(e);
191 >     * Submitting to underlying AES that overrides newTaskFor(Callable)
192 >     * returns and eventually runs Future returned by newTaskFor.
193 >     */
194 >    public void testNewTaskForCallable() throws InterruptedException {
195 >        final AtomicBoolean done = new AtomicBoolean(false);
196 >        class MyCallableFuture<V> extends FutureTask<V> {
197 >            MyCallableFuture(Callable<V> c) { super(c); }
198 >            @Override protected void done() { done.set(true); }
199 >        }
200 >        final ExecutorService e =
201 >            new ThreadPoolExecutor(1, 1,
202 >                                   30L, TimeUnit.SECONDS,
203 >                                   new ArrayBlockingQueue<Runnable>(1)) {
204 >                protected <T> RunnableFuture<T> newTaskFor(Callable<T> c) {
205 >                    return new MyCallableFuture<T>(c);
206 >                }};
207 >        CompletionService<String> cs = new ExecutorCompletionService<>(e);
208 >        try (PoolCleaner cleaner = cleaner(e)) {
209 >            assertNull(cs.poll());
210 >            Callable<String> c = new StringTask();
211 >            Future f1 = cs.submit(c);
212 >            assertTrue("submit must return MyCallableFuture",
213 >                       f1 instanceof MyCallableFuture);
214 >            Future f2 = cs.take();
215 >            assertSame("submit and take must return same objects", f1, f2);
216 >            assertTrue("completed task must have set done", done.get());
217          }
218      }
219  
220      /**
221 <     * If timed poll returns non-null, the returned task is completed
222 <     */
223 <    public void testPoll2() throws InterruptedException {
224 <        ExecutorService e = Executors.newCachedThreadPool();
225 <        ExecutorCompletionService ecs = new ExecutorCompletionService(e);
226 <        try {
227 <            assertNull(ecs.poll());
228 <            Callable c = new StringTask();
229 <            ecs.submit(c);
230 <            Future f = ecs.poll(SHORT_DELAY_MS, MILLISECONDS);
231 <            if (f != null)
232 <                assertTrue(f.isDone());
233 <        } finally {
234 <            joinPool(e);
235 <        }
236 <    }
237 <     /**
238 <      * Submitting to underlying AES that overrides newTaskFor(Callable)
239 <      * returns and eventually runs Future returned by newTaskFor.
240 <      */
241 <     public void testNewTaskForCallable() throws InterruptedException {
242 <         final AtomicBoolean done = new AtomicBoolean(false);
243 <         class MyCallableFuture<V> extends FutureTask<V> {
244 <             MyCallableFuture(Callable<V> c) { super(c); }
245 <             protected void done() { done.set(true); }
246 <         }
247 <         ExecutorService e = new ThreadPoolExecutor(
248 <                                 1, 1, 30L, TimeUnit.SECONDS,
164 <                                 new ArrayBlockingQueue<Runnable>(1)) {
165 <             protected <T> RunnableFuture<T> newTaskFor(Callable<T> c) {
166 <                 return new MyCallableFuture<T>(c);
167 <             }
168 <         };
169 <         ExecutorCompletionService<String> ecs =
170 <             new ExecutorCompletionService<String>(e);
171 <         try {
172 <             assertNull(ecs.poll());
173 <             Callable<String> c = new StringTask();
174 <             Future f1 = ecs.submit(c);
175 <             assertTrue("submit must return MyCallableFuture",
176 <                        f1 instanceof MyCallableFuture);
177 <             Future f2 = ecs.take();
178 <             assertSame("submit and take must return same objects", f1, f2);
179 <             assertTrue("completed task must have set done", done.get());
180 <         } finally {
181 <             joinPool(e);
182 <         }
183 <     }
184 <
185 <     /**
186 <      * Submitting to underlying AES that overrides newTaskFor(Runnable,T)
187 <      * returns and eventually runs Future returned by newTaskFor.
188 <      */
189 <     public void testNewTaskForRunnable() throws InterruptedException {
190 <         final AtomicBoolean done = new AtomicBoolean(false);
191 <         class MyRunnableFuture<V> extends FutureTask<V> {
192 <             MyRunnableFuture(Runnable t, V r) { super(t, r); }
193 <             protected void done() { done.set(true); }
194 <         }
195 <         ExecutorService e = new ThreadPoolExecutor(
196 <                                 1, 1, 30L, TimeUnit.SECONDS,
197 <                                 new ArrayBlockingQueue<Runnable>(1)) {
198 <             protected <T> RunnableFuture<T> newTaskFor(Runnable t, T r) {
199 <                 return new MyRunnableFuture<T>(t, r);
200 <             }
201 <         };
202 <         ExecutorCompletionService<String> ecs =
203 <             new ExecutorCompletionService<String>(e);
204 <         try {
205 <             assertNull(ecs.poll());
206 <             Runnable r = new NoOpRunnable();
207 <             Future f1 = ecs.submit(r, null);
208 <             assertTrue("submit must return MyRunnableFuture",
209 <                        f1 instanceof MyRunnableFuture);
210 <             Future f2 = ecs.take();
211 <             assertSame("submit and take must return same objects", f1, f2);
212 <             assertTrue("completed task must have set done", done.get());
213 <         } finally {
214 <             joinPool(e);
215 <         }
216 <     }
221 >     * Submitting to underlying AES that overrides newTaskFor(Runnable,T)
222 >     * returns and eventually runs Future returned by newTaskFor.
223 >     */
224 >    public void testNewTaskForRunnable() throws InterruptedException {
225 >        final AtomicBoolean done = new AtomicBoolean(false);
226 >        class MyRunnableFuture<V> extends FutureTask<V> {
227 >            MyRunnableFuture(Runnable t, V r) { super(t, r); }
228 >            @Override protected void done() { done.set(true); }
229 >        }
230 >        final ExecutorService e =
231 >            new ThreadPoolExecutor(1, 1,
232 >                                   30L, TimeUnit.SECONDS,
233 >                                   new ArrayBlockingQueue<Runnable>(1)) {
234 >                protected <T> RunnableFuture<T> newTaskFor(Runnable t, T r) {
235 >                    return new MyRunnableFuture<T>(t, r);
236 >                }};
237 >        CompletionService<String> cs = new ExecutorCompletionService<>(e);
238 >        try (PoolCleaner cleaner = cleaner(e)) {
239 >            assertNull(cs.poll());
240 >            Runnable r = new NoOpRunnable();
241 >            Future f1 = cs.submit(r, null);
242 >            assertTrue("submit must return MyRunnableFuture",
243 >                       f1 instanceof MyRunnableFuture);
244 >            Future f2 = cs.take();
245 >            assertSame("submit and take must return same objects", f1, f2);
246 >            assertTrue("completed task must have set done", done.get());
247 >        }
248 >    }
249  
250   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines