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

Comparing jsr166/src/test/tck/ScheduledExecutorTest.java (file contents):
Revision 1.44 by jsr166, Sat May 28 15:33:20 2011 UTC vs.
Revision 1.57 by jsr166, Mon Sep 28 03:05:23 2015 UTC

# Line 6 | Line 6
6   * Pat Fisher, Mike Judd.
7   */
8  
9 import junit.framework.*;
10 import java.util.*;
11 import java.util.concurrent.*;
9   import static java.util.concurrent.TimeUnit.MILLISECONDS;
10 < import java.util.concurrent.atomic.*;
10 > import static java.util.concurrent.TimeUnit.SECONDS;
11 >
12 > import java.util.ArrayList;
13 > import java.util.HashSet;
14 > import java.util.List;
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;
21 > import java.util.concurrent.ExecutorService;
22 > import java.util.concurrent.Future;
23 > import java.util.concurrent.RejectedExecutionException;
24 > import java.util.concurrent.ScheduledFuture;
25 > import java.util.concurrent.ScheduledThreadPoolExecutor;
26 > import java.util.concurrent.ThreadFactory;
27 > import java.util.concurrent.ThreadPoolExecutor;
28 > import java.util.concurrent.atomic.AtomicInteger;
29 >
30 > import junit.framework.Test;
31 > import junit.framework.TestSuite;
32  
33   public class ScheduledExecutorTest extends JSR166TestCase {
34      public static void main(String[] args) {
35 <        junit.textui.TestRunner.run(suite());
35 >        main(suite(), args);
36      }
37      public static Test suite() {
38          return new TestSuite(ScheduledExecutorTest.class);
# Line 141 | Line 159 | public class ScheduledExecutorTest exten
159       */
160      public void testFixedRateSequence() throws InterruptedException {
161          ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
162 <        RunnableCounter counter = new RunnableCounter();
163 <        ScheduledFuture h =
164 <            p.scheduleAtFixedRate(counter, 0, 1, MILLISECONDS);
165 <        delay(SMALL_DELAY_MS);
166 <        h.cancel(true);
167 <        int c = counter.count.get();
168 <        // By time scaling conventions, we must have at least
169 <        // an execution per SHORT delay, but no more than one SHORT more
170 <        assertTrue(c >= SMALL_DELAY_MS / SHORT_DELAY_MS);
171 <        assertTrue(c <= SMALL_DELAY_MS + SHORT_DELAY_MS);
172 <        joinPool(p);
162 >        try {
163 >            for (int delay = 1; delay <= LONG_DELAY_MS; delay *= 3) {
164 >                long startTime = System.nanoTime();
165 >                int cycles = 10;
166 >                final CountDownLatch done = new CountDownLatch(cycles);
167 >                Runnable task = new CheckedRunnable() {
168 >                    public void realRun() { done.countDown(); }};
169 >                ScheduledFuture h =
170 >                    p.scheduleAtFixedRate(task, 0, delay, MILLISECONDS);
171 >                done.await();
172 >                h.cancel(true);
173 >                double normalizedTime =
174 >                    (double) millisElapsedSince(startTime) / delay;
175 >                if (normalizedTime >= cycles - 1 &&
176 >                    normalizedTime <= cycles)
177 >                    return;
178 >            }
179 >            throw new AssertionError("unexpected execution rate");
180 >        } finally {
181 >            joinPool(p);
182 >        }
183      }
184  
185      /**
# Line 159 | Line 187 | public class ScheduledExecutorTest exten
187       */
188      public void testFixedDelaySequence() throws InterruptedException {
189          ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
190 <        RunnableCounter counter = new RunnableCounter();
191 <        ScheduledFuture h =
192 <            p.scheduleWithFixedDelay(counter, 0, 1, MILLISECONDS);
193 <        delay(SMALL_DELAY_MS);
194 <        h.cancel(true);
195 <        int c = counter.count.get();
196 <        assertTrue(c >= SMALL_DELAY_MS / SHORT_DELAY_MS);
197 <        assertTrue(c <= SMALL_DELAY_MS + SHORT_DELAY_MS);
198 <        joinPool(p);
190 >        try {
191 >            for (int delay = 1; delay <= LONG_DELAY_MS; delay *= 3) {
192 >                long startTime = System.nanoTime();
193 >                int cycles = 10;
194 >                final CountDownLatch done = new CountDownLatch(cycles);
195 >                Runnable task = new CheckedRunnable() {
196 >                    public void realRun() { done.countDown(); }};
197 >                ScheduledFuture h =
198 >                    p.scheduleWithFixedDelay(task, 0, delay, MILLISECONDS);
199 >                done.await();
200 >                h.cancel(true);
201 >                double normalizedTime =
202 >                    (double) millisElapsedSince(startTime) / delay;
203 >                if (normalizedTime >= cycles - 1 &&
204 >                    normalizedTime <= cycles)
205 >                    return;
206 >            }
207 >            throw new AssertionError("unexpected execution rate");
208 >        } finally {
209 >            joinPool(p);
210 >        }
211      }
212  
213      /**
# Line 320 | Line 360 | public class ScheduledExecutorTest exten
360                      threadProceed.await();
361                      threadDone.countDown();
362                  }});
363 <            assertTrue(threadStarted.await(SMALL_DELAY_MS, MILLISECONDS));
363 >            await(threadStarted);
364              assertEquals(0, p.getCompletedTaskCount());
365              threadProceed.countDown();
366              threadDone.await();
# Line 613 | Line 653 | public class ScheduledExecutorTest exten
653      }
654  
655      /**
656 <     * shutdownNow returns a list containing tasks that were not run
656 >     * shutdownNow returns a list containing tasks that were not run,
657 >     * and those tasks are drained from the queue
658 >     */
659 >    public void testShutdownNow() throws InterruptedException {
660 >        final int poolSize = 2;
661 >        final int count = 5;
662 >        final AtomicInteger ran = new AtomicInteger(0);
663 >        final ScheduledThreadPoolExecutor p =
664 >            new ScheduledThreadPoolExecutor(poolSize);
665 >        CountDownLatch threadsStarted = new CountDownLatch(poolSize);
666 >        CheckedRunnable waiter = new CheckedRunnable() { public void realRun() {
667 >            threadsStarted.countDown();
668 >            try {
669 >                MILLISECONDS.sleep(2 * LONG_DELAY_MS);
670 >            } catch (InterruptedException success) {}
671 >            ran.getAndIncrement();
672 >        }};
673 >        for (int i = 0; i < count; i++)
674 >            p.execute(waiter);
675 >        assertTrue(threadsStarted.await(LONG_DELAY_MS, MILLISECONDS));
676 >        assertEquals(poolSize, p.getActiveCount());
677 >        assertEquals(0, p.getCompletedTaskCount());
678 >        final List<Runnable> queuedTasks;
679 >        try {
680 >            queuedTasks = p.shutdownNow();
681 >        } catch (SecurityException ok) {
682 >            return; // Allowed in case test doesn't have privs
683 >        }
684 >        assertTrue(p.isShutdown());
685 >        assertTrue(p.getQueue().isEmpty());
686 >        assertEquals(count - poolSize, queuedTasks.size());
687 >        assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
688 >        assertTrue(p.isTerminated());
689 >        assertEquals(poolSize, ran.get());
690 >        assertEquals(poolSize, p.getCompletedTaskCount());
691 >    }
692 >
693 >    /**
694 >     * shutdownNow returns a list containing tasks that were not run,
695 >     * and those tasks are drained from the queue
696       */
697 <    public void testShutdownNow() {
697 >    public void testShutdownNow_delayedTasks() throws InterruptedException {
698          ScheduledThreadPoolExecutor p = new ScheduledThreadPoolExecutor(1);
699 <        for (int i = 0; i < 5; i++)
700 <            p.schedule(new SmallPossiblyInterruptedRunnable(),
701 <                       LONG_DELAY_MS, MILLISECONDS);
699 >        List<ScheduledFuture> tasks = new ArrayList<>();
700 >        for (int i = 0; i < 3; i++) {
701 >            Runnable r = new NoOpRunnable();
702 >            tasks.add(p.schedule(r, 9, SECONDS));
703 >            tasks.add(p.scheduleAtFixedRate(r, 9, 9, SECONDS));
704 >            tasks.add(p.scheduleWithFixedDelay(r, 9, 9, SECONDS));
705 >        }
706 >        if (testImplementationDetails)
707 >            assertEquals(new HashSet(tasks), new HashSet(p.getQueue()));
708 >        final List<Runnable> queuedTasks;
709          try {
710 <            List<Runnable> l = p.shutdownNow();
625 <            assertTrue(p.isShutdown());
626 <            assertEquals(5, l.size());
710 >            queuedTasks = p.shutdownNow();
711          } catch (SecurityException ok) {
712 <            // Allowed in case test doesn't have privs
713 <        } finally {
714 <            joinPool(p);
712 >            return; // Allowed in case test doesn't have privs
713 >        }
714 >        assertTrue(p.isShutdown());
715 >        assertTrue(p.getQueue().isEmpty());
716 >        if (testImplementationDetails)
717 >            assertEquals(new HashSet(tasks), new HashSet(queuedTasks));
718 >        assertEquals(tasks.size(), queuedTasks.size());
719 >        for (ScheduledFuture task : tasks) {
720 >            assertFalse(task.isDone());
721 >            assertFalse(task.isCancelled());
722          }
723 +        assertTrue(p.awaitTermination(LONG_DELAY_MS, MILLISECONDS));
724 +        assertTrue(p.isTerminated());
725      }
726  
727      /**
# Line 1149 | Line 1242 | public class ScheduledExecutorTest exten
1242      public void testTimedInvokeAll6() throws Exception {
1243          ExecutorService e = new ScheduledThreadPoolExecutor(2);
1244          try {
1245 <            List<Callable<String>> l = new ArrayList<Callable<String>>();
1246 <            l.add(new StringTask());
1247 <            l.add(Executors.callable(new MediumPossiblyInterruptedRunnable(), TEST_STRING));
1248 <            l.add(new StringTask());
1249 <            List<Future<String>> futures =
1250 <                e.invokeAll(l, SHORT_DELAY_MS, MILLISECONDS);
1251 <            assertEquals(3, futures.size());
1252 <            Iterator<Future<String>> it = futures.iterator();
1253 <            Future<String> f1 = it.next();
1254 <            Future<String> f2 = it.next();
1255 <            Future<String> f3 = it.next();
1256 <            assertTrue(f1.isDone());
1257 <            assertTrue(f2.isDone());
1258 <            assertTrue(f3.isDone());
1259 <            assertFalse(f1.isCancelled());
1260 <            assertTrue(f2.isCancelled());
1245 >            for (long timeout = timeoutMillis();;) {
1246 >                List<Callable<String>> tasks = new ArrayList<>();
1247 >                tasks.add(new StringTask("0"));
1248 >                tasks.add(Executors.callable(new LongPossiblyInterruptedRunnable(), TEST_STRING));
1249 >                tasks.add(new StringTask("2"));
1250 >                long startTime = System.nanoTime();
1251 >                List<Future<String>> futures =
1252 >                    e.invokeAll(tasks, timeout, MILLISECONDS);
1253 >                assertEquals(tasks.size(), futures.size());
1254 >                assertTrue(millisElapsedSince(startTime) >= timeout);
1255 >                for (Future future : futures)
1256 >                    assertTrue(future.isDone());
1257 >                assertTrue(futures.get(1).isCancelled());
1258 >                try {
1259 >                    assertEquals("0", futures.get(0).get());
1260 >                    assertEquals("2", futures.get(2).get());
1261 >                    break;
1262 >                } catch (CancellationException retryWithLongerTimeout) {
1263 >                    timeout *= 2;
1264 >                    if (timeout >= LONG_DELAY_MS / 2)
1265 >                        fail("expected exactly one task to be cancelled");
1266 >                }
1267 >            }
1268          } finally {
1269              joinPool(e);
1270          }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines