1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
|
/*
* Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 6253848 6366811
* @summary Basic tests for CyclicBarrier
* @library /lib/testlibrary/
* @author Martin Buchholz, David Holmes
*/
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import jdk.testlibrary.Utils;
public class Basic {
static final long LONG_DELAY_MS = Utils.adjustTimeout(10_000);
private static void checkBroken(final CyclicBarrier barrier) {
check(barrier.isBroken());
equal(barrier.getNumberWaiting(), 0);
THROWS(BrokenBarrierException.class,
() -> barrier.await(),
() -> barrier.await(100, MILLISECONDS));
}
private static void reset(CyclicBarrier barrier) {
barrier.reset();
check(! barrier.isBroken());
equal(barrier.getNumberWaiting(), 0);
}
private static void checkResult(Awaiter a, Class<? extends Throwable> c) {
Throwable t = a.result();
if (! ((t == null && c == null) || (c != null && c.isInstance(t)))) {
// t.printStackTrace();
fail("Mismatch in thread " +
a.getName() + ": " +
t + ", " +
(c == null ? "<null>" : c.getName()));
} else {
pass();
}
}
//----------------------------------------------------------------
// Mechanism to get all victim threads into "running" mode.
// The fact that this also uses CyclicBarrier is entirely coincidental.
//----------------------------------------------------------------
private static final CyclicBarrier atTheStartingGate = new CyclicBarrier(3);
private static void toTheStartingGate() {
try { atTheStartingGate.await(LONG_DELAY_MS, MILLISECONDS); pass(); }
catch (Throwable t) {
unexpected(t);
reset(atTheStartingGate);
throw new Error(t);
}
}
//----------------------------------------------------------------
// Convenience methods for creating threads that call CyclicBarrier.await
//----------------------------------------------------------------
private abstract static class Awaiter extends Thread {
static AtomicInteger count = new AtomicInteger(1);
{
this.setName("Awaiter:"+count.getAndIncrement());
this.setDaemon(true);
}
private volatile Throwable result = null;
protected void result(Throwable result) { this.result = result; }
public Throwable result() { return this.result; }
}
private static Awaiter awaiter(final CyclicBarrier barrier) {
return new Awaiter() { public void run() {
toTheStartingGate();
try { barrier.await(); }
catch (Throwable result) { result(result); }}};
}
private static Awaiter awaiter(final CyclicBarrier barrier,
final long millis) {
return new Awaiter() { public void run() {
toTheStartingGate();
try { barrier.await(millis, MILLISECONDS); }
catch (Throwable result) { result(result); }}};
}
// Returns an infinite lazy list of all possible awaiter pair combinations.
private static Iterator<Awaiter> awaiterIterator(final CyclicBarrier barrier) {
return new Iterator<Awaiter>() {
int i = 0;
public boolean hasNext() { return true; }
public Awaiter next() {
switch ((i++)&7) {
case 0: case 2: case 4: case 5:
return awaiter(barrier);
default:
return awaiter(barrier, 10 * 1000); }}
public void remove() {throw new UnsupportedOperationException();}};
}
private static void realMain(String[] args) throws Throwable {
Thread.currentThread().setName("mainThread");
//----------------------------------------------------------------
// Normal use
//----------------------------------------------------------------
try {
CyclicBarrier barrier = new CyclicBarrier(3);
equal(barrier.getParties(), 3);
Iterator<Awaiter> awaiters = awaiterIterator(barrier);
for (boolean doReset : new boolean[] {false, true})
for (int i = 0; i < 4; i++) {
Awaiter a1 = awaiters.next(); a1.start();
Awaiter a2 = awaiters.next(); a2.start();
toTheStartingGate();
barrier.await();
a1.join();
a2.join();
checkResult(a1, null);
checkResult(a2, null);
check(! barrier.isBroken());
equal(barrier.getParties(), 3);
equal(barrier.getNumberWaiting(), 0);
if (doReset) reset(barrier);
}
} catch (Throwable t) { unexpected(t); }
//----------------------------------------------------------------
// One thread interrupted
//----------------------------------------------------------------
try {
CyclicBarrier barrier = new CyclicBarrier(3);
Iterator<Awaiter> awaiters = awaiterIterator(barrier);
for (int i = 0; i < 4; i++) {
Awaiter a1 = awaiters.next(); a1.start();
Awaiter a2 = awaiters.next(); a2.start();
toTheStartingGate();
a1.interrupt();
a1.join();
a2.join();
checkResult(a1, InterruptedException.class);
checkResult(a2, BrokenBarrierException.class);
checkBroken(barrier);
reset(barrier);
}
} catch (Throwable t) { unexpected(t); }
//----------------------------------------------------------------
// Barrier is reset while threads are waiting
//----------------------------------------------------------------
try {
CyclicBarrier barrier = new CyclicBarrier(3);
Iterator<Awaiter> awaiters = awaiterIterator(barrier);
for (int i = 0; i < 4; i++) {
Awaiter a1 = awaiters.next(); a1.start();
Awaiter a2 = awaiters.next(); a2.start();
toTheStartingGate();
while (barrier.getNumberWaiting() < 2) Thread.yield();
barrier.reset();
a1.join();
a2.join();
checkResult(a1, BrokenBarrierException.class);
checkResult(a2, BrokenBarrierException.class);
check(! barrier.isBroken());
equal(barrier.getParties(), 3);
equal(barrier.getNumberWaiting(), 0);
}
} catch (Throwable t) { unexpected(t); }
//----------------------------------------------------------------
// One thread timed out
//----------------------------------------------------------------
try {
CyclicBarrier barrier = new CyclicBarrier(3);
Iterator<Awaiter> awaiters = awaiterIterator(barrier);
for (long timeout : new long[] { 0L, 10L }) {
for (int i = 0; i < 2; i++) {
Awaiter a1 = awaiter(barrier, timeout); a1.start();
Awaiter a2 = awaiters.next(); a2.start();
toTheStartingGate();
a1.join();
a2.join();
checkResult(a1, TimeoutException.class);
checkResult(a2, BrokenBarrierException.class);
checkBroken(barrier);
equal(barrier.getParties(), 3);
reset(barrier);
}
}
} catch (Throwable t) { unexpected(t); }
//----------------------------------------------------------------
// Barrier action completed normally
//----------------------------------------------------------------
try {
final AtomicInteger count = new AtomicInteger(0);
final CyclicBarrier[] kludge = new CyclicBarrier[1];
Runnable action = new Runnable() { public void run() {
count.incrementAndGet();
equal(kludge[0].getNumberWaiting(),
kludge[0].getParties());
System.out.println("OK!"); }};
CyclicBarrier barrier = new CyclicBarrier(3, action);
kludge[0] = barrier;
equal(barrier.getParties(), 3);
Iterator<Awaiter> awaiters = awaiterIterator(barrier);
for (int i = 0; i < 4; i++) {
Awaiter a1 = awaiters.next(); a1.start();
Awaiter a2 = awaiters.next(); a2.start();
toTheStartingGate();
while (barrier.getNumberWaiting() < 2) Thread.yield();
try { barrier.await(); }
catch (Throwable t) { unexpected(t); }
a1.join();
a2.join();
checkResult(a1, null);
checkResult(a2, null);
check(! barrier.isBroken());
equal(barrier.getNumberWaiting(), 0);
reset(barrier);
equal(count.get(), i+1);
}
} catch (Throwable t) { unexpected(t); }
//----------------------------------------------------------------
// Barrier action threw exception
//----------------------------------------------------------------
try {
Runnable action = new Runnable() {
public void run() { throw new Error(); }};
CyclicBarrier barrier = new CyclicBarrier(3, action);
Iterator<Awaiter> awaiters = awaiterIterator(barrier);
for (int i = 0; i < 4; i++) {
Awaiter a1 = awaiters.next(); a1.start();
Awaiter a2 = awaiters.next(); a2.start();
toTheStartingGate();
while (barrier.getNumberWaiting() < 2) Thread.yield();
try {
barrier.await();
fail("Expected Error not thrown"); }
catch (Error e) { pass(); }
catch (Throwable t) { unexpected(t); }
a1.join();
a2.join();
checkResult(a1, BrokenBarrierException.class);
checkResult(a2, BrokenBarrierException.class);
checkBroken(barrier);
reset(barrier);
}
} catch (Throwable t) { unexpected(t); }
testInterrupts();
}
/**
* Handling of extra interrupts while waiting - tests for bug 6366811
*/
private static void testInterrupts() {
final int N = 10;
final CyclicBarrier startingGate = new CyclicBarrier(N+1);
/**
* A version of Awaiter that also records interrupted state.
*/
class Waiter extends CheckedThread {
private boolean timed;
private CyclicBarrier barrier;
private CountDownLatch doneSignal;
private Throwable throwable;
private boolean interrupted;
public Waiter(boolean timed,
CountDownLatch doneSignal,
CyclicBarrier barrier) {
this.timed = timed;
this.doneSignal = doneSignal;
this.barrier = barrier;
}
Throwable throwable() { return this.throwable; }
boolean interruptBit() { return this.interrupted; }
void realRun() throws Throwable {
startingGate.await(LONG_DELAY_MS, MILLISECONDS);
try {
if (timed) barrier.await(LONG_DELAY_MS, MILLISECONDS);
else barrier.await(); }
catch (Throwable throwable) { this.throwable = throwable; }
try { doneSignal.await(LONG_DELAY_MS, MILLISECONDS); }
catch (InterruptedException e) { interrupted = true; }
}
}
//----------------------------------------------------------------
// Interrupt occurs during barrier trip
//----------------------------------------------------------------
try {
final CountDownLatch doneSignal = new CountDownLatch(1);
final List<Waiter> waiters = new ArrayList<>(N);
// work around finality of closed-over variables
final Runnable[] realAction = new Runnable[1];
final Runnable delegateAction =
new Runnable() {public void run() {realAction[0].run();}};
final CyclicBarrier barrier = new CyclicBarrier(N+1, delegateAction);
realAction[0] = new Runnable() { public void run() {
try {
for (int i = 0; i < N/2; i++)
waiters.get(i).interrupt();
// we need to try and ensure that the waiters get
// to process their interruption before we do the
// signalAll that trips the barrier. Using sleep
// seems to work reliably while yield does not.
Thread.sleep(100);
} catch (Throwable t) { unexpected(t); }
}};
for (int i = 0; i < N; i++) {
Waiter waiter = new Waiter(i < N/2, doneSignal, barrier);
waiter.start();
waiters.add(waiter);
}
startingGate.await(LONG_DELAY_MS, MILLISECONDS);
while (barrier.getNumberWaiting() < N) Thread.yield();
barrier.await();
doneSignal.countDown();
int countInterrupted = 0;
int countInterruptedException = 0;
int countBrokenBarrierException = 0;
for (Waiter waiter : waiters) {
waiter.join();
equal(waiter.throwable(), null);
if (waiter.interruptBit())
countInterrupted++;
}
equal(countInterrupted, N/2);
check(! barrier.isBroken());
} catch (Throwable t) { unexpected(t); }
//----------------------------------------------------------------
// Multiple interrupts occur during barrier await
//----------------------------------------------------------------
try {
final CountDownLatch doneSignal = new CountDownLatch(1);
final CyclicBarrier barrier = new CyclicBarrier(N+1);
final List<Waiter> waiters = new ArrayList<>(N);
for (int i = 0; i < N; i++) {
Waiter waiter = new Waiter(i < N/2, doneSignal, barrier);
waiter.start();
waiters.add(waiter);
}
startingGate.await(LONG_DELAY_MS, MILLISECONDS);
while (barrier.getNumberWaiting() < N) Thread.yield();
for (int i = 0; i < N/2; i++)
waiters.get(i).interrupt();
doneSignal.countDown();
int countInterrupted = 0;
int countInterruptedException = 0;
int countBrokenBarrierException = 0;
for (Waiter waiter : waiters) {
waiter.join();
if (waiter.throwable() instanceof InterruptedException)
countInterruptedException++;
if (waiter.throwable() instanceof BrokenBarrierException)
countBrokenBarrierException++;
if (waiter.interruptBit())
countInterrupted++;
}
equal(countInterrupted, N/2-1);
equal(countInterruptedException, 1);
equal(countBrokenBarrierException, N-1);
checkBroken(barrier);
reset(barrier);
} catch (Throwable t) { unexpected(t); }
}
//--------------------- Infrastructure ---------------------------
static volatile int passed = 0, failed = 0;
static void pass() {passed++;}
static void fail() {failed++; Thread.dumpStack();}
static void fail(String msg) {System.out.println(msg); fail();}
static void unexpected(Throwable t) {failed++; t.printStackTrace();}
static void check(boolean cond) {if (cond) pass(); else fail();}
static void equal(Object x, Object y) {
if (x == null ? y == null : x.equals(y)) pass();
else fail(x + " not equal to " + y);}
public static void main(String[] args) throws Throwable {
try {realMain(args);} catch (Throwable t) {unexpected(t);}
System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
if (failed > 0) throw new AssertionError("Some tests failed");}
interface Fun {void f() throws Throwable;}
private static void THROWS(Class<? extends Throwable> k, Fun... fs) {
for (Fun f : fs)
try { f.f(); fail("Expected " + k.getName() + " not thrown"); }
catch (Throwable t) {
if (k.isAssignableFrom(t.getClass())) pass();
else unexpected(t);}}
private abstract static class CheckedThread extends Thread {
abstract void realRun() throws Throwable;
public void run() {
try {realRun();} catch (Throwable t) {unexpected(t);}}}
}
|