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.36 by jsr166, Fri May 15 17:07:27 2015 UTC vs.
Revision 1.49 by jsr166, Sun Oct 4 00:30:50 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 223 | Line 230 | public class ThreadPoolExecutorSubclassT
230       * execute successfully executes a runnable
231       */
232      public void testExecute() throws InterruptedException {
233 <        final ThreadPoolExecutor p =
234 <            new CustomTPE(1, 1,
235 <                          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();
241 <            }};
235 <        try {
233 >        try (PoolCleaner<CustomTPE> cleaner =
234 >             cleaner(new CustomTPE(1, 1,
235 >                                   2 * LONG_DELAY_MS, MILLISECONDS,
236 >                                   new ArrayBlockingQueue<Runnable>(10)))) {
237 >            final ThreadPoolExecutor p = cleaner.pool;
238 >            final CountDownLatch done = new CountDownLatch(1);
239 >            final Runnable task = new CheckedRunnable() {
240 >                public void realRun() { done.countDown();
241 >                }};
242              p.execute(task);
243 <            assertTrue(done.await(SMALL_DELAY_MS, MILLISECONDS));
238 <        } finally {
239 <            joinPool(p);
243 >            assertTrue(done.await(LONG_DELAY_MS, MILLISECONDS));
244          }
245      }
246  
# Line 345 | Line 349 | public class ThreadPoolExecutorSubclassT
349       */
350      public void testGetKeepAliveTime() {
351          ThreadPoolExecutor p = new CustomTPE(2, 2, 1000, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
352 <        assertEquals(1, p.getKeepAliveTime(TimeUnit.SECONDS));
352 >        assertEquals(1, p.getKeepAliveTime(SECONDS));
353          joinPool(p);
354      }
355  
# Line 698 | Line 702 | public class ThreadPoolExecutorSubclassT
702      }
703  
704      /**
705 <     * shutdownNow returns a list containing tasks that were not run
705 >     * shutdownNow returns a list containing tasks that were not run,
706 >     * and those tasks are drained from the queue
707       */
708 <    public void testShutdownNow() {
709 <        ThreadPoolExecutor p = new CustomTPE(1, 1, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
710 <        List l;
711 <        try {
712 <            for (int i = 0; i < 5; i++)
713 <                p.execute(new MediumPossiblyInterruptedRunnable());
714 <        }
715 <        finally {
708 >    public void testShutdownNow() throws InterruptedException {
709 >        final int poolSize = 2;
710 >        final int count = 5;
711 >        final AtomicInteger ran = new AtomicInteger(0);
712 >        ThreadPoolExecutor p =
713 >            new CustomTPE(poolSize, poolSize, LONG_DELAY_MS, MILLISECONDS,
714 >                          new ArrayBlockingQueue<Runnable>(10));
715 >        CountDownLatch threadsStarted = new CountDownLatch(poolSize);
716 >        Runnable waiter = new CheckedRunnable() { public void realRun() {
717 >            threadsStarted.countDown();
718              try {
719 <                l = p.shutdownNow();
720 <            } catch (SecurityException ok) { return; }
719 >                MILLISECONDS.sleep(2 * LONG_DELAY_MS);
720 >            } catch (InterruptedException success) {}
721 >            ran.getAndIncrement();
722 >        }};
723 >        for (int i = 0; i < count; i++)
724 >            p.execute(waiter);
725 >        assertTrue(threadsStarted.await(LONG_DELAY_MS, MILLISECONDS));
726 >        assertEquals(poolSize, p.getActiveCount());
727 >        assertEquals(0, p.getCompletedTaskCount());
728 >        final List<Runnable> queuedTasks;
729 >        try {
730 >            queuedTasks = p.shutdownNow();
731 >        } catch (SecurityException ok) {
732 >            return; // Allowed in case test doesn't have privs
733          }
734          assertTrue(p.isShutdown());
735 <        assertTrue(l.size() <= 4);
735 >        assertTrue(p.getQueue().isEmpty());
736 >        assertEquals(count - poolSize, queuedTasks.size());
737 >        assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
738 >        assertTrue(p.isTerminated());
739 >        assertEquals(poolSize, ran.get());
740 >        assertEquals(poolSize, p.getCompletedTaskCount());
741      }
742  
743      // Exception Tests
# Line 1223 | Line 1247 | public class ThreadPoolExecutorSubclassT
1247       * execute(null) throws NPE
1248       */
1249      public void testExecuteNull() {
1250 <        ThreadPoolExecutor p = null;
1250 >        ThreadPoolExecutor p =
1251 >            new CustomTPE(1, 2, 1L, SECONDS,
1252 >                          new ArrayBlockingQueue<Runnable>(10));
1253          try {
1228            p = new CustomTPE(1,2,LONG_DELAY_MS, MILLISECONDS,new ArrayBlockingQueue<Runnable>(10));
1254              p.execute(null);
1255              shouldThrow();
1256          } catch (NullPointerException success) {}
# Line 1721 | Line 1746 | public class ThreadPoolExecutorSubclassT
1746              l.add(new StringTask());
1747              l.add(new StringTask());
1748              List<Future<String>> futures =
1749 <                e.invokeAll(l, MEDIUM_DELAY_MS, MILLISECONDS);
1749 >                e.invokeAll(l, LONG_DELAY_MS, MILLISECONDS);
1750              assertEquals(2, futures.size());
1751              for (Future<String> future : futures)
1752                  assertSame(TEST_STRING, future.get());
# Line 1736 | Line 1761 | public class ThreadPoolExecutorSubclassT
1761      public void testTimedInvokeAll6() throws Exception {
1762          ExecutorService e = new CustomTPE(2, 2, LONG_DELAY_MS, MILLISECONDS, new ArrayBlockingQueue<Runnable>(10));
1763          try {
1764 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1765 <            l.add(new StringTask());
1766 <            l.add(Executors.callable(new MediumPossiblyInterruptedRunnable(), TEST_STRING));
1767 <            l.add(new StringTask());
1768 <            List<Future<String>> futures =
1769 <                e.invokeAll(l, SHORT_DELAY_MS, MILLISECONDS);
1770 <            assertEquals(l.size(), futures.size());
1771 <            for (Future future : futures)
1772 <                assertTrue(future.isDone());
1773 <            assertFalse(futures.get(0).isCancelled());
1774 <            assertTrue(futures.get(1).isCancelled());
1764 >            for (long timeout = timeoutMillis();;) {
1765 >                List<Callable<String>> tasks = new ArrayList<>();
1766 >                tasks.add(new StringTask("0"));
1767 >                tasks.add(Executors.callable(new LongPossiblyInterruptedRunnable(), TEST_STRING));
1768 >                tasks.add(new StringTask("2"));
1769 >                long startTime = System.nanoTime();
1770 >                List<Future<String>> futures =
1771 >                    e.invokeAll(tasks, timeout, MILLISECONDS);
1772 >                assertEquals(tasks.size(), futures.size());
1773 >                assertTrue(millisElapsedSince(startTime) >= timeout);
1774 >                for (Future future : futures)
1775 >                    assertTrue(future.isDone());
1776 >                assertTrue(futures.get(1).isCancelled());
1777 >                try {
1778 >                    assertEquals("0", futures.get(0).get());
1779 >                    assertEquals("2", futures.get(2).get());
1780 >                    break;
1781 >                } catch (CancellationException retryWithLongerTimeout) {
1782 >                    timeout *= 2;
1783 >                    if (timeout >= LONG_DELAY_MS / 2)
1784 >                        fail("expected exactly one task to be cancelled");
1785 >                }
1786 >            }
1787          } finally {
1788              joinPool(e);
1789          }
# Line 1789 | Line 1826 | public class ThreadPoolExecutorSubclassT
1826       * allowCoreThreadTimeOut(true) causes idle threads to time out
1827       */
1828      public void testAllowCoreThreadTimeOut_true() throws Exception {
1829 <        long coreThreadTimeOut = SHORT_DELAY_MS;
1829 >        long keepAliveTime = timeoutMillis();
1830          final ThreadPoolExecutor p =
1831              new CustomTPE(2, 10,
1832 <                          coreThreadTimeOut, MILLISECONDS,
1832 >                          keepAliveTime, MILLISECONDS,
1833                            new ArrayBlockingQueue<Runnable>(10));
1834          final CountDownLatch threadStarted = new CountDownLatch(1);
1835          try {
1836              p.allowCoreThreadTimeOut(true);
1837              p.execute(new CheckedRunnable() {
1838 <                public void realRun() throws InterruptedException {
1838 >                public void realRun() {
1839                      threadStarted.countDown();
1840                      assertEquals(1, p.getPoolSize());
1841                  }});
1842              await(threadStarted);
1843 <            delay(coreThreadTimeOut);
1843 >            delay(keepAliveTime);
1844              long startTime = System.nanoTime();
1845              while (p.getPoolSize() > 0
1846                     && millisElapsedSince(startTime) < LONG_DELAY_MS)
# Line 1819 | Line 1856 | public class ThreadPoolExecutorSubclassT
1856       * allowCoreThreadTimeOut(false) causes idle threads not to time out
1857       */
1858      public void testAllowCoreThreadTimeOut_false() throws Exception {
1859 <        long coreThreadTimeOut = SHORT_DELAY_MS;
1859 >        long keepAliveTime = timeoutMillis();
1860          final ThreadPoolExecutor p =
1861              new CustomTPE(2, 10,
1862 <                          coreThreadTimeOut, MILLISECONDS,
1862 >                          keepAliveTime, MILLISECONDS,
1863                            new ArrayBlockingQueue<Runnable>(10));
1864          final CountDownLatch threadStarted = new CountDownLatch(1);
1865          try {
# Line 1832 | Line 1869 | public class ThreadPoolExecutorSubclassT
1869                      threadStarted.countDown();
1870                      assertTrue(p.getPoolSize() >= 1);
1871                  }});
1872 <            delay(2 * coreThreadTimeOut);
1872 >            delay(2 * keepAliveTime);
1873              assertTrue(p.getPoolSize() >= 1);
1874          } finally {
1875              joinPool(p);
1876          }
1877      }
1878  
1879 +    /**
1880 +     * get(cancelled task) throws CancellationException
1881 +     * (in part, a test of CustomTPE itself)
1882 +     */
1883 +    public void testGet_cancelled() throws Exception {
1884 +        final ExecutorService e =
1885 +            new CustomTPE(1, 1,
1886 +                          LONG_DELAY_MS, MILLISECONDS,
1887 +                          new LinkedBlockingQueue<Runnable>());
1888 +        try {
1889 +            final CountDownLatch blockerStarted = new CountDownLatch(1);
1890 +            final CountDownLatch done = new CountDownLatch(1);
1891 +            final List<Future<?>> futures = new ArrayList<>();
1892 +            for (int i = 0; i < 2; i++) {
1893 +                Runnable r = new CheckedRunnable() { public void realRun()
1894 +                                                         throws Throwable {
1895 +                    blockerStarted.countDown();
1896 +                    assertTrue(done.await(2 * LONG_DELAY_MS, MILLISECONDS));
1897 +                }};
1898 +                futures.add(e.submit(r));
1899 +            }
1900 +            assertTrue(blockerStarted.await(LONG_DELAY_MS, MILLISECONDS));
1901 +            for (Future<?> future : futures) future.cancel(false);
1902 +            for (Future<?> future : futures) {
1903 +                try {
1904 +                    future.get();
1905 +                    shouldThrow();
1906 +                } catch (CancellationException success) {}
1907 +                try {
1908 +                    future.get(LONG_DELAY_MS, MILLISECONDS);
1909 +                    shouldThrow();
1910 +                } catch (CancellationException success) {}
1911 +                assertTrue(future.isCancelled());
1912 +                assertTrue(future.isDone());
1913 +            }
1914 +            done.countDown();
1915 +        } finally {
1916 +            joinPool(e);
1917 +        }
1918 +    }
1919 +
1920   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines