1

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.

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for replying, there are multiple threads which share the Semaphore object
@SashiKant The number of permits you specify in the constructor is just an initial amount, not a limit.
up 1 for your comment, but I am still confused with *** Question 2 and 3 ***
@SashiKant Can you clarify what you don't understand? Multiple threads may invoke acquire. Setting the flag to true in the constructor will guarantee the order in which threads will receive the permits (FIFO). Since the initial number of permits isn't a limit, any number of threads can call release and the number of permits will keep increasing.
1

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.

1 Comment

Thanks for your inputs, Hope there would had been an option to select multiple correct answer rather than selecting one :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.