BrokenBarrierException

Understand the causes of BrokenBarrierException with runnable code examples in the browser.

We'll cover the following

If you are interviewing, consider buying our number#1 course for Java Multithreading Interviews.

Overview

The BrokenBarrierException is usually an indication of a programming flaw. It occurs when:

  1. A thread is already waiting on a barrier and the barrier enters the broken state.
  2. A thread attempts to wait on a barrier that is in the broken state.

Example

Consider the program below that submits two tasks to the executor. Both the tasks await() on a CyclicBarrier object, which is initialized with a count of 3, i.e. three threads must await() the barrier object before they can proceed forward. The main thread cancel()-s one of the tasks. The thread executing the task is already waiting on the barrier and experiences an InterruptedException. At this point the barrier is broken and the second task throws BrokenBarrierException. This sequence of events manifests the first condition described above i.e. BrokenBarrierException is thrown when a barrier is broken and there are threads already waiting on the barrier object.

The other condition when a BrokenBarrierException is thrown, is when a thread attempts to await() an already broken barrier. This is showcased by the main thread when it await()-s the broken barrier object on line#55 and the program exits with the BrokenBarrierException.

Create a free account to view this lesson.

By signing up, you agree to Educative's Terms of Service and Privacy Policy