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.3 by dl, Sun Sep 14 20:42:40 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 JSR166TestCase{
15    
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 <    /**
24 <     *   execute(Executor, Runnable) will throw
25 <     *  RejectedExecutionException Attempting to execute a runnable on
26 <     *  a full ThreadPool will cause such an exception here, up to 5
27 <     *  runnables are attempted on a pool capable on handling one
28 <     *  until it throws an exception
29 <     */
30 <    public void testExecute1(){
31 <        ThreadPoolExecutor p = new ThreadPoolExecutor(1,1, SHORT_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(1));
32 <        try{
33 <            
34 <            for(int i = 0; i < 5; ++i){
35 <                Executors.execute(p, new MediumRunnable(), Boolean.TRUE);
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 <            fail("should throw");
40 <        } catch(RejectedExecutionException success){}
41 <        joinPool(p);
41 >        }
42      }
43  
44 <    /**
45 <     *   execute(Executor, Callable) will throw
46 <     *  RejectedExecutionException Attempting to execute a callable on
47 <     *  a full ThreadPool will cause such an exception here, up to 5
48 <     *  runnables are attempted on a pool capable on handling one
49 <     *  until it throws an exception
50 <     */
51 <    public void testExecute2(){
52 <         ThreadPoolExecutor p = new ThreadPoolExecutor(1,1, SHORT_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(1));
53 <        try{
54 <            for(int i = 0; i < 5; ++i) {
55 <                Executors.execute(p, new SmallCallable());
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 <            fail("should throw");
60 <        }catch(RejectedExecutionException e){}
61 <        joinPool(p);
60 <    }
59 >            return f1;
60 >        }
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 <     *   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,SHORT_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
81 <        Thread t = new Thread(new Runnable() {
82 <                public void run(){
72 <                    try{
73 <                        Executors.invoke(p,new Runnable(){
74 <                                public void run(){
75 <                                    try{
76 <                                        Thread.sleep(MEDIUM_DELAY_MS);
77 <                                        fail("should throw");
78 <                                    }catch(InterruptedException e){
79 <                                    }
80 <                                }
81 <                            });
82 <                    } catch(InterruptedException success){
83 <                    } catch(Exception e) {
84 <                        fail("unexpected exception");
85 <                    }
86 <                    
87 <                }
88 <            });
89 <        try{
90 <            t.start();
91 <            Thread.sleep(SHORT_DELAY_MS);
92 <            t.interrupt();
93 <        }catch(Exception e){
94 <            fail("unexpected exception");
95 <        }
96 <        joinPool(p);
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 <     *   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,SHORT_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
93 <        try{
108 <            Runnable r = new Runnable(){
109 <                    public void run(){
110 <                        int i = 5/0;
111 <                    }
112 <                };
113 <            
114 <            for(int i =0; i < 5; i++){
115 <                Executors.invoke(p,r);
116 <            }
117 <            
118 <            fail("should throw");
119 <        } catch(ExecutionException success){
120 <        } catch(Exception e){
121 <            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          }
123        joinPool(p);
95      }
96  
97  
127
98      /**
99 <     *   invoke(Executor, Callable) throws
130 <     *  InterruptedException A single use of invoke starts that will
131 <     *  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,SHORT_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
103 <        
104 <        final Callable c = new Callable(){
105 <                public Object call(){
106 <                    try{
139 <                        Executors.invoke(p, new SmallCallable());
140 <                        fail("should throw");
141 <                    }catch(InterruptedException e){}
142 <                    catch(RejectedExecutionException e2){}
143 <                    catch(ExecutionException e3){}
144 <                    return Boolean.TRUE;
145 <                }
146 <            };
147 <
148 <
149 <        
150 <        Thread t = new Thread(new Runnable(){
151 <                public void run(){
152 <                    try{
153 <                        c.call();
154 <                    }catch(Exception e){}
155 <                }
156 <          });
157 <        try{
158 <            t.start();
159 <            Thread.sleep(SHORT_DELAY_MS);
160 <            t.interrupt();
161 <            t.join();
162 <        }catch(InterruptedException e){
163 <            fail("unexpected exception");
164 <        }
165 <        
166 <        joinPool(p);
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 <     *   invoke(Executor, Callable) will throw ExecutionException
171 <     *  An ExecutionException occurs when the underlying Runnable throws
172 <     *  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,SHORT_DELAY_MS, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
114 <
115 <        try{
116 <            Callable c = new Callable(){
117 <                    public Object call(){
180 <                        int i = 5/0;
181 <                        return Boolean.TRUE;
182 <                    }
183 <                };
184 <            
185 <            for(int i =0; i < 5; i++){
186 <                Executors.invoke(p,c);
187 <            }
188 <            
189 <            fail("should throw");
190 <        }catch(RejectedExecutionException e){}
191 <        catch(InterruptedException e2){}
192 <        catch(ExecutionException e3){}
193 <        joinPool(p);
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();
200 <
201 <            assertFalse("task should not be complete", task.isCompleted());
202 <
203 <            Future<String> future = Executors.execute(e, task, TEST_STRING);
204 <            String result = future.get();
205 <
206 <            assertTrue("task should be complete", task.isCompleted());
207 <            assertSame("should return test string", TEST_STRING, result);
208 <        }
209 <        catch (ExecutionException ex) {
210 <            fail("Unexpected exception");
125 >            ExecutorService e = Executors.newSingleThreadExecutor(null);
126 >            shouldThrow();
127          }
128 <        catch (InterruptedException ex) {
213 <            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());
240 <            String result = future.get();
241 <
242 <            assertSame("should return test string", TEST_STRING, result);
243 <        }
244 <        catch (ExecutionException ex) {
245 <            fail("Unexpected exception");
159 >            ExecutorService e = Executors.newFixedThreadPool(2, null);
160 >            shouldThrow();
161          }
162 <        catch (InterruptedException ex) {
248 <            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());
256 <
257 <            assertSame("should return test string", TEST_STRING, result);
258 <        }
259 <        catch (ExecutionException ex) {
260 <            fail("Unexpected exception" );
171 >            ExecutorService e = Executors.newFixedThreadPool(0);
172 >            shouldThrow();
173          }
174 <        catch (InterruptedException ex) {
263 <            fail("Unexpected exception");
174 >        catch(IllegalArgumentException success) {
175          }
176      }
177  
267    private static final String TEST_STRING = "a test string";
268
269    private static class Task implements Runnable {
270        public void run() { completed = true; }
271        public boolean isCompleted() { return completed; }
272        public void reset() { completed = false; }
273        private boolean completed = false;
274    }
275
276    private static class StringTask implements Callable<String> {
277        public String call() { return TEST_STRING; }
278    }
279
280    static class DirectExecutor implements Executor {
281        public void execute(Runnable r) {
282            r.run();
283        }
284    }
178  
179      /**
180 <     * Check that timeouts from execute will time out if they compute
288 <     * too long.
180 >     *  timeouts from execute will time out if they compute too long.
181       */
290
182      public void testTimedCallable() {
183          int N = 10000;
184          ExecutorService executor = Executors.newSingleThreadExecutor();
# Line 313 | Line 204 | public class ExecutorsTest extends JSR16
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 326 | Line 217 | public class ExecutorsTest extends JSR16
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          }
367    };
368
297  
298 +    }
299  
300   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines