java.util.concurrent.BrokenBarrierException Java Examples

The following examples show how to use java.util.concurrent.BrokenBarrierException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: B4769350.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void handle(HttpExchange exchange) throws IOException {
    count++;
    try {
        switch(count) {
            case 0:
                AuthenticationHandler.errorReply(exchange,
                        "Basic realm=\"realm1\"");
                break;
            case 1:
                t1Cond1.await();
                AuthenticationHandler.okReply(exchange);
                break;
            default:
                System.out.println ("Unexpected request");
        }
    } catch (InterruptedException |
                     BrokenBarrierException e)
            {
                throw new RuntimeException(e);
            }
}
 
Example #2
Source File: CyclicBarrierTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * A reset of an active barrier causes waiting threads to throw
 * BrokenBarrierException
 */
public void testReset_BrokenBarrier() throws InterruptedException {
    final CyclicBarrier c = new CyclicBarrier(3);
    final CountDownLatch pleaseReset = new CountDownLatch(2);
    Thread t1 = new ThreadShouldThrow(BrokenBarrierException.class) {
        public void realRun() throws Exception {
            pleaseReset.countDown();
            c.await();
        }};
    Thread t2 = new ThreadShouldThrow(BrokenBarrierException.class) {
        public void realRun() throws Exception {
            pleaseReset.countDown();
            c.await();
        }};

    t1.start();
    t2.start();
    await(pleaseReset);

    awaitNumberWaiting(c, 2);
    c.reset();
    awaitTermination(t1);
    awaitTermination(t2);
}
 
Example #3
Source File: BusyLock.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void run() {
    try {
        // wait until forceAbort leave monitor
        barrier.await();
        if (UNSAFE.tryMonitorEnter(monitor)) {
            try {
                barrier.await();
                Thread.sleep(timeout);
            } finally {
                UNSAFE.monitorExit(monitor);
            }
        } else {
            throw new RuntimeException("Monitor should be entered by " +
                                       "::run() first.");
        }
    } catch (InterruptedException | BrokenBarrierException e) {
        throw new RuntimeException("Synchronization error happened.", e);
    }
}
 
Example #4
Source File: BusyLock.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void run() {
    try {
        // wait until forceAbort leave monitor
        barrier.await();
        if (UNSAFE.tryMonitorEnter(monitor)) {
            try {
                barrier.await();
                Thread.sleep(timeout);
            } finally {
                UNSAFE.monitorExit(monitor);
            }
        } else {
            throw new RuntimeException("Monitor should be entered by " +
                                       "::run() first.");
        }
    } catch (InterruptedException | BrokenBarrierException e) {
        throw new RuntimeException("Synchronization error happened.", e);
    }
}
 
Example #5
Source File: B4769350.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void handle(HttpExchange exchange) throws IOException {
    count++;
    try {
        switch(count) {
            case 0:
                AuthenticationHandler.errorReply(exchange,
                        "Basic realm=\"realm1\"");
                break;
            case 1:
                t1Cond1.await();
                AuthenticationHandler.okReply(exchange);
                break;
            default:
                System.out.println ("Unexpected request");
        }
    } catch (InterruptedException |
                     BrokenBarrierException e)
            {
                throw new RuntimeException(e);
            }
}
 
Example #6
Source File: B4769350.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void handle(HttpExchange exchange) throws IOException {
    count++;
    try {
        switch(count) {
            case 0:
                AuthenticationHandler.errorReply(exchange,
                        "Basic realm=\"realm2\"");
                break;
            case 1:
                t1Cond1.await();
                AuthenticationHandler.okReply(exchange);
                break;
            default:
                System.out.println ("Unexpected request");
        }
    } catch (InterruptedException | BrokenBarrierException e) {
        throw new RuntimeException(e);
    }
}
 
Example #7
Source File: CyclicBarrierTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * An interruption in one party causes others waiting in timed await to
 * throw BrokenBarrierException
 */
public void testAwait2_Interrupted_BrokenBarrier() throws Exception {
    final CyclicBarrier c = new CyclicBarrier(3);
    final CountDownLatch pleaseInterrupt = new CountDownLatch(2);
    Thread t1 = new ThreadShouldThrow(InterruptedException.class) {
        public void realRun() throws Exception {
            pleaseInterrupt.countDown();
            c.await(LONG_DELAY_MS, MILLISECONDS);
        }};
    Thread t2 = new ThreadShouldThrow(BrokenBarrierException.class) {
        public void realRun() throws Exception {
            pleaseInterrupt.countDown();
            c.await(LONG_DELAY_MS, MILLISECONDS);
        }};

    t1.start();
    t2.start();
    await(pleaseInterrupt);
    t1.interrupt();
    awaitTermination(t1);
    awaitTermination(t2);
}
 
Example #8
Source File: BackgroundActionPauser.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
public void await() {
    if(0 == delay) {
        log.info("No pause between retry");
        return;
    }
    final Timer wakeup = new Timer();
    final CyclicBarrier wait = new CyclicBarrier(2);
    // Schedule for immediate execution with an interval of 1s
    wakeup.scheduleAtFixedRate(new PauserTimerTask(wait), 0, 1000);
    try {
        // Wait for notify from wakeup timer
        wait.await();
    }
    catch(InterruptedException | BrokenBarrierException e) {
        log.error(e.getMessage(), e);
    }
}
 
Example #9
Source File: TransferQueueTest.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testConcurrent() throws Exception {
    final TransferQueue queue = new TransferQueue(1);
    final DownloadTransfer transfer = new DownloadTransfer(new Host(new TestProtocol()), new Path("/t", EnumSet.of(Path.Type.directory)), null);
    queue.add(transfer, new DisabledProgressListener());
    final AtomicBoolean added = new AtomicBoolean();
    final CyclicBarrier wait = new CyclicBarrier(2);
    new Thread(new Runnable() {
        @Override
        public void run() {
            queue.add(new DownloadTransfer(new Host(new TestProtocol()), new Path("/t", EnumSet.of(Path.Type.directory)), null), new DisabledProgressListener());
            added.set(true);
            try {
                wait.await();
            }
            catch(InterruptedException | BrokenBarrierException e) {
                fail();
            }
        }
    }).start();
    assertFalse(added.get());
    queue.remove(transfer);
    wait.await();
    assertTrue(added.get());
}
 
Example #10
Source File: ScoreAligner.java    From mzmine3 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void run() {
  while (!aligningDone()) {
    align();
    // Exceptions cause wrong results but do not report
    // that in any way
    try {
      barrier.await();
    } catch (InterruptedException e) {
      return;
    } catch (BrokenBarrierException e2) {
      return;
    } catch (CancellationException e3) {
      return;
    }
  }
}
 
Example #11
Source File: AwsXRayIdsGeneratorTest.java    From opentelemetry-java with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldGenerateUniqueIdsInMultithreadedEnvironment()
    throws BrokenBarrierException, InterruptedException {
  AwsXRayIdsGenerator generator = new AwsXRayIdsGenerator();
  Set<TraceId> traceIds = new CopyOnWriteArraySet<>();
  Set<SpanId> spanIds = new CopyOnWriteArraySet<>();
  int threads = 8;
  int generations = 128;
  CyclicBarrier barrier = new CyclicBarrier(threads + 1);
  Executor executor = Executors.newFixedThreadPool(threads);
  for (int i = 0; i < threads; i++) {
    executor.execute(new GenerateRunner(generations, generator, barrier, traceIds, spanIds));
  }
  barrier.await();
  barrier.await();
  assertThat(traceIds).hasSize(threads * generations);
  assertThat(spanIds).hasSize(threads * generations);
}
 
Example #12
Source File: B4769350.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void handle(HttpExchange exchange) throws IOException {
    count++;
    try {
        switch(count) {
            case 0:
                AuthenticationHandler.errorReply(exchange,
                        "Basic realm=\"realm1\"");
                break;
            case 1:
                t1Cond1.await();
                t1cond2latch.await();
                AuthenticationHandler.okReply(exchange);
                break;
            default:
                System.out.println ("Unexpected request");
        }
    } catch (InterruptedException |
                     BrokenBarrierException e)
            {
                throw new RuntimeException(e);
            }
}
 
Example #13
Source File: B4769350.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void handle(HttpExchange exchange) throws IOException {
    count++;
    try {
        switch(count) {
            case 0:
                AuthenticationHandler.errorReply(exchange,
                        "Basic realm=\"realm2\"");
                break;
            case 1:
                t1Cond1.await();
                AuthenticationHandler.okReply(exchange);
                break;
            default:
                System.out.println ("Unexpected request");
        }
    } catch (InterruptedException | BrokenBarrierException e) {
        throw new RuntimeException(e);
    }
}
 
Example #14
Source File: UsingBarriers.java    From java-concurrency-patterns with MIT License 6 votes vote down vote up
public static void main(String[] args) {

		Runnable barrierAction = () -> System.out.println("Well done, guys!");

		var executor = Executors.newCachedThreadPool();
		var barrier = new CyclicBarrier(10, barrierAction);

		Runnable task = () -> {
			try {
				// simulating a task that can take at most 1sec to run
				System.out.println("Doing task for " + Thread.currentThread().getName());
				Thread.sleep(new Random().nextInt(10) * 100);
				System.out.println("Done for " + Thread.currentThread().getName());
				barrier.await();
			} catch (InterruptedException | BrokenBarrierException e) {
				e.printStackTrace();
			}
		};

		for (int i = 0; i < 10; i++) {
			executor.execute(task);
		}
		executor.shutdown();

	}
 
Example #15
Source File: CyclicBarrierDemo.java    From blog-sample with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    ExecutorService executorService = Executors.newCachedThreadPool();
    CyclicBarrier cyclicBarrier = new CyclicBarrier(6);
    for (int i = 1; i <= 18; i++) {
        executorService.execute(() -> {
            System.out.println(Thread.currentThread().getName() + "开始等待其他线程");
            try {
                cyclicBarrier.await();
                System.out.println(Thread.currentThread().getName() + "开始执行业务逻辑,耗时0.5秒");
                // 工作线程开始处理,这里用Thread.sleep()来模拟业务处理
                Thread.sleep(500);
                System.out.println(Thread.currentThread().getName() + "业务逻辑执行完毕");
            } catch (InterruptedException | BrokenBarrierException e) {
                e.printStackTrace();
            }
        });
    }
    executorService.shutdown();
}
 
Example #16
Source File: HelloServer.java    From apm-agent-java with Apache License 2.0 6 votes vote down vote up
private void syncWait(boolean isStart) {
    Sync sync = syncBarriers.get();
    if (sync != null) {
        String step = isStart ? "start" : "end";
        logVerbose("server waiting sync on " + step);
        CyclicBarrier barrier = isStart ? sync.processingStart : sync.processingEnd;
        long waitStart = System.currentTimeMillis();
        try {
            barrier.await();
        } catch (InterruptedException | BrokenBarrierException e) {
            throw new RuntimeException(e);
        } finally {
            barrier.reset();
        }
        long waitedMillis = System.currentTimeMillis() - waitStart;
        logVerbose("waited for {} ms at processing {}", waitedMillis, step);
    }
}
 
Example #17
Source File: CyclicBarrierTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * An interruption in one party causes others waiting in await to
 * throw BrokenBarrierException
 */
public void testAwait1_Interrupted_BrokenBarrier() {
    final CyclicBarrier c = new CyclicBarrier(3);
    final CountDownLatch pleaseInterrupt = new CountDownLatch(2);
    Thread t1 = new ThreadShouldThrow(InterruptedException.class) {
        public void realRun() throws Exception {
            pleaseInterrupt.countDown();
            c.await();
        }};
    Thread t2 = new ThreadShouldThrow(BrokenBarrierException.class) {
        public void realRun() throws Exception {
            pleaseInterrupt.countDown();
            c.await();
        }};

    t1.start();
    t2.start();
    await(pleaseInterrupt);
    t1.interrupt();
    awaitTermination(t1);
    awaitTermination(t2);
}
 
Example #18
Source File: CyclicBarrierDemo02.java    From javacore with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
@Override
public void run() {
    try {
        Thread.sleep(1000);
        System.out.println(Thread.currentThread().getName() + " waiting at barrier 1");
        this.barrier1.await();

        Thread.sleep(1000);
        System.out.println(Thread.currentThread().getName() + " waiting at barrier 2");
        this.barrier2.await();

        System.out.println(Thread.currentThread().getName() + " done!");
    } catch (InterruptedException | BrokenBarrierException e) {
        e.printStackTrace();
    }
}
 
Example #19
Source File: WorkloadMemoryTest.java    From Oak with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    try {
        barrier.await();
    } catch (InterruptedException | BrokenBarrierException e) {
        e.printStackTrace();
    }

    Random r = new Random();
    while (!stop.get()) {
        Integer key = r.nextInt(NUM_OF_ENTRIES);
        int op = r.nextInt(100);

        if (op < getPercents) {
            oak.zc().get(key);
        } else {
            oak.zc().put(key, 8);
        }
    }
}
 
Example #20
Source File: B4769350.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void handle(HttpExchange exchange) throws IOException {
    count++;
    switch(count) {
        case 0:
            AuthenticationHandler.errorReply(exchange,
                    "Basic realm=\"realm2\"");
            try {
                t1Cond2.await();
            } catch (InterruptedException |
                     BrokenBarrierException e)
            {
                throw new RuntimeException(e);
            }
            t1cond2latch.countDown();
            break;
        case 1:
            AuthenticationHandler.okReply(exchange);
            break;
        default:
            System.out.println ("Unexpected request");
    }
}
 
Example #21
Source File: B4769350.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void handle(HttpExchange exchange) throws IOException {
    count++;
    switch(count) {
        case 0:
            AuthenticationHandler.errorReply(exchange,
                    "Basic realm=\"realm1\"");
            try {
                t1Cond2.await();
            } catch (InterruptedException |
                     BrokenBarrierException e)
            {
                throw new RuntimeException(e);
            }
            break;
        case 1:
            AuthenticationHandler.okReply(exchange);
            break;
        default:
            System.out.println ("Unexpected request");
    }
}
 
Example #22
Source File: ConnectableBufferOutputStreamTest.java    From servicetalk with Apache License 2.0 6 votes vote down vote up
@Test
public void subscribeCloseSynchronously() throws Exception {
    AtomicReference<Future<?>> futureRef = new AtomicReference<>();
    toSource(cbos.connect().afterOnSubscribe(subscription -> {
        // We want to increase the chance that the writer thread has to wait for the Subscriber to become
        // available, instead of waiting for the requestN demand.
        CyclicBarrier barrier = new CyclicBarrier(2);
        futureRef.compareAndSet(null, executorService.submit(toRunnable(() -> {
            barrier.await();
            cbos.close();
        })));
        try {
            barrier.await();
        } catch (InterruptedException | BrokenBarrierException e) {
            throw new RuntimeException(e);
        }
    })).subscribe(subscriber);

    Future<?> f = futureRef.get();
    assertNotNull(f);
    f.get();
    assertThat(subscriber.takeTerminal(), is(complete()));
}
 
Example #23
Source File: B4769350.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void handle(HttpExchange exchange) throws IOException {
    count++;
    try {
        switch(count) {
            case 0:
                AuthenticationHandler.errorReply(exchange,
                        "Basic realm=\"realm2\"");
                break;
            case 1:
                t1Cond1.await();
                t1cond1latch.countDown();
                t1cond2latch.await();
                AuthenticationHandler.okReply(exchange);
                break;
            default:
                System.out.println ("Unexpected request");
        }
    } catch (InterruptedException | BrokenBarrierException e) {
        throw new RuntimeException(e);
    }
}
 
Example #24
Source File: ConnectablePayloadWriterTest.java    From servicetalk with Apache License 2.0 6 votes vote down vote up
@Test
public void subscribeCloseSynchronously() throws Exception {
    AtomicReference<Future<?>> futureRef = new AtomicReference<>();
    toSource(cpw.connect().afterOnSubscribe(subscription -> {
        // We want to increase the chance that the writer thread has to wait for the Subscriber to become
        // available, instead of waiting for the requestN demand.
        CyclicBarrier barrier = new CyclicBarrier(2);
        futureRef.compareAndSet(null, executorService.submit(toRunnable(() -> {
            barrier.await();
            cpw.close();
        })));
        try {
            barrier.await();
        } catch (InterruptedException | BrokenBarrierException e) {
            throw new RuntimeException(e);
        }
    })).subscribe(subscriber);

    Future<?> f = futureRef.get();
    assertNotNull(f);
    f.get();
    assertThat(subscriber.takeTerminal(), is(complete()));
}
 
Example #25
Source File: B4769350.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void handle(HttpExchange exchange) throws IOException {
    count++;
    try {
        switch(count) {
            case 0:
                AuthenticationHandler.errorReply(exchange,
                        "Basic realm=\"realm1\"");
                break;
            case 1:
                t1Cond1.await();
                t1cond2latch.await();
                AuthenticationHandler.okReply(exchange);
                break;
            default:
                System.out.println ("Unexpected request");
        }
    } catch (InterruptedException |
                     BrokenBarrierException e)
            {
                throw new RuntimeException(e);
            }
}
 
Example #26
Source File: BusyLock.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void run() {
    try {
        // wait until forceAbort leave monitor
        barrier.await();
        if (UNSAFE.tryMonitorEnter(monitor)) {
            try {
                barrier.await();
                Thread.sleep(timeout);
            } finally {
                UNSAFE.monitorExit(monitor);
            }
        } else {
            throw new RuntimeException("Monitor should be entered by " +
                                       "::run() first.");
        }
    } catch (InterruptedException | BrokenBarrierException e) {
        throw new RuntimeException("Synchronization error happened.", e);
    }
}
 
Example #27
Source File: B4769350.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void handle(HttpExchange exchange) throws IOException {
    count++;
    try {
        switch(count) {
            case 0:
                AuthenticationHandler.errorReply(exchange,
                        "Basic realm=\"realm2\"");
                break;
            case 1:
                t1Cond1.await();
                AuthenticationHandler.okReply(exchange);
                break;
            default:
                System.out.println ("Unexpected request");
        }
    } catch (InterruptedException | BrokenBarrierException e) {
        throw new RuntimeException(e);
    }
}
 
Example #28
Source File: B4769350.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void handle(HttpExchange exchange) throws IOException {
    count++;
    try {
        switch(count) {
            case 0:
                AuthenticationHandler.errorReply(exchange,
                        "Basic realm=\"realm1\"");
                break;
            case 1:
                t1Cond1.await();
                AuthenticationHandler.okReply(exchange);
                break;
            default:
                System.out.println ("Unexpected request");
        }
    } catch (InterruptedException |
                     BrokenBarrierException e)
            {
                throw new RuntimeException(e);
            }
}
 
Example #29
Source File: WorkloadMemoryTest.java    From Oak with Apache License 2.0 5 votes vote down vote up
private static void testMain() throws InterruptedException {
    printHeapStats("Initial stats");
    for (int i = 0; i < NUM_THREADS; i++) {
        threads.add(new Thread(new RunThread()));
    }
    Random r = new Random();
    for (int i = 0; i < (int) Math.round(NUM_OF_ENTRIES * 0.5); ) {
        Integer key = r.nextInt(NUM_OF_ENTRIES);
        if (oak.putIfAbsent(key, 8) == null) {
            i++;
        }
    }

    printHeapStats("After warm-up");

    for (int i = 0; i < NUM_THREADS; i++) {
        threads.get(i).start();
    }

    try {
        barrier.await();
    } catch (InterruptedException | BrokenBarrierException e) {
        e.printStackTrace();
    }

    Thread.sleep(DURATION);

    stop.set(true);

    for (int i = 0; i < NUM_THREADS; i++) {
        threads.get(i).join();
    }

    printHeapStats("End of test");
}
 
Example #30
Source File: WaitStrategyTestUtil.java    From sofa-tracer with Apache License 2.0 5 votes vote down vote up
public static void assertWaitForWithDelayOf(long sleepTimeMillis, WaitStrategy waitStrategy)
                                                                                            throws InterruptedException,
                                                                                            BrokenBarrierException,
                                                                                            AlertException,
                                                                                            TimeoutException {
    SequenceUpdater sequenceUpdater = new SequenceUpdater(sleepTimeMillis, waitStrategy);
    EXECUTOR.execute(sequenceUpdater);
    sequenceUpdater.waitForStartup();
    Sequence cursor = new Sequence(0);
    long sequence = waitStrategy.waitFor(0, cursor, sequenceUpdater.sequence,
        new DummySequenceBarrier());
    assertThat(sequence, is(0L));
}