Search code examples
javasemaphorejava.util.concurrent

Difference between Semaphore initialized with 1 and 0


Please tell what is difference between a Semaphore initialized with 1 and Vs. intialized zero, as below:

public static Semaphore semOne = new Semaphore(1);

and

public static Semaphore semZero = new Semaphore(0);

Solution

  • The argument to the Semaphore instance is the number of "permits" that are available. It can be any integer, not just 0 or 1.

    For semZero all acquire() calls will block and tryAcquire() calls will return false, until you do a release()

    For semOne the first acquire() calls will succeed and the rest will block until the first one releases.

    The class is well documented here.

    Parameters: permits - the initial number of permits available. This value may be negative, in which case releases must occur before any acquires will be granted.