Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Semaphore and Barrier | High-level Synchronization Mechanisms
Multithreading in Java
course content

Conteúdo do Curso

Multithreading in Java

Multithreading in Java

1. Multithreading Basics
2. Synchronized Collections
3. High-level Synchronization Mechanisms
4. Multithreading Best Practices

Semaphore and Barrier

In multithreaded programs, it’s often necessary to control access to resources or synchronize thread execution. Semaphore and Barrier are high-level synchronization mechanisms that help address these challenges.

Today, we’ll explore each of these mechanisms in sequence and understand their differences. Let’s begin with Semaphore.

Semaphore in Java are implemented through the java.util.concurrent.Semaphore class.

Constructors

Semaphore(int permits): Constructor that creates a semaphore with a certain number of permissions. The permissions represent the number of accesses to the shared resource.

java

Main

Semaphore(int permits, boolean fair): Сonstructor that provides first-come, first-served resolution.

java

Main

If fair is set to true, the semaphore will grant permissions in first-in-first-out (FIFO) order, which can help avoid starvation. Default - false.

Main Methods

The acquire() method requests a single permission. If a permission is available, it’s granted immediately; otherwise, the thread is blocked until a permission becomes available. Once a task is completed, the release() method is used to release the permission, returning it to the semaphore. If other threads were waiting for a permission, one of them will be unblocked.

Imagine a parking lot with a limited number of spaces. The semaphore functions as a controller, keeping track of the available spaces and denying access once the lot is full.

java

Main

You can also find out how many permissions are currently available in Semaphore using the int availablePermits() method. You can also try to get a permission using the boolean tryAcquire() method, returns true if a permission was obtained and false if not.

java

Main

Outcomes

In other words, a Semaphore is useful when you need to provide limited simultaneous access to a specific code segment. The only drawback is the potential for a deadlock if threads are blocked in the wrong order.

Now, let’s move on to the next synchronization mechanism that is even simpler to use but will be 100 percent valuable for your needs.

CyclicBarrier

Barrier in Java are represented by the java.util.concurrent.CyclicBarrier class. The main methods of CyclicBarrier include:

Constructors CyclicBarrier

CyclicBarrier(int parties): Constructor that creates a barrier that blocks threads until a certain number of threads (parties) arrive.

java

Main

CyclicBarrier(int parties, Runnable barrierAction): Constructor that creates a barrier with a given number of parties and an action (barrierAction) that is executed when all parties arrive at the barrier.

java

Main

Methods CyclicBarrier

The main method await() which is used as a barrier and does not let the thread go any further until all threads reach this method. Returns a sequence number indicating the order of arrival of the participants.

java

Main

It may happen that not all threads will reach the barrier and the program will hang, for this purpose int await(long timeout, TimeUnit unit) method is used, which is similar to await(), but with timeout. If the timeout expires before all participants arrive, the method generates a TimeoutException exception.

You can also find out the number of participants required to complete the barrier int getParties() and its similar method int getNumberWaiting() which returns the number of participants currently waiting at the barrier.

java

Main

It is also possible to check if the barrier has been destroyed if one of the threads is interrupted or the waiting timeout has expired using the boolean isBroken() method. If it has been broken, you can use the void reset() method which will simply restore the barrier.

java

Main

Note

It should be taken into account that some flow may not reach the barrier because of an error or something else and then it is clear that the barrier will not allow those flows that are currently waiting at the barrier

Tudo estava claro?

Seção 3. Capítulo 3
We're sorry to hear that something went wrong. What happened?
some-alt