Sashi Kant
Sashi Kant

Reputation: 13455

Java multithreading concepts in Semaphores

I created a Semaphore

Semaphore semaphore =  new Semaphore(1);

We have overloaded aquire methods like:

aquire()
aquire(int)

Q1 : For the current semaphore where there is only 1 permit, will the second method(aquire(int)) have any significance?

Q2: I am still a bit confused with

new Semaphore(int)
new Semaphore(int,true)
new Semaphore(int, false)

Q3: If I call release(), without calling aquire(), what happens to the number of permits, does that increase than what we have declared?

Note : There are multiple threads which share the Semaphore Object .

Appreciate any help.

Upvotes: 1

Views: 139

Answers (2)

Solomon Slow
Solomon Slow

Reputation: 27115

Q2: I am still a bit confused with

new Semaphore(int)          //same as new Semaphore(i, false);
new Semaphore(int,true)     //the Semaphore will be "fair".
new Semaphore(int, false)   //the semaphore will not be "fair".

The boolean flag controls whether or not the semaphore is fair. "Fair" means that when more than one thread is blocked waiting to acquire permits, then the waiting threads will get to run in strict first-come first-served order. The first thread to be blocked will be the first one to run, and so on.

When the Semaphore is not fair, then it may be implemented by an algorithm that potentially gives higher performance as compared to the fair algorithm on some computer architectures.

Upvotes: 1

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279880

If your Semaphore starts out with a single permit and a single thread tries to acquire more than 1 permit, then that thread will block. Assuming no other thread will ever call the necessary number of release, then the thread will be blocked indefinitely.

The boolean argument to the overloaded constructor indicates

if this semaphore will guarantee first-in first-out granting of permits under contention, else false

The number of permits you specify in the constructor is just an initial amount, not a limit.

Upvotes: 1

Related Questions