Difference between Semaphore initialized with 1 and 0

Atul Kumar picture Atul Kumar · Aug 29, 2014 · Viewed 17.8k times · Source

Please tell what is difference Semaphore initialized with 1 and zero. as below:

public static Semaphore semOne = new Semaphore(1);

and

public static Semaphore semZero = new Semaphore(0);

Answer

Chip picture Chip · Aug 29, 2014

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.