CancelledFutureLoops.java revision 13172:2103ed2d51f5
1/*
2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
3 *
4 * This code is free software; you can redistribute it and/or modify it
5 * under the terms of the GNU General Public License version 2 only, as
6 * published by the Free Software Foundation.
7 *
8 * This code is distributed in the hope that it will be useful, but WITHOUT
9 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
11 * version 2 for more details (a copy is included in the LICENSE file that
12 * accompanied this code).
13 *
14 * You should have received a copy of the GNU General Public License version
15 * 2 along with this work; if not, write to the Free Software Foundation,
16 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
17 *
18 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
19 * or visit www.oracle.com if you need additional information or have any
20 * questions.
21 */
22
23/*
24 * This file is available under and governed by the GNU General Public
25 * License version 2 only, as published by the Free Software Foundation.
26 * However, the following notice accompanied the original version of this
27 * file:
28 *
29 * Written by Doug Lea with assistance from members of JCP JSR-166
30 * Expert Group and released to the public domain, as explained at
31 * http://creativecommons.org/publicdomain/zero/1.0/
32 */
33
34/*
35 * @test
36 * @bug 4486658
37 * @run main/timeout=2000 CancelledFutureLoops
38 * @summary Checks for responsiveness of futures to cancellation.
39 * Runs under the assumption that ITERS computations require more than
40 * TIMEOUT msecs to complete.
41 */
42
43import static java.util.concurrent.TimeUnit.SECONDS;
44
45import java.util.SplittableRandom;
46import java.util.concurrent.BrokenBarrierException;
47import java.util.concurrent.Callable;
48import java.util.concurrent.CyclicBarrier;
49import java.util.concurrent.ExecutionException;
50import java.util.concurrent.ExecutorService;
51import java.util.concurrent.Executors;
52import java.util.concurrent.Future;
53import java.util.concurrent.locks.ReentrantLock;
54
55public final class CancelledFutureLoops {
56    static final ExecutorService pool = Executors.newCachedThreadPool();
57    static final SplittableRandom rnd = new SplittableRandom();
58    static boolean print = false;
59    static final int ITERS = 1000000;
60    static final long TIMEOUT = 100;
61
62    public static void main(String[] args) throws Exception {
63        int maxThreads = 5;
64        if (args.length > 0)
65            maxThreads = Integer.parseInt(args[0]);
66
67        print = true;
68
69        for (int i = 2; i <= maxThreads; i += (i+1) >>> 1) {
70            System.out.print("Threads: " + i);
71            try {
72                new FutureLoop(i, rnd.split()).test();
73            }
74            catch (BrokenBarrierException bb) {
75                // OK; ignore
76            }
77            catch (ExecutionException ee) {
78                // OK; ignore
79            }
80            Thread.sleep(TIMEOUT);
81        }
82        pool.shutdown();
83        if (! pool.awaitTermination(60L, SECONDS))
84            throw new Error();
85    }
86
87    static final class FutureLoop implements Callable {
88        private final int nthreads;
89        private final SplittableRandom rnd;
90        private final ReentrantLock lock = new ReentrantLock();
91        private final LoopHelpers.BarrierTimer timer = new LoopHelpers.BarrierTimer();
92        private final CyclicBarrier barrier;
93        private int v;
94        FutureLoop(int nthreads, SplittableRandom rnd) {
95            this.nthreads = nthreads;
96            this.rnd = rnd;
97            barrier = new CyclicBarrier(nthreads+1, timer);
98            v = rnd.nextInt();
99        }
100
101        final void test() throws Exception {
102            Future[] futures = new Future[nthreads];
103            for (int i = 0; i < nthreads; ++i)
104                futures[i] = pool.submit(this);
105
106            barrier.await();
107            Thread.sleep(TIMEOUT);
108            boolean tooLate = false;
109            for (int i = 1; i < nthreads; ++i) {
110                if (!futures[i].cancel(true))
111                    tooLate = true;
112                // Unbunch some of the cancels
113                if ( (i & 3) == 0)
114                    Thread.sleep(1 + rnd.nextInt(5));
115            }
116
117            Object f0 = futures[0].get();
118            if (!tooLate) {
119                for (int i = 1; i < nthreads; ++i) {
120                    if (!futures[i].isDone() || !futures[i].isCancelled())
121                        throw new Error("Only one thread should complete");
122                }
123            }
124            else
125                System.out.print("(cancelled too late) ");
126
127            long endTime = System.nanoTime();
128            long time = endTime - timer.startTime;
129            if (print) {
130                double secs = (double)(time) / 1000000000.0;
131                System.out.println("\t " + secs + "s run time");
132            }
133
134        }
135
136        public final Object call() throws Exception {
137            barrier.await();
138            int sum = v;
139            int x = 0;
140            int n = ITERS;
141            while (n-- > 0) {
142                lock.lockInterruptibly();
143                try {
144                    v = x = LoopHelpers.compute1(v);
145                }
146                finally {
147                    lock.unlock();
148                }
149                sum += LoopHelpers.compute2(LoopHelpers.compute2(x));
150            }
151            return new Integer(sum);
152        }
153    }
154
155}
156