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 8040928 8140468
37 * @summary tests ReentrantLock.lockInterruptibly.
38 * Checks for responsiveness of locks to interrupts.
39 */
40
41import static java.util.concurrent.TimeUnit.NANOSECONDS;
42
43import java.util.concurrent.CyclicBarrier;
44import java.util.concurrent.ThreadLocalRandom;
45import java.util.concurrent.locks.ReentrantLock;
46
47public final class CancelledLockLoops {
48    public static void main(String[] args) throws Exception {
49        final int maxThreads = (args.length > 0) ? Integer.parseInt(args[0]) : 5;
50        final int reps = 1;     // increase for stress testing
51
52        for (int j = 0; j < reps; j++) {
53            for (int i = 2; i <= maxThreads; i += (i+1) >>> 1) {
54                new Loops(i).test();
55            }
56        }
57    }
58
59    static final class Loops implements Runnable {
60        private final boolean print = false;
61        private volatile boolean done = false;
62        private int v = ThreadLocalRandom.current().nextInt();
63        private int completed = 0;
64        private volatile int result = 17;
65        private final ReentrantLock lock = new ReentrantLock();
66        private final LoopHelpers.BarrierTimer timer = new LoopHelpers.BarrierTimer();
67        private final CyclicBarrier barrier;
68        private final int nthreads;
69        private volatile Throwable fail = null;
70        Loops(int nthreads) {
71            this.nthreads = nthreads;
72            if (print) System.out.print("Threads: " + nthreads);
73            barrier = new CyclicBarrier(nthreads+1, timer);
74        }
75
76        final void test() throws Exception {
77            final ThreadLocalRandom rnd = ThreadLocalRandom.current();
78            Thread[] threads = new Thread[nthreads];
79            for (int i = 0; i < threads.length; ++i)
80                threads[i] = new Thread(this);
81            for (int i = 0; i < threads.length; ++i)
82                threads[i].start();
83            Thread[] cancels = threads.clone();
84            barrier.await();
85            Thread.sleep(rnd.nextInt(5));
86            for (int i = 0; i < cancels.length-2; ++i) {
87                cancels[i].interrupt();
88                // make sure all OK even when cancellations spaced out
89                if ( (i & 3) == 0)
90                    Thread.sleep(1 + rnd.nextInt(5));
91            }
92            done = true;
93            barrier.await();
94            if (print) {
95                long time = timer.getTime();
96                double secs = (double)(time) / 1000000000.0;
97                System.out.println("\t " + secs + "s run time");
98            }
99
100            int c;
101            lock.lock();
102            try {
103                c = completed;
104            }
105            finally {
106                lock.unlock();
107            }
108            if (c != 2)
109                throw new Error("Completed == " + c + "; expected 2");
110            int r = result;
111            if (r == 0) // avoid overoptimization
112                System.out.println("useless result: " + r);
113            if (fail != null) throw new RuntimeException(fail);
114        }
115
116        public final void run() {
117            try {
118                barrier.await();
119                boolean interrupted = false;
120                long startTime = System.nanoTime();
121                int sum = v;
122                int x = 0;
123                while (!done || Thread.currentThread().isInterrupted()) {
124                    try {
125                        lock.lockInterruptibly();
126                    }
127                    catch (InterruptedException ie) {
128                        interrupted = true;
129                        if (print)
130                            System.out.printf("interrupted after %d millis%n",
131                                              NANOSECONDS.toMillis(System.nanoTime() - startTime));
132                        break;
133                    }
134                    try {
135                        v = x = LoopHelpers.compute1(v);
136                    }
137                    finally {
138                        lock.unlock();
139                    }
140                    sum += LoopHelpers.compute2(x);
141                }
142                if (!interrupted) {
143                    if (print)
144                        System.out.printf("completed after %d millis%n",
145                                          NANOSECONDS.toMillis(System.nanoTime() - startTime));
146                    lock.lock();
147                    try {
148                        ++completed;
149                    }
150                    finally {
151                        lock.unlock();
152                    }
153                }
154                barrier.await();
155                result += sum;
156            }
157            catch (Throwable ex) {
158                fail = ex;
159                throw new RuntimeException(ex);
160            }
161        }
162    }
163
164}
165