Semaphores on Java – Some Edge Cases

At work, we recently had a discussion about semaphores. With these two tests, I want to shed some light on using semaphores on the JVM with Java:

import java.util.concurrent.Semaphore;

import org.junit.Assert;
import org.junit.Test;

public class SemaphoreTests {

public void releaseWithoutPreviousAcquirePossible() {
Semaphore semaphore = new Semaphore(1, true);
Assert.assertEquals(2, semaphore.availablePermits());

@Test(expected = Error.class)
public void upperBoundOfSempahoreDefinedByMaxInteger() {
new Semaphore(Integer.MAX_VALUE).release();

2 thoughts on “Semaphores on Java – Some Edge Cases

  1. So what is your suggestion for locking data?

    Lets say I cannot use high level constructs like ConcurrentHashMap for some reason. Should I stick to semaphores or is there a better alternative?

  2. It always depends on the use case (as always…). Sorry, but this is true for concurrency as well.

    The best way to use concurrency, in my opinion, is to divide a problem into sub-problems that can be solved in parallel without sharing data, e.g., with the fork-join framework or using callables with the executor framework. Using this style of programming, the amount of concurrency bugs should be smallest ceteris paribus.

    Semaphores are also fine, but need careful handling as they do not ensure that before a release, the thread has acquired the semaphore lock (see code snippets above). Nevertheless, you can write a simple wrapper class that provides this additional functionality.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s