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

Comparing jsr166/src/test/tck/ThreadPoolExecutorTest.java (file contents):
Revision 1.38 by jsr166, Wed Nov 17 23:12:31 2010 UTC vs.
Revision 1.50 by jsr166, Wed Dec 31 19:05:43 2014 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 import java.util.concurrent.*;
9   import static java.util.concurrent.TimeUnit.MILLISECONDS;
10 < import java.util.concurrent.atomic.*;
11 < import junit.framework.*;
12 < import java.util.*;
10 > import static java.util.concurrent.TimeUnit.NANOSECONDS;
11 >
12 > import java.util.ArrayList;
13 > import java.util.List;
14 > import java.util.concurrent.ArrayBlockingQueue;
15 > import java.util.concurrent.BlockingQueue;
16 > import java.util.concurrent.Callable;
17 > import java.util.concurrent.CountDownLatch;
18 > import java.util.concurrent.ExecutionException;
19 > import java.util.concurrent.Executors;
20 > import java.util.concurrent.ExecutorService;
21 > import java.util.concurrent.Future;
22 > import java.util.concurrent.FutureTask;
23 > import java.util.concurrent.LinkedBlockingQueue;
24 > import java.util.concurrent.RejectedExecutionException;
25 > import java.util.concurrent.RejectedExecutionHandler;
26 > import java.util.concurrent.SynchronousQueue;
27 > import java.util.concurrent.ThreadFactory;
28 > import java.util.concurrent.ThreadPoolExecutor;
29 > import java.util.concurrent.TimeUnit;
30 >
31 > import junit.framework.Test;
32 > import junit.framework.TestSuite;
33  
34   public class ThreadPoolExecutorTest extends JSR166TestCase {
35      public static void main(String[] args) {
# Line 21 | Line 40 | public class ThreadPoolExecutorTest exte
40      }
41  
42      static class ExtendedTPE extends ThreadPoolExecutor {
43 <        volatile boolean beforeCalled = false;
44 <        volatile boolean afterCalled = false;
45 <        volatile boolean terminatedCalled = false;
43 >        final CountDownLatch beforeCalled = new CountDownLatch(1);
44 >        final CountDownLatch afterCalled = new CountDownLatch(1);
45 >        final CountDownLatch terminatedCalled = new CountDownLatch(1);
46 >
47          public ExtendedTPE() {
48              super(1, 1, LONG_DELAY_MS, MILLISECONDS, new SynchronousQueue<Runnable>());
49          }
50          protected void beforeExecute(Thread t, Runnable r) {
51 <            beforeCalled = true;
51 >            beforeCalled.countDown();
52          }
53          protected void afterExecute(Runnable r, Throwable t) {
54 <            afterCalled = true;
54 >            afterCalled.countDown();
55          }
56          protected void terminated() {
57 <            terminatedCalled = true;
57 >            terminatedCalled.countDown();
58 >        }
59 >
60 >        public boolean beforeCalled() {
61 >            return beforeCalled.getCount() == 0;
62 >        }
63 >        public boolean afterCalled() {
64 >            return afterCalled.getCount() == 0;
65 >        }
66 >        public boolean terminatedCalled() {
67 >            return terminatedCalled.getCount() == 0;
68          }
69      }
70  
# Line 46 | Line 76 | public class ThreadPoolExecutorTest exte
76          }
77      }
78  
49
79      /**
80       * execute successfully executes a runnable
81       */
# Line 150 | Line 179 | public class ThreadPoolExecutorTest exte
179                      threadProceed.await();
180                      threadDone.countDown();
181                  }});
182 <            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
182 >            await(threadStarted);
183              assertEquals(0, p.getCompletedTaskCount());
184              threadProceed.countDown();
185              threadDone.await();
186 <            Thread.sleep(SHORT_DELAY_MS);
187 <            assertEquals(1, p.getCompletedTaskCount());
186 >            long startTime = System.nanoTime();
187 >            while (p.getCompletedTaskCount() != 1) {
188 >                if (millisElapsedSince(startTime) > LONG_DELAY_MS)
189 >                    fail("timed out");
190 >                Thread.yield();
191 >            }
192          } finally {
193              joinPool(p);
194          }
# Line 185 | Line 218 | public class ThreadPoolExecutorTest exte
218          joinPool(p);
219      }
220  
188
221      /**
222       * getThreadFactory returns factory in constructor if not set
223       */
# Line 215 | Line 247 | public class ThreadPoolExecutorTest exte
247          joinPool(p);
248      }
249  
218
250      /**
251       * setThreadFactory(null) throws NPE
252       */
# Line 262 | Line 293 | public class ThreadPoolExecutorTest exte
293          joinPool(p);
294      }
295  
265
296      /**
297       * setRejectedExecutionHandler(null) throws NPE
298       */
# Line 280 | Line 310 | public class ThreadPoolExecutorTest exte
310          }
311      }
312  
283
313      /**
314       * getLargestPoolSize increases, but doesn't overestimate, when
315       * multiple threads active
# Line 378 | Line 407 | public class ThreadPoolExecutorTest exte
407      }
408  
409      /**
410 <     * isShutDown is false before shutdown, true after
410 >     * isShutdown is false before shutdown, true after
411       */
412      public void testIsShutdown() {
413          final ThreadPoolExecutor p =
# Line 391 | Line 420 | public class ThreadPoolExecutorTest exte
420          joinPool(p);
421      }
422  
423 +    /**
424 +     * awaitTermination on a non-shutdown pool times out
425 +     */
426 +    public void testAwaitTermination_timesOut() throws InterruptedException {
427 +        final ThreadPoolExecutor p =
428 +            new ThreadPoolExecutor(1, 1,
429 +                                   LONG_DELAY_MS, MILLISECONDS,
430 +                                   new ArrayBlockingQueue<Runnable>(10));
431 +        assertFalse(p.isTerminated());
432 +        assertFalse(p.awaitTermination(Long.MIN_VALUE, NANOSECONDS));
433 +        assertFalse(p.awaitTermination(Long.MIN_VALUE, MILLISECONDS));
434 +        assertFalse(p.awaitTermination(-1L, NANOSECONDS));
435 +        assertFalse(p.awaitTermination(-1L, MILLISECONDS));
436 +        assertFalse(p.awaitTermination(0L, NANOSECONDS));
437 +        assertFalse(p.awaitTermination(0L, MILLISECONDS));
438 +        long timeoutNanos = 999999L;
439 +        long startTime = System.nanoTime();
440 +        assertFalse(p.awaitTermination(timeoutNanos, NANOSECONDS));
441 +        assertTrue(System.nanoTime() - startTime >= timeoutNanos);
442 +        assertFalse(p.isTerminated());
443 +        startTime = System.nanoTime();
444 +        long timeoutMillis = timeoutMillis();
445 +        assertFalse(p.awaitTermination(timeoutMillis, MILLISECONDS));
446 +        assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
447 +        assertFalse(p.isTerminated());
448 +        p.shutdown();
449 +        assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
450 +        assertTrue(p.isTerminated());
451 +    }
452  
453      /**
454       * isTerminated is false before termination, true after
# Line 406 | Line 464 | public class ThreadPoolExecutorTest exte
464          try {
465              p.execute(new CheckedRunnable() {
466                  public void realRun() throws InterruptedException {
409                    threadStarted.countDown();
467                      assertFalse(p.isTerminated());
468 +                    threadStarted.countDown();
469                      done.await();
470                  }});
471              assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
472 +            assertFalse(p.isTerminating());
473              done.countDown();
474          } finally {
475              try { p.shutdown(); } catch (SecurityException ok) { return; }
# Line 563 | Line 622 | public class ThreadPoolExecutorTest exte
622      }
623  
624      /**
625 <     * shutDownNow returns a list containing tasks that were not run
625 >     * shutdownNow returns a list containing tasks that were not run
626       */
627 <    public void testShutDownNow() {
627 >    public void testShutdownNow() {
628          final ThreadPoolExecutor p =
629              new ThreadPoolExecutor(1, 1,
630                                     LONG_DELAY_MS, MILLISECONDS,
# Line 586 | Line 645 | public class ThreadPoolExecutorTest exte
645  
646      // Exception Tests
647  
589
648      /**
649       * Constructor throws if corePoolSize argument is less than zero
650       */
# Line 659 | Line 717 | public class ThreadPoolExecutorTest exte
717          } catch (NullPointerException success) {}
718      }
719  
662
663
720      /**
721       * Constructor throws if corePoolSize argument is less than zero
722       */
# Line 752 | Line 808 | public class ThreadPoolExecutorTest exte
808          } catch (NullPointerException success) {}
809      }
810  
755
811      /**
812       * Constructor throws if corePoolSize argument is less than zero
813       */
# Line 844 | Line 899 | public class ThreadPoolExecutorTest exte
899          } catch (NullPointerException success) {}
900      }
901  
847
902      /**
903       * Constructor throws if corePoolSize argument is less than zero
904       */
# Line 1211 | Line 1265 | public class ThreadPoolExecutorTest exte
1265          }
1266      }
1267  
1214
1268      /**
1269       * execute using DiscardOldestPolicy drops task on shutdown
1270       */
# Line 1233 | Line 1286 | public class ThreadPoolExecutorTest exte
1286          }
1287      }
1288  
1236
1289      /**
1290       * execute(null) throws NPE
1291       */
# Line 1306 | Line 1358 | public class ThreadPoolExecutorTest exte
1358          joinPool(p);
1359      }
1360  
1309
1361      /**
1362       * setKeepAliveTime throws IllegalArgumentException
1363       * when given a negative value
# Line 1332 | Line 1383 | public class ThreadPoolExecutorTest exte
1383      public void testTerminated() {
1384          ExtendedTPE p = new ExtendedTPE();
1385          try { p.shutdown(); } catch (SecurityException ok) { return; }
1386 <        assertTrue(p.terminatedCalled);
1386 >        assertTrue(p.terminatedCalled());
1387          joinPool(p);
1388      }
1389  
# Line 1342 | Line 1393 | public class ThreadPoolExecutorTest exte
1393      public void testBeforeAfter() throws InterruptedException {
1394          ExtendedTPE p = new ExtendedTPE();
1395          try {
1396 <            TrackedNoOpRunnable r = new TrackedNoOpRunnable();
1397 <            p.execute(r);
1398 <            Thread.sleep(SHORT_DELAY_MS);
1399 <            assertTrue(r.done);
1400 <            assertTrue(p.beforeCalled);
1401 <            assertTrue(p.afterCalled);
1396 >            final CountDownLatch done = new CountDownLatch(1);
1397 >            p.execute(new CheckedRunnable() {
1398 >                public void realRun() {
1399 >                    done.countDown();
1400 >                }});
1401 >            await(p.afterCalled);
1402 >            assertEquals(0, done.getCount());
1403 >            assertTrue(p.afterCalled());
1404 >            assertTrue(p.beforeCalled());
1405              try { p.shutdown(); } catch (SecurityException ok) { return; }
1406          } finally {
1407              joinPool(p);
# Line 1405 | Line 1459 | public class ThreadPoolExecutorTest exte
1459          }
1460      }
1461  
1408
1462      /**
1463       * invokeAny(null) throws NPE
1464       */
# Line 1599 | Line 1652 | public class ThreadPoolExecutorTest exte
1652          }
1653      }
1654  
1602
1603
1655      /**
1656       * timed invokeAny(null) throws NPE
1657       */
# Line 1847 | Line 1898 | public class ThreadPoolExecutorTest exte
1898              l.add(new StringTask());
1899              List<Future<String>> futures =
1900                  e.invokeAll(l, SHORT_DELAY_MS, MILLISECONDS);
1901 <            assertEquals(3, futures.size());
1902 <            Iterator<Future<String>> it = futures.iterator();
1903 <            Future<String> f1 = it.next();
1904 <            Future<String> f2 = it.next();
1905 <            Future<String> f3 = it.next();
1855 <            assertTrue(f1.isDone());
1856 <            assertTrue(f2.isDone());
1857 <            assertTrue(f3.isDone());
1858 <            assertFalse(f1.isCancelled());
1859 <            assertTrue(f2.isCancelled());
1901 >            assertEquals(l.size(), futures.size());
1902 >            for (Future future : futures)
1903 >                assertTrue(future.isDone());
1904 >            assertFalse(futures.get(0).isCancelled());
1905 >            assertTrue(futures.get(1).isCancelled());
1906          } finally {
1907              joinPool(e);
1908          }
# Line 1902 | Line 1948 | public class ThreadPoolExecutorTest exte
1948       * allowCoreThreadTimeOut(true) causes idle threads to time out
1949       */
1950      public void testAllowCoreThreadTimeOut_true() throws Exception {
1951 +        long coreThreadTimeOut = SHORT_DELAY_MS;
1952          final ThreadPoolExecutor p =
1953              new ThreadPoolExecutor(2, 10,
1954 <                                   SHORT_DELAY_MS, MILLISECONDS,
1954 >                                   coreThreadTimeOut, MILLISECONDS,
1955                                     new ArrayBlockingQueue<Runnable>(10));
1956          final CountDownLatch threadStarted = new CountDownLatch(1);
1957          try {
1958              p.allowCoreThreadTimeOut(true);
1959              p.execute(new CheckedRunnable() {
1960 <                public void realRun() throws InterruptedException {
1960 >                public void realRun() {
1961                      threadStarted.countDown();
1962                      assertEquals(1, p.getPoolSize());
1963                  }});
1964 <            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
1965 <            for (int i = 0; i < (MEDIUM_DELAY_MS/10); i++) {
1966 <                if (p.getPoolSize() == 0)
1967 <                    break;
1968 <                Thread.sleep(10);
1969 <            }
1964 >            await(threadStarted);
1965 >            delay(coreThreadTimeOut);
1966 >            long startTime = System.nanoTime();
1967 >            while (p.getPoolSize() > 0
1968 >                   && millisElapsedSince(startTime) < LONG_DELAY_MS)
1969 >                Thread.yield();
1970 >            assertTrue(millisElapsedSince(startTime) < LONG_DELAY_MS);
1971              assertEquals(0, p.getPoolSize());
1972          } finally {
1973              joinPool(p);
# Line 1930 | Line 1978 | public class ThreadPoolExecutorTest exte
1978       * allowCoreThreadTimeOut(false) causes idle threads not to time out
1979       */
1980      public void testAllowCoreThreadTimeOut_false() throws Exception {
1981 +        long coreThreadTimeOut = SHORT_DELAY_MS;
1982          final ThreadPoolExecutor p =
1983              new ThreadPoolExecutor(2, 10,
1984 <                                   SHORT_DELAY_MS, MILLISECONDS,
1984 >                                   coreThreadTimeOut, MILLISECONDS,
1985                                     new ArrayBlockingQueue<Runnable>(10));
1986          final CountDownLatch threadStarted = new CountDownLatch(1);
1987          try {
# Line 1942 | Line 1991 | public class ThreadPoolExecutorTest exte
1991                      threadStarted.countDown();
1992                      assertTrue(p.getPoolSize() >= 1);
1993                  }});
1994 <            Thread.sleep(SMALL_DELAY_MS);
1994 >            delay(2 * coreThreadTimeOut);
1995              assertTrue(p.getPoolSize() >= 1);
1996          } finally {
1997              joinPool(p);
# Line 1976 | Line 2025 | public class ThreadPoolExecutorTest exte
2025              // enough time to run all tasks
2026              assertTrue(done.await(nTasks * SHORT_DELAY_MS, MILLISECONDS));
2027          } finally {
2028 <            p.shutdown();
2028 >            joinPool(p);
2029          }
2030      }
2031  

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines