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.1 by dl, Sun Aug 31 19:24:55 2003 UTC vs.
Revision 1.10 by tim, Wed Dec 10 01:51:12 2003 UTC

# Line 9 | Line 9
9   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{
14 <    
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      }
18    
19
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){
32 <                fail("unexpected exception");
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 >        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              }
41          }
42      }
37    
43  
44 <    class SleepCall implements Callable {
45 <        public Object call(){
46 <            try{
47 <                Thread.sleep(MEDIUM_DELAY_MS);
48 <            }catch(InterruptedException e){
49 <                fail("unexpected exception");
44 >
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 <            return Boolean.TRUE;
59 >            return f1;
60          }
61 <    }
49 <
61 >    };
62  
63 +    /**
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  
74      /**
75 <     *  Test to verify execute(Executor, Runnable) will throw
54 <     *  RejectedExecutionException Attempting to execute a runnable on
55 <     *  a full ThreadPool will cause such an exception here, up to 5
56 <     *  runnables are attempted on a pool capable on handling one
57 <     *  until it throws an exception
75 >     * A newCachedThreadPool with given ThreadFactory can execute runnables
76       */
77 <    public void testExecute1(){
78 <        ThreadPoolExecutor p = new ThreadPoolExecutor(1,1,100L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(1));
79 <        try{
80 <            
81 <            for(int i = 0; i < 5; ++i){
82 <                Executors.execute(p, new SleepRun(), Boolean.TRUE);
65 <            }
66 <            fail("should throw");
67 <        } catch(RejectedExecutionException success){}
68 <        p.shutdownNow();
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 execute(Executor, Callable) will throw
87 <     *  RejectedExecutionException Attempting to execute a callable on
88 <     *  a full ThreadPool will cause such an exception here, up to 5
89 <     *  runnables are attempted on a pool capable on handling one
90 <     *  until it throws an exception
91 <     */
92 <    public void testExecute2(){
93 <         ThreadPoolExecutor p = new ThreadPoolExecutor(1,1,100L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(1));
94 <        try{
81 <            for(int i = 0; i < 5; ++i) {
82 <                Executors.execute(p, new SleepCall());
83 <            }
84 <            fail("should throw");
85 <        }catch(RejectedExecutionException e){}
86 <        p.shutdownNow();
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 >        }
95      }
96  
97  
98      /**
99 <     *  Test to verify invoke(Executor, Runnable) throws InterruptedException
100 <     *  A single use of invoke starts that will wait long enough
101 <     *  for the invoking thread to be interrupted
102 <     */
103 <    public void testInvoke2(){
104 <        final ThreadPoolExecutor p = new ThreadPoolExecutor(1,1,100L,TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
105 <        Thread t = new Thread(new Runnable() {
106 <                public void run(){
99 <                    try{
100 <                        Executors.invoke(p,new Runnable(){
101 <                                public void run(){
102 <                                    try{
103 <                                        Thread.sleep(MEDIUM_DELAY_MS);
104 <                                        fail("should throw");
105 <                                    }catch(InterruptedException e){
106 <                                    }
107 <                                }
108 <                            });
109 <                    } catch(InterruptedException success){
110 <                    } catch(Exception e) {
111 <                        fail("unexpected exception");
112 <                    }
113 <                    
114 <                }
115 <            });
116 <        try{
117 <            t.start();
118 <            Thread.sleep(SHORT_DELAY_MS);
119 <            t.interrupt();
120 <        }catch(Exception e){
121 <            fail("unexpected exception");
122 <        }
123 <        p.shutdownNow();
99 >     * A new SingleThreadExecutor can execute runnables
100 >     */
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, Runnable) will throw
111 <     *  ExecutionException An ExecutionException occurs when the
112 <     *  underlying Runnable throws an exception, here the
113 <     *  DivideByZeroException will cause an ExecutionException
114 <     */
115 <    public void testInvoke3(){
116 <        ThreadPoolExecutor p = new ThreadPoolExecutor(1,1,100L,TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
117 <        try{
135 <            Runnable r = new Runnable(){
136 <                    public void run(){
137 <                        int i = 5/0;
138 <                    }
139 <                };
140 <            
141 <            for(int i =0; i < 5; i++){
142 <                Executors.invoke(p,r);
143 <            }
144 <            
145 <            fail("should throw");
146 <        } catch(ExecutionException success){
147 <        } catch(Exception e){
148 <            fail("should throw EE");
149 <        }
150 <        p.shutdownNow();
110 >     * A new SingleThreadExecutor with given ThreadFactory can execute runnables
111 >     */
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  
153
154
120      /**
121 <     *  Test to verify invoke(Executor, Callable) throws
157 <     *  InterruptedException A single use of invoke starts that will
158 <     *  wait long enough for the invoking thread to be interrupted
121 >     * A new SingleThreadExecutor with null ThreadFactory throws NPE
122       */
123 <    public void testInvoke5(){
124 <        final ThreadPoolExecutor p = new ThreadPoolExecutor(1,1,100L,TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
125 <        
126 <        final Callable c = new Callable(){
127 <                public Object call(){
128 <                    try{
166 <                        Executors.invoke(p, new SleepCall());
167 <                        fail("should throw");
168 <                    }catch(InterruptedException e){}
169 <                    catch(RejectedExecutionException e2){}
170 <                    catch(ExecutionException e3){}
171 <                    return Boolean.TRUE;
172 <                }
173 <            };
174 <
175 <
176 <        
177 <        Thread t = new Thread(new Runnable(){
178 <                public void run(){
179 <                    try{
180 <                        c.call();
181 <                    }catch(Exception e){}
182 <                }
183 <          });
184 <        try{
185 <            t.start();
186 <            Thread.sleep(SHORT_DELAY_MS);
187 <            t.interrupt();
188 <            t.join();
189 <        }catch(InterruptedException e){
190 <            fail("unexpected exception");
123 >    public void testNewSingleThreadExecutor3() {
124 >        try {
125 >            ExecutorService e = Executors.newSingleThreadExecutor(null);
126 >            shouldThrow();
127 >        }
128 >        catch(NullPointerException success) {
129          }
192        
193        p.shutdownNow();
130      }
131  
132      /**
133 <     *  Test to verify invoke(Executor, Callable) will throw ExecutionException
198 <     *  An ExecutionException occurs when the underlying Runnable throws
199 <     *  an exception, here the DivideByZeroException will cause an ExecutionException
133 >     * A new newFixedThreadPool can execute runnables
134       */
135 <    public void testInvoke6(){
136 <        ThreadPoolExecutor p = new ThreadPoolExecutor(1,1,100L,TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
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 <        try{
144 <            Callable c = new Callable(){
145 <                    public Object call(){
146 <                        int i = 5/0;
147 <                        return Boolean.TRUE;
148 <                    }
149 <                };
150 <            
151 <            for(int i =0; i < 5; i++){
213 <                Executors.invoke(p,c);
214 <            }
215 <            
216 <            fail("should throw");
217 <        }catch(RejectedExecutionException e){}
218 <        catch(InterruptedException e2){}
219 <        catch(ExecutionException e3){}
220 <        p.shutdownNow();
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 testExecuteRunnable () {
154 >    /**
155 >     * A new newFixedThreadPool with null ThreadFactory throws NPE
156 >     */
157 >    public void testNewFixedThreadPool3() {
158          try {
159 <            Executor e = new DirectExecutor();
160 <            Task task = new Task();
227 <
228 <            assertFalse("task should not be complete", task.isCompleted());
229 <
230 <            Future<String> future = Executors.execute(e, task, TEST_STRING);
231 <            String result = future.get();
232 <
233 <            assertTrue("task should be complete", task.isCompleted());
234 <            assertSame("should return test string", TEST_STRING, result);
235 <        }
236 <        catch (ExecutionException ex) {
237 <            fail("Unexpected exception");
159 >            ExecutorService e = Executors.newFixedThreadPool(2, null);
160 >            shouldThrow();
161          }
162 <        catch (InterruptedException ex) {
240 <            fail("Unexpected exception");
162 >        catch(NullPointerException success) {
163          }
164      }
165  
166 <    public void testInvokeRunnable () {
166 >    /**
167 >     * A new newFixedThreadPool with 0 threads throws IAE
168 >     */
169 >    public void testNewFixedThreadPool4() {
170          try {
171 <            Executor e = new DirectExecutor();
172 <            Task task = new Task();
248 <
249 <            assertFalse("task should not be complete", task.isCompleted());
250 <
251 <            Executors.invoke(e, task);
252 <
253 <            assertTrue("task should be complete", task.isCompleted());
254 <        }
255 <        catch (ExecutionException ex) {
256 <            fail("Unexpected exception");
171 >            ExecutorService e = Executors.newFixedThreadPool(0);
172 >            shouldThrow();
173          }
174 <        catch (InterruptedException ex) {
259 <            fail("Unexpected exception");
174 >        catch(IllegalArgumentException success) {
175          }
176      }
177  
263    public void testExecuteCallable () {
264        try {
265            Executor e = new DirectExecutor();
266            Future<String> future = Executors.execute(e, new StringTask());
267            String result = future.get();
178  
179 <            assertSame("should return test string", TEST_STRING, result);
180 <        }
181 <        catch (ExecutionException ex) {
182 <            fail("Unexpected exception");
179 >    /**
180 >     *  timeouts from execute will time out if they compute too long.
181 >     */
182 >    public void testTimedCallable() {
183 >        int N = 10000;
184 >        ExecutorService executor = Executors.newSingleThreadExecutor();
185 >        List<Callable<BigInteger>> tasks = new ArrayList<Callable<BigInteger>>(N);
186 >        try {
187 >            long startTime = System.currentTimeMillis();
188 >            
189 >            long i = 0;
190 >            while (tasks.size() < N) {
191 >                tasks.add(new TimedCallable<BigInteger>(executor, new Fib(i), 1));
192 >                i += 10;
193 >            }
194 >            
195 >            int iters = 0;
196 >            BigInteger sum = BigInteger.ZERO;
197 >            for (Iterator<Callable<BigInteger>> it = tasks.iterator(); it.hasNext();) {
198 >                try {
199 >                    ++iters;
200 >                    sum = sum.add(it.next().call());
201 >                }
202 >                catch (TimeoutException success) {
203 >                    assertTrue(iters > 0);
204 >                    return;
205 >                }
206 >                catch (Exception e) {
207 >                    unexpectedException();
208 >                }
209 >            }
210 >            // if by chance we didn't ever time out, total time must be small
211 >            long elapsed = System.currentTimeMillis() - startTime;
212 >            assertTrue(elapsed < N);
213          }
214 <        catch (InterruptedException ex) {
215 <            fail("Unexpected exception");
214 >        finally {
215 >            joinPool(executor);
216          }
217      }
218  
219 <    public void testInvokeCallable () {
219 >    
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 >        e.execute(r);
244 >        e.shutdown();
245          try {
246 <            Executor e = new DirectExecutor();
247 <            String result = Executors.invoke(e, new StringTask());
248 <
249 <            assertSame("should return test string", TEST_STRING, result);
250 <        }
286 <        catch (ExecutionException ex) {
287 <            fail("Unexpected exception" );
288 <        }
289 <        catch (InterruptedException ex) {
290 <            fail("Unexpected exception");
246 >            Thread.sleep(SHORT_DELAY_MS);
247 >        } catch (Exception eX) {
248 >            unexpectedException();
249 >        } finally {
250 >            joinPool(e);
251          }
252      }
253  
254 <    private static final String TEST_STRING = "a test string";
255 <
256 <    private static class Task implements Runnable {
257 <        public void run() { completed = true; }
258 <        public boolean isCompleted() { return completed; }
259 <        public void reset() { completed = false; }
260 <        private boolean completed = false;
261 <    }
262 <
263 <    private static class StringTask implements Callable<String> {
264 <        public String call() { return TEST_STRING; }
265 <    }
266 <
267 <    static class DirectExecutor implements Executor {
268 <        public void execute(Runnable r) {
269 <            r.run();
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          }
311    }
297  
298 +    }
299  
300   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines