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

Comparing jsr166/src/test/tck/ThreadPoolExecutorSubclassTest.java (file contents):
Revision 1.37 by jsr166, Fri May 15 18:21:19 2015 UTC vs.
Revision 1.53 by jsr166, Sun Oct 4 01:23:41 2015 UTC

# Line 14 | Line 14 | 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.CancellationException;
18   import java.util.concurrent.CountDownLatch;
19   import java.util.concurrent.ExecutionException;
20   import java.util.concurrent.Executors;
# Line 29 | Line 30 | import java.util.concurrent.ThreadFactor
30   import java.util.concurrent.ThreadPoolExecutor;
31   import java.util.concurrent.TimeoutException;
32   import java.util.concurrent.TimeUnit;
33 + import java.util.concurrent.atomic.AtomicInteger;
34   import java.util.concurrent.locks.Condition;
35   import java.util.concurrent.locks.ReentrantLock;
36  
# Line 99 | Line 101 | public class ThreadPoolExecutorSubclassT
101              }
102              lock.lock();
103              try {
104 <                result = v;
105 <                exception = e;
106 <                done = true;
107 <                thread = null;
108 <                cond.signalAll();
104 >                if (!done) {
105 >                    result = v;
106 >                    exception = e;
107 >                    done = true;
108 >                    thread = null;
109 >                    cond.signalAll();
110 >                }
111              }
112              finally { lock.unlock(); }
113          }
# Line 112 | Line 116 | public class ThreadPoolExecutorSubclassT
116              try {
117                  while (!done)
118                      cond.await();
119 +                if (cancelled)
120 +                    throw new CancellationException();
121                  if (exception != null)
122                      throw new ExecutionException(exception);
123                  return result;
# Line 123 | Line 129 | public class ThreadPoolExecutorSubclassT
129              long nanos = unit.toNanos(timeout);
130              lock.lock();
131              try {
132 <                for (;;) {
133 <                    if (done) break;
128 <                    if (nanos < 0)
132 >                while (!done) {
133 >                    if (nanos <= 0L)
134                          throw new TimeoutException();
135                      nanos = cond.awaitNanos(nanos);
136                  }
137 +                if (cancelled)
138 +                    throw new CancellationException();
139                  if (exception != null)
140                      throw new ExecutionException(exception);
141                  return result;
# Line 225 | Line 232 | public class ThreadPoolExecutorSubclassT
232      public void testExecute() throws InterruptedException {
233          final ThreadPoolExecutor p =
234              new CustomTPE(1, 1,
235 <                          LONG_DELAY_MS, MILLISECONDS,
235 >                          2 * LONG_DELAY_MS, MILLISECONDS,
236                            new ArrayBlockingQueue<Runnable>(10));
237 <        final CountDownLatch done = new CountDownLatch(1);
238 <        final Runnable task = new CheckedRunnable() {
239 <            public void realRun() {
240 <                done.countDown();
234 <            }};
235 <        try {
237 >        try (PoolCleaner cleaner = cleaner(p)) {
238 >            final CountDownLatch done = new CountDownLatch(1);
239 >            final Runnable task = new CheckedRunnable() {
240 >                public void realRun() { done.countDown(); }};
241              p.execute(task);
242 <            assertTrue(done.await(SMALL_DELAY_MS, MILLISECONDS));
238 <        } finally {
239 <            joinPool(p);
242 >            assertTrue(done.await(LONG_DELAY_MS, MILLISECONDS));
243          }
244      }
245  
# Line 251 | Line 254 | public class ThreadPoolExecutorSubclassT
254                            new ArrayBlockingQueue<Runnable>(10));
255          final CountDownLatch threadStarted = new CountDownLatch(1);
256          final CountDownLatch done = new CountDownLatch(1);
257 <        try {
257 >        try (PoolCleaner cleaner = cleaner(p)) {
258              assertEquals(0, p.getActiveCount());
259              p.execute(new CheckedRunnable() {
260                  public void realRun() throws InterruptedException {
# Line 261 | Line 264 | public class ThreadPoolExecutorSubclassT
264                  }});
265              assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
266              assertEquals(1, p.getActiveCount());
264        } finally {
267              done.countDown();
266            joinPool(p);
268          }
269      }
270  
# Line 271 | Line 272 | public class ThreadPoolExecutorSubclassT
272       * prestartCoreThread starts a thread if under corePoolSize, else doesn't
273       */
274      public void testPrestartCoreThread() {
275 <        ThreadPoolExecutor p = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
276 <        assertEquals(0, p.getPoolSize());
277 <        assertTrue(p.prestartCoreThread());
278 <        assertEquals(1, p.getPoolSize());
279 <        assertTrue(p.prestartCoreThread());
280 <        assertEquals(2, p.getPoolSize());
281 <        assertFalse(p.prestartCoreThread());
282 <        assertEquals(2, p.getPoolSize());
283 <        joinPool(p);
275 >        ThreadPoolExecutor p =
276 >            new CustomTPE(2, 6,
277 >                          LONG_DELAY_MS, MILLISECONDS,
278 >                          new ArrayBlockingQueue<Runnable>(10));
279 >        try (PoolCleaner cleaner = cleaner(p)) {
280 >            assertEquals(0, p.getPoolSize());
281 >            assertTrue(p.prestartCoreThread());
282 >            assertEquals(1, p.getPoolSize());
283 >            assertTrue(p.prestartCoreThread());
284 >            assertEquals(2, p.getPoolSize());
285 >            assertFalse(p.prestartCoreThread());
286 >            assertEquals(2, p.getPoolSize());
287 >            p.setCorePoolSize(4);
288 >            assertTrue(p.prestartCoreThread());
289 >            assertEquals(3, p.getPoolSize());
290 >            assertTrue(p.prestartCoreThread());
291 >            assertEquals(4, p.getPoolSize());
292 >            assertFalse(p.prestartCoreThread());
293 >            assertEquals(4, p.getPoolSize());
294 >        }
295      }
296  
297      /**
298       * prestartAllCoreThreads starts all corePoolSize threads
299       */
300      public void testPrestartAllCoreThreads() {
301 <        ThreadPoolExecutor p = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
302 <        assertEquals(0, p.getPoolSize());
303 <        p.prestartAllCoreThreads();
304 <        assertEquals(2, p.getPoolSize());
305 <        p.prestartAllCoreThreads();
306 <        assertEquals(2, p.getPoolSize());
307 <        joinPool(p);
301 >        ThreadPoolExecutor p =
302 >            new CustomTPE(2, 6,
303 >                          LONG_DELAY_MS, MILLISECONDS,
304 >                          new ArrayBlockingQueue<Runnable>(10));
305 >        try (PoolCleaner cleaner = cleaner(p)) {
306 >            assertEquals(0, p.getPoolSize());
307 >            p.prestartAllCoreThreads();
308 >            assertEquals(2, p.getPoolSize());
309 >            p.prestartAllCoreThreads();
310 >            assertEquals(2, p.getPoolSize());
311 >            p.setCorePoolSize(4);
312 >            p.prestartAllCoreThreads();
313 >            assertEquals(4, p.getPoolSize());
314 >            p.prestartAllCoreThreads();
315 >            assertEquals(4, p.getPoolSize());
316 >        }
317      }
318  
319      /**
# Line 345 | Line 366 | public class ThreadPoolExecutorSubclassT
366       */
367      public void testGetKeepAliveTime() {
368          ThreadPoolExecutor p = new CustomTPE(2, 2, 1000, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
369 <        assertEquals(1, p.getKeepAliveTime(TimeUnit.SECONDS));
369 >        assertEquals(1, p.getKeepAliveTime(SECONDS));
370          joinPool(p);
371      }
372  
# Line 698 | Line 719 | public class ThreadPoolExecutorSubclassT
719      }
720  
721      /**
722 <     * shutdownNow returns a list containing tasks that were not run
722 >     * shutdownNow returns a list containing tasks that were not run,
723 >     * and those tasks are drained from the queue
724       */
725 <    public void testShutdownNow() {
726 <        ThreadPoolExecutor p = new CustomTPE(1, 1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
727 <        List l;
728 <        try {
729 <            for (int i = 0; i < 5; i++)
730 <                p.execute(new MediumPossiblyInterruptedRunnable());
731 <        }
732 <        finally {
725 >    public void testShutdownNow() throws InterruptedException {
726 >        final int poolSize = 2;
727 >        final int count = 5;
728 >        final AtomicInteger ran = new AtomicInteger(0);
729 >        ThreadPoolExecutor p =
730 >            new CustomTPE(poolSize, poolSize, LONG_DELAY_MS, MILLISECONDS,
731 >                          new ArrayBlockingQueue<Runnable>(10));
732 >        CountDownLatch threadsStarted = new CountDownLatch(poolSize);
733 >        Runnable waiter = new CheckedRunnable() { public void realRun() {
734 >            threadsStarted.countDown();
735              try {
736 <                l = p.shutdownNow();
737 <            } catch (SecurityException ok) { return; }
736 >                MILLISECONDS.sleep(2 * LONG_DELAY_MS);
737 >            } catch (InterruptedException success) {}
738 >            ran.getAndIncrement();
739 >        }};
740 >        for (int i = 0; i < count; i++)
741 >            p.execute(waiter);
742 >        assertTrue(threadsStarted.await(LONG_DELAY_MS, MILLISECONDS));
743 >        assertEquals(poolSize, p.getActiveCount());
744 >        assertEquals(0, p.getCompletedTaskCount());
745 >        final List<Runnable> queuedTasks;
746 >        try {
747 >            queuedTasks = p.shutdownNow();
748 >        } catch (SecurityException ok) {
749 >            return; // Allowed in case test doesn't have privs
750          }
751          assertTrue(p.isShutdown());
752 <        assertTrue(l.size() <= 4);
752 >        assertTrue(p.getQueue().isEmpty());
753 >        assertEquals(count - poolSize, queuedTasks.size());
754 >        assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
755 >        assertTrue(p.isTerminated());
756 >        assertEquals(poolSize, ran.get());
757 >        assertEquals(poolSize, p.getCompletedTaskCount());
758      }
759  
760      // Exception Tests
# Line 1722 | Line 1763 | public class ThreadPoolExecutorSubclassT
1763              l.add(new StringTask());
1764              l.add(new StringTask());
1765              List<Future<String>> futures =
1766 <                e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
1766 >                e.invokeAll(l, LONG_DELAY_MS, MILLISECONDS);
1767              assertEquals(2, futures.size());
1768              for (Future<String> future : futures)
1769                  assertSame(TEST_STRING, future.get());
# Line 1737 | Line 1778 | public class ThreadPoolExecutorSubclassT
1778      public void testTimedInvokeAll6() throws Exception {
1779          ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
1780          try {
1781 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1782 <            l.add(new StringTask());
1783 <            l.add(Executors.callable(new MediumPossiblyInterruptedRunnable(), TEST_STRING));
1784 <            l.add(new StringTask());
1785 <            List<Future<String>> futures =
1786 <                e.invokeAll(l, SHORT_DELAY_MS, MILLISECONDS);
1787 <            assertEquals(l.size(), futures.size());
1788 <            for (Future future : futures)
1789 <                assertTrue(future.isDone());
1790 <            assertFalse(futures.get(0).isCancelled());
1791 <            assertTrue(futures.get(1).isCancelled());
1781 >            for (long timeout = timeoutMillis();;) {
1782 >                List<Callable<String>> tasks = new ArrayList<>();
1783 >                tasks.add(new StringTask("0"));
1784 >                tasks.add(Executors.callable(new LongPossiblyInterruptedRunnable(), TEST_STRING));
1785 >                tasks.add(new StringTask("2"));
1786 >                long startTime = System.nanoTime();
1787 >                List<Future<String>> futures =
1788 >                    e.invokeAll(tasks, timeout, MILLISECONDS);
1789 >                assertEquals(tasks.size(), futures.size());
1790 >                assertTrue(millisElapsedSince(startTime) >= timeout);
1791 >                for (Future future : futures)
1792 >                    assertTrue(future.isDone());
1793 >                assertTrue(futures.get(1).isCancelled());
1794 >                try {
1795 >                    assertEquals("0", futures.get(0).get());
1796 >                    assertEquals("2", futures.get(2).get());
1797 >                    break;
1798 >                } catch (CancellationException retryWithLongerTimeout) {
1799 >                    timeout *= 2;
1800 >                    if (timeout >= LONG_DELAY_MS / 2)
1801 >                        fail("expected exactly one task to be cancelled");
1802 >                }
1803 >            }
1804          } finally {
1805              joinPool(e);
1806          }
# Line 1790 | Line 1843 | public class ThreadPoolExecutorSubclassT
1843       * allowCoreThreadTimeOut(true) causes idle threads to time out
1844       */
1845      public void testAllowCoreThreadTimeOut_true() throws Exception {
1846 <        long coreThreadTimeOut = SHORT_DELAY_MS;
1846 >        long keepAliveTime = timeoutMillis();
1847          final ThreadPoolExecutor p =
1848              new CustomTPE(2, 10,
1849 <                          coreThreadTimeOut, MILLISECONDS,
1849 >                          keepAliveTime, MILLISECONDS,
1850                            new ArrayBlockingQueue<Runnable>(10));
1851          final CountDownLatch threadStarted = new CountDownLatch(1);
1852          try {
1853              p.allowCoreThreadTimeOut(true);
1854              p.execute(new CheckedRunnable() {
1855 <                public void realRun() throws InterruptedException {
1855 >                public void realRun() {
1856                      threadStarted.countDown();
1857                      assertEquals(1, p.getPoolSize());
1858                  }});
1859              await(threadStarted);
1860 <            delay(coreThreadTimeOut);
1860 >            delay(keepAliveTime);
1861              long startTime = System.nanoTime();
1862              while (p.getPoolSize() > 0
1863                     && millisElapsedSince(startTime) < LONG_DELAY_MS)
# Line 1820 | Line 1873 | public class ThreadPoolExecutorSubclassT
1873       * allowCoreThreadTimeOut(false) causes idle threads not to time out
1874       */
1875      public void testAllowCoreThreadTimeOut_false() throws Exception {
1876 <        long coreThreadTimeOut = SHORT_DELAY_MS;
1876 >        long keepAliveTime = timeoutMillis();
1877          final ThreadPoolExecutor p =
1878              new CustomTPE(2, 10,
1879 <                          coreThreadTimeOut, MILLISECONDS,
1879 >                          keepAliveTime, MILLISECONDS,
1880                            new ArrayBlockingQueue<Runnable>(10));
1881          final CountDownLatch threadStarted = new CountDownLatch(1);
1882          try {
# Line 1833 | Line 1886 | public class ThreadPoolExecutorSubclassT
1886                      threadStarted.countDown();
1887                      assertTrue(p.getPoolSize() >= 1);
1888                  }});
1889 <            delay(2 * coreThreadTimeOut);
1889 >            delay(2 * keepAliveTime);
1890              assertTrue(p.getPoolSize() >= 1);
1891          } finally {
1892              joinPool(p);
1893          }
1894      }
1895  
1896 +    /**
1897 +     * get(cancelled task) throws CancellationException
1898 +     * (in part, a test of CustomTPE itself)
1899 +     */
1900 +    public void testGet_cancelled() throws Exception {
1901 +        final ExecutorService e =
1902 +            new CustomTPE(1, 1,
1903 +                          LONG_DELAY_MS, MILLISECONDS,
1904 +                          new LinkedBlockingQueue<Runnable>());
1905 +        try {
1906 +            final CountDownLatch blockerStarted = new CountDownLatch(1);
1907 +            final CountDownLatch done = new CountDownLatch(1);
1908 +            final List<Future<?>> futures = new ArrayList<>();
1909 +            for (int i = 0; i < 2; i++) {
1910 +                Runnable r = new CheckedRunnable() { public void realRun()
1911 +                                                         throws Throwable {
1912 +                    blockerStarted.countDown();
1913 +                    assertTrue(done.await(2 * LONG_DELAY_MS, MILLISECONDS));
1914 +                }};
1915 +                futures.add(e.submit(r));
1916 +            }
1917 +            assertTrue(blockerStarted.await(LONG_DELAY_MS, MILLISECONDS));
1918 +            for (Future<?> future : futures) future.cancel(false);
1919 +            for (Future<?> future : futures) {
1920 +                try {
1921 +                    future.get();
1922 +                    shouldThrow();
1923 +                } catch (CancellationException success) {}
1924 +                try {
1925 +                    future.get(LONG_DELAY_MS, MILLISECONDS);
1926 +                    shouldThrow();
1927 +                } catch (CancellationException success) {}
1928 +                assertTrue(future.isCancelled());
1929 +                assertTrue(future.isDone());
1930 +            }
1931 +            done.countDown();
1932 +        } finally {
1933 +            joinPool(e);
1934 +        }
1935 +    }
1936 +
1937   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines