KilyenOrs
KilyenOrs

Reputation: 1496

Incrementing Semaphore permits, in Java

Can I add more permit to a semaphore in Java?

Semaphore s = new Semaphore(3);

After this somewhere in the code i want to change the permits to 4. Is this possible?

Upvotes: 15

Views: 5363

Answers (1)

Jim
Jim

Reputation: 22656

Yes. The release method (confusingly named imo) can be used to increment permits since, from the docs:

There is no requirement that a thread that releases a permit must 
have acquired that permit by calling acquire. 
Correct usage of a semaphore is established by programming convention
in the application. 

In other words:

semaphore.release(10);

Will add 10 more permits if the thread calling hasn't acquired any.

Upvotes: 24

Related Questions