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

Comparing jsr166/src/test/tck/ExecutorsTest.java (file contents):
Revision 1.2 by dl, Sun Sep 7 20:39:11 2003 UTC vs.
Revision 1.10 by tim, Wed Dec 10 01:51:12 2003 UTC

# Line 10 | Line 10 | import junit.framework.*;
10   import java.util.*;
11   import java.util.concurrent.*;
12   import java.math.BigInteger;
13 + import java.security.*;
14  
15 < public class ExecutorsTest extends TestCase{
15 <    
15 > public class ExecutorsTest extends JSR166TestCase{
16      public static void main(String[] args) {
17 <        junit.textui.TestRunner.run (suite());  
17 >        junit.textui.TestRunner.run (suite());  
18      }
19    
20
19      public static Test suite() {
20 <        return new TestSuite(ExecutorsTest.class);
20 >        return new TestSuite(ExecutorsTest.class);
21      }
22  
23 <    private static long SHORT_DELAY_MS = 100;
24 <    private static long MEDIUM_DELAY_MS = 1000;
25 <    private static long LONG_DELAY_MS = 10000;
26 <
27 <    class SleepRun implements Runnable {
28 <        public void run() {
29 <            try{
30 <                Thread.sleep(MEDIUM_DELAY_MS);
31 <            } catch(InterruptedException e){
34 <                fail("unexpected exception");
35 <            }
23 >    static class TimedCallable<T> implements Callable<T> {
24 >        private final ExecutorService exec;
25 >        private final Callable<T> func;
26 >        private final long msecs;
27 >        
28 >        TimedCallable(ExecutorService exec, Callable<T> func, long msecs) {
29 >            this.exec = exec;
30 >            this.func = func;
31 >            this.msecs = msecs;
32          }
33 <    }
34 <    
35 <
36 <    class SleepCall implements Callable {
37 <        public Object call(){
38 <            try{
39 <                Thread.sleep(MEDIUM_DELAY_MS);
44 <            }catch(InterruptedException e){
45 <                fail("unexpected exception");
33 >        
34 >        public T call() throws Exception {
35 >            Future<T> ftask = exec.submit(func);
36 >            try {
37 >                return ftask.get(msecs, TimeUnit.MILLISECONDS);
38 >            } finally {
39 >                ftask.cancel(true);
40              }
47            return Boolean.TRUE;
41          }
42      }
43  
44  
45 <
46 <    /**
47 <     *  Test to verify execute(Executor, Runnable) will throw
48 <     *  RejectedExecutionException Attempting to execute a runnable on
49 <     *  a full ThreadPool will cause such an exception here, up to 5
50 <     *  runnables are attempted on a pool capable on handling one
51 <     *  until it throws an exception
52 <     */
53 <    public void testExecute1(){
54 <        ThreadPoolExecutor p = new ThreadPoolExecutor(1,1,100L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(1));
55 <        try{
56 <            
57 <            for(int i = 0; i < 5; ++i){
65 <                Executors.execute(p, new SleepRun(), Boolean.TRUE);
45 >    private static class Fib implements Callable<BigInteger> {
46 >        private final BigInteger n;
47 >        Fib(long n) {
48 >            if (n < 0) throw new IllegalArgumentException("need non-negative arg, but got " + n);
49 >            this.n = BigInteger.valueOf(n);
50 >        }
51 >        public BigInteger call() {
52 >            BigInteger f1 = BigInteger.ONE;
53 >            BigInteger f2 = f1;
54 >            for (BigInteger i = BigInteger.ZERO; i.compareTo(n) < 0; i = i.add(BigInteger.ONE)) {
55 >                BigInteger t = f1.add(f2);
56 >                f1 = f2;
57 >                f2 = t;
58              }
59 <            fail("should throw");
60 <        } catch(RejectedExecutionException success){}
61 <        p.shutdownNow();
70 <    }
59 >            return f1;
60 >        }
61 >    };
62  
63      /**
64 <     *  Test to verify execute(Executor, Callable) will throw
65 <     *  RejectedExecutionException Attempting to execute a callable on
66 <     *  a full ThreadPool will cause such an exception here, up to 5
67 <     *  runnables are attempted on a pool capable on handling one
68 <     *  until it throws an exception
69 <     */
70 <    public void testExecute2(){
71 <         ThreadPoolExecutor p = new ThreadPoolExecutor(1,1,100L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(1));
81 <        try{
82 <            for(int i = 0; i < 5; ++i) {
83 <                Executors.execute(p, new SleepCall());
84 <            }
85 <            fail("should throw");
86 <        }catch(RejectedExecutionException e){}
87 <        p.shutdownNow();
64 >     * A newCachedThreadPool can execute runnables
65 >     */
66 >    public void testNewCachedThreadPool1() {
67 >        ExecutorService e = Executors.newCachedThreadPool();
68 >        e.execute(new NoOpRunnable());
69 >        e.execute(new NoOpRunnable());
70 >        e.execute(new NoOpRunnable());
71 >        e.shutdown();
72      }
73  
90
74      /**
75 <     *  Test to verify invoke(Executor, Runnable) throws InterruptedException
76 <     *  A single use of invoke starts that will wait long enough
77 <     *  for the invoking thread to be interrupted
78 <     */
79 <    public void testInvoke2(){
80 <        final ThreadPoolExecutor p = new ThreadPoolExecutor(1,1,100L,TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
81 <        Thread t = new Thread(new Runnable() {
82 <                public void run(){
100 <                    try{
101 <                        Executors.invoke(p,new Runnable(){
102 <                                public void run(){
103 <                                    try{
104 <                                        Thread.sleep(MEDIUM_DELAY_MS);
105 <                                        fail("should throw");
106 <                                    }catch(InterruptedException e){
107 <                                    }
108 <                                }
109 <                            });
110 <                    } catch(InterruptedException success){
111 <                    } catch(Exception e) {
112 <                        fail("unexpected exception");
113 <                    }
114 <                    
115 <                }
116 <            });
117 <        try{
118 <            t.start();
119 <            Thread.sleep(SHORT_DELAY_MS);
120 <            t.interrupt();
121 <        }catch(Exception e){
122 <            fail("unexpected exception");
123 <        }
124 <        p.shutdownNow();
75 >     * A newCachedThreadPool with given ThreadFactory can execute runnables
76 >     */
77 >    public void testNewCachedThreadPool2() {
78 >        ExecutorService e = Executors.newCachedThreadPool(new SimpleThreadFactory());
79 >        e.execute(new NoOpRunnable());
80 >        e.execute(new NoOpRunnable());
81 >        e.execute(new NoOpRunnable());
82 >        e.shutdown();
83      }
84  
85      /**
86 <     *  Test to verify invoke(Executor, Runnable) will throw
87 <     *  ExecutionException An ExecutionException occurs when the
88 <     *  underlying Runnable throws an exception, here the
89 <     *  DivideByZeroException will cause an ExecutionException
90 <     */
91 <    public void testInvoke3(){
92 <        ThreadPoolExecutor p = new ThreadPoolExecutor(1,1,100L,TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
93 <        try{
136 <            Runnable r = new Runnable(){
137 <                    public void run(){
138 <                        int i = 5/0;
139 <                    }
140 <                };
141 <            
142 <            for(int i =0; i < 5; i++){
143 <                Executors.invoke(p,r);
144 <            }
145 <            
146 <            fail("should throw");
147 <        } catch(ExecutionException success){
148 <        } catch(Exception e){
149 <            fail("should throw EE");
86 >     * A newCachedThreadPool with null ThreadFactory throws NPE
87 >     */
88 >    public void testNewCachedThreadPool3() {
89 >        try {
90 >            ExecutorService e = Executors.newCachedThreadPool(null);
91 >            shouldThrow();
92 >        }
93 >        catch(NullPointerException success) {
94          }
151        p.shutdownNow();
95      }
96  
97  
155
98      /**
99 <     *  Test to verify invoke(Executor, Callable) throws
158 <     *  InterruptedException A single use of invoke starts that will
159 <     *  wait long enough for the invoking thread to be interrupted
99 >     * A new SingleThreadExecutor can execute runnables
100       */
101 <    public void testInvoke5(){
102 <        final ThreadPoolExecutor p = new ThreadPoolExecutor(1,1,100L,TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
103 <        
104 <        final Callable c = new Callable(){
105 <                public Object call(){
106 <                    try{
167 <                        Executors.invoke(p, new SleepCall());
168 <                        fail("should throw");
169 <                    }catch(InterruptedException e){}
170 <                    catch(RejectedExecutionException e2){}
171 <                    catch(ExecutionException e3){}
172 <                    return Boolean.TRUE;
173 <                }
174 <            };
175 <
176 <
177 <        
178 <        Thread t = new Thread(new Runnable(){
179 <                public void run(){
180 <                    try{
181 <                        c.call();
182 <                    }catch(Exception e){}
183 <                }
184 <          });
185 <        try{
186 <            t.start();
187 <            Thread.sleep(SHORT_DELAY_MS);
188 <            t.interrupt();
189 <            t.join();
190 <        }catch(InterruptedException e){
191 <            fail("unexpected exception");
192 <        }
193 <        
194 <        p.shutdownNow();
101 >    public void testNewSingleThreadExecutor1() {
102 >        ExecutorService e = Executors.newSingleThreadExecutor();
103 >        e.execute(new NoOpRunnable());
104 >        e.execute(new NoOpRunnable());
105 >        e.execute(new NoOpRunnable());
106 >        e.shutdown();
107      }
108  
109      /**
110 <     *  Test to verify invoke(Executor, Callable) will throw ExecutionException
199 <     *  An ExecutionException occurs when the underlying Runnable throws
200 <     *  an exception, here the DivideByZeroException will cause an ExecutionException
110 >     * A new SingleThreadExecutor with given ThreadFactory can execute runnables
111       */
112 <    public void testInvoke6(){
113 <        ThreadPoolExecutor p = new ThreadPoolExecutor(1,1,100L,TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
114 <
115 <        try{
116 <            Callable c = new Callable(){
117 <                    public Object call(){
208 <                        int i = 5/0;
209 <                        return Boolean.TRUE;
210 <                    }
211 <                };
212 <            
213 <            for(int i =0; i < 5; i++){
214 <                Executors.invoke(p,c);
215 <            }
216 <            
217 <            fail("should throw");
218 <        }catch(RejectedExecutionException e){}
219 <        catch(InterruptedException e2){}
220 <        catch(ExecutionException e3){}
221 <        p.shutdownNow();
112 >    public void testNewSingleThreadExecutor2() {
113 >        ExecutorService e = Executors.newSingleThreadExecutor(new SimpleThreadFactory());
114 >        e.execute(new NoOpRunnable());
115 >        e.execute(new NoOpRunnable());
116 >        e.execute(new NoOpRunnable());
117 >        e.shutdown();
118      }
119  
120 <    public void testExecuteRunnable () {
120 >    /**
121 >     * A new SingleThreadExecutor with null ThreadFactory throws NPE
122 >     */
123 >    public void testNewSingleThreadExecutor3() {
124          try {
125 <            Executor e = new DirectExecutor();
126 <            Task task = new Task();
228 <
229 <            assertFalse("task should not be complete", task.isCompleted());
230 <
231 <            Future<String> future = Executors.execute(e, task, TEST_STRING);
232 <            String result = future.get();
233 <
234 <            assertTrue("task should be complete", task.isCompleted());
235 <            assertSame("should return test string", TEST_STRING, result);
236 <        }
237 <        catch (ExecutionException ex) {
238 <            fail("Unexpected exception");
125 >            ExecutorService e = Executors.newSingleThreadExecutor(null);
126 >            shouldThrow();
127          }
128 <        catch (InterruptedException ex) {
241 <            fail("Unexpected exception");
128 >        catch(NullPointerException success) {
129          }
130      }
131  
132 <    public void testInvokeRunnable () {
133 <        try {
134 <            Executor e = new DirectExecutor();
135 <            Task task = new Task();
136 <
137 <            assertFalse("task should not be complete", task.isCompleted());
138 <
139 <            Executors.invoke(e, task);
132 >    /**
133 >     * A new newFixedThreadPool can execute runnables
134 >     */
135 >    public void testNewFixedThreadPool1() {
136 >        ExecutorService e = Executors.newFixedThreadPool(2);
137 >        e.execute(new NoOpRunnable());
138 >        e.execute(new NoOpRunnable());
139 >        e.execute(new NoOpRunnable());
140 >        e.shutdown();
141 >    }
142  
143 <            assertTrue("task should be complete", task.isCompleted());
144 <        }
145 <        catch (ExecutionException ex) {
146 <            fail("Unexpected exception");
147 <        }
148 <        catch (InterruptedException ex) {
149 <            fail("Unexpected exception");
150 <        }
143 >    /**
144 >     * A new newFixedThreadPool with given ThreadFactory can execute runnables
145 >     */
146 >    public void testNewFixedThreadPool2() {
147 >        ExecutorService e = Executors.newFixedThreadPool(2, new SimpleThreadFactory());
148 >        e.execute(new NoOpRunnable());
149 >        e.execute(new NoOpRunnable());
150 >        e.execute(new NoOpRunnable());
151 >        e.shutdown();
152      }
153  
154 <    public void testExecuteCallable () {
154 >    /**
155 >     * A new newFixedThreadPool with null ThreadFactory throws NPE
156 >     */
157 >    public void testNewFixedThreadPool3() {
158          try {
159 <            Executor e = new DirectExecutor();
160 <            Future<String> future = Executors.execute(e, new StringTask());
268 <            String result = future.get();
269 <
270 <            assertSame("should return test string", TEST_STRING, result);
271 <        }
272 <        catch (ExecutionException ex) {
273 <            fail("Unexpected exception");
159 >            ExecutorService e = Executors.newFixedThreadPool(2, null);
160 >            shouldThrow();
161          }
162 <        catch (InterruptedException ex) {
276 <            fail("Unexpected exception");
162 >        catch(NullPointerException success) {
163          }
164      }
165  
166 <    public void testInvokeCallable () {
166 >    /**
167 >     * A new newFixedThreadPool with 0 threads throws IAE
168 >     */
169 >    public void testNewFixedThreadPool4() {
170          try {
171 <            Executor e = new DirectExecutor();
172 <            String result = Executors.invoke(e, new StringTask());
284 <
285 <            assertSame("should return test string", TEST_STRING, result);
286 <        }
287 <        catch (ExecutionException ex) {
288 <            fail("Unexpected exception" );
171 >            ExecutorService e = Executors.newFixedThreadPool(0);
172 >            shouldThrow();
173          }
174 <        catch (InterruptedException ex) {
291 <            fail("Unexpected exception");
174 >        catch(IllegalArgumentException success) {
175          }
176      }
177  
295    private static final String TEST_STRING = "a test string";
296
297    private static class Task implements Runnable {
298        public void run() { completed = true; }
299        public boolean isCompleted() { return completed; }
300        public void reset() { completed = false; }
301        private boolean completed = false;
302    }
303
304    private static class StringTask implements Callable<String> {
305        public String call() { return TEST_STRING; }
306    }
307
308    static class DirectExecutor implements Executor {
309        public void execute(Runnable r) {
310            r.run();
311        }
312    }
178  
179      /**
180 <     * Check that timeouts from execute will time out if they compute
316 <     * too long.
180 >     *  timeouts from execute will time out if they compute too long.
181       */
318
182      public void testTimedCallable() {
183          int N = 10000;
184          ExecutorService executor = Executors.newSingleThreadExecutor();
# Line 341 | Line 204 | public class ExecutorsTest extends TestC
204                      return;
205                  }
206                  catch (Exception e) {
207 <                    fail("unexpected exception: " + e);
207 >                    unexpectedException();
208                  }
209              }
210              // if by chance we didn't ever time out, total time must be small
# Line 349 | Line 212 | public class ExecutorsTest extends TestC
212              assertTrue(elapsed < N);
213          }
214          finally {
215 <            executor.shutdownNow();
215 >            joinPool(executor);
216          }
217      }
218  
219      
220 <    static class TimedCallable<T> implements Callable<T> {
221 <        private final Executor exec;
222 <        private final Callable<T> func;
223 <        private final long msecs;
224 <        
225 <        TimedCallable(Executor exec, Callable<T> func, long msecs) {
226 <            this.exec = exec;
227 <            this.func = func;
228 <            this.msecs = msecs;
229 <        }
220 >    /**
221 >     * ThreadPoolExecutor using defaultThreadFactory has
222 >     * specified group, priority, daemon status, and name
223 >     */
224 >    public void testDefaultThreadFactory() {
225 >        final ThreadGroup egroup = Thread.currentThread().getThreadGroup();
226 >        Runnable r = new Runnable() {
227 >                public void run() {
228 >                    Thread current = Thread.currentThread();
229 >                    threadAssertTrue(!current.isDaemon());
230 >                    threadAssertTrue(current.getPriority() == Thread.NORM_PRIORITY);
231 >                    ThreadGroup g = current.getThreadGroup();
232 >                    SecurityManager s = System.getSecurityManager();
233 >                    if (s != null)
234 >                        threadAssertTrue(g == s.getThreadGroup());
235 >                    else
236 >                        threadAssertTrue(g == egroup);
237 >                    String name = current.getName();
238 >                    threadAssertTrue(name.endsWith("thread-1"));
239 >                }
240 >            };
241 >        ExecutorService e = Executors.newSingleThreadExecutor(Executors.defaultThreadFactory());
242          
243 <        public T call() throws Exception {
244 <            Future<T> ftask = Executors.execute(exec, func);
245 <            try {
246 <                return ftask.get(msecs, TimeUnit.MILLISECONDS);
247 <            } finally {
248 <                ftask.cancel(true);
249 <            }
243 >        e.execute(r);
244 >        e.shutdown();
245 >        try {
246 >            Thread.sleep(SHORT_DELAY_MS);
247 >        } catch (Exception eX) {
248 >            unexpectedException();
249 >        } finally {
250 >            joinPool(e);
251          }
252      }
253  
254 <
255 <    private static class Fib implements Callable<BigInteger> {
256 <        private final BigInteger n;
257 <        Fib(long n) {
258 <            if (n < 0) throw new IllegalArgumentException("need non-negative arg, but got " + n);
259 <            this.n = BigInteger.valueOf(n);
260 <        }
261 <        public BigInteger call() {
262 <            BigInteger f1 = BigInteger.ONE;
263 <            BigInteger f2 = f1;
264 <            for (BigInteger i = BigInteger.ZERO; i.compareTo(n) < 0; i = i.add(BigInteger.ONE)) {
265 <                BigInteger t = f1.add(f2);
266 <                f1 = f2;
267 <                f2 = t;
268 <            }
269 <            return f1;
254 >    /**
255 >     * ThreadPoolExecutor using privilegedThreadFactory has
256 >     * specified group, priority, daemon status, name,
257 >     * access control context and context class loader
258 >     */
259 >    public void testPrivilegedThreadFactory() {
260 >        Policy savedPolicy = Policy.getPolicy();
261 >        AdjustablePolicy policy = new AdjustablePolicy();
262 >        policy.addPermission(new RuntimePermission("getContextClassLoader"));
263 >        policy.addPermission(new RuntimePermission("setContextClassLoader"));
264 >        Policy.setPolicy(policy);
265 >        final ThreadGroup egroup = Thread.currentThread().getThreadGroup();
266 >        final ClassLoader thisccl = Thread.currentThread().getContextClassLoader();
267 >        final AccessControlContext thisacc = AccessController.getContext();
268 >        Runnable r = new Runnable() {
269 >                public void run() {
270 >                    Thread current = Thread.currentThread();
271 >                    threadAssertTrue(!current.isDaemon());
272 >                    threadAssertTrue(current.getPriority() == Thread.NORM_PRIORITY);
273 >                    ThreadGroup g = current.getThreadGroup();
274 >                    SecurityManager s = System.getSecurityManager();
275 >                    if (s != null)
276 >                        threadAssertTrue(g == s.getThreadGroup());
277 >                    else
278 >                        threadAssertTrue(g == egroup);
279 >                    String name = current.getName();
280 >                    threadAssertTrue(name.endsWith("thread-1"));
281 >                    threadAssertTrue(thisccl == current.getContextClassLoader());
282 >                    threadAssertTrue(thisacc.equals(AccessController.getContext()));
283 >                }
284 >            };
285 >        ExecutorService e = Executors.newSingleThreadExecutor(Executors.privilegedThreadFactory());
286 >        
287 >        Policy.setPolicy(savedPolicy);
288 >        e.execute(r);
289 >        e.shutdown();
290 >        try {
291 >            Thread.sleep(SHORT_DELAY_MS);
292 >        } catch (Exception ex) {
293 >            unexpectedException();
294 >        } finally {
295 >            joinPool(e);
296          }
395    };
396
297  
298 +    }
299  
300   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines