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 Project: opentelemetry-java   Author: open-telemetry   File: AwsXRayIdsGeneratorTest.java    License: 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 #2
Source Project: mzmine3   Author: mzmine   File: ScoreAligner.java    License: 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 #3
Source Project: dragonwell8_jdk   Author: alibaba   File: B4769350.java    License: 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 #4
Source Project: TencentKona-8   Author: Tencent   File: BusyLock.java    License: 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 Project: jdk8u-jdk   Author: lambdalab-mirror   File: B4769350.java    License: 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 #6
Source Project: TencentKona-8   Author: Tencent   File: B4769350.java    License: 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 #7
Source Project: TencentKona-8   Author: Tencent   File: B4769350.java    License: 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 #8
Source Project: java-concurrency-patterns   Author: LeonardoZ   File: UsingBarriers.java    License: 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 #9
Source Project: blog-sample   Author: jitwxs   File: CyclicBarrierDemo.java    License: 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 #10
Source Project: apm-agent-java   Author: elastic   File: HelloServer.java    License: 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 #11
Source Project: servicetalk   Author: apple   File: ConnectableBufferOutputStreamTest.java    License: 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 #12
Source Project: servicetalk   Author: apple   File: ConnectablePayloadWriterTest.java    License: 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 #13
Source Project: jdk8u60   Author: chenghanpeng   File: BusyLock.java    License: 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 #14
Source Project: jdk8u60   Author: chenghanpeng   File: B4769350.java    License: 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 #15
Source Project: jdk8u60   Author: chenghanpeng   File: B4769350.java    License: 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 #16
Source Project: jdk8u60   Author: chenghanpeng   File: B4769350.java    License: 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 #17
Source Project: jdk8u60   Author: chenghanpeng   File: B4769350.java    License: 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 #18
Source Project: Oak   Author: yahoo   File: WorkloadMemoryTest.java    License: 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 #19
Source Project: openjdk-jdk8u   Author: AdoptOpenJDK   File: BusyLock.java    License: 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 #20
Source Project: openjdk-jdk8u   Author: AdoptOpenJDK   File: B4769350.java    License: 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 #21
Source Project: openjdk-jdk8u   Author: AdoptOpenJDK   File: B4769350.java    License: 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 #22
@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 #23
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: CyclicBarrierTest.java    License: 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 #24
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: CyclicBarrierTest.java    License: 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 #25
Source Project: openjdk-jdk8u-backup   Author: AdoptOpenJDK   File: B4769350.java    License: 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 #26
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: CyclicBarrierTest.java    License: 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 #27
Source Project: cyberduck   Author: iterate-ch   File: BackgroundActionPauser.java    License: 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 #28
Source Project: cyberduck   Author: iterate-ch   File: TransferQueueTest.java    License: 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 #29
Source Project: swim   Author: swimos   File: MockClock.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void sleep(long millis) throws InterruptedException {
  try {
    this.tickBarrier.await();
    this.tickBarrier.await();
  } catch (BrokenBarrierException cause) {
    throw new RuntimeException(cause);
  }
}
 
Example #30
Source Project: swim   Author: swimos   File: MockClock.java    License: Apache License 2.0 5 votes vote down vote up
void halfTick() {
  try {
    tickBarrier.await();
  } catch (BrokenBarrierException | InterruptedException error) {
    throw new TestException(error);
  }
}