jayendra bhatt
jayendra bhatt

Reputation: 1385

how to implement of semaphore

I am going through this link , here the implementation of coiunting semaphore is given as :

public class CountingSemaphore {
  private int signals = 0;

  public synchronized void take() {
    this.signals++;
    this.notify();
  }

  public synchronized void release() throws InterruptedException{
    while(this.signals == 0) wait();
    this.signals--;
  }

}

i am not able to get that. in the take() method , notify is called which will make other threads to enter the section.Shouldnt there be wait inside take method. please help me understand.

Thanks

Jayendra

Upvotes: 2

Views: 98

Answers (3)

avh
avh

Reputation: 188

The method names are switched by a translation error, see the original author's comment. The code makes no sense in this form, since it will produce a deadlock: the release will only decrease the counter if it's zero, which will never happen again!

If you swap the calls, i.e. lock by calling 'release', the semaphore will work, but not count.

Upvotes: 0

Thilo
Thilo

Reputation: 262474

The first comment on that article points out:

Don't you have "take" and "release" reversed?

and the author concedes

You are right, that should probably have been reversed.

So, yes, it seems the article got things mixed up a bit.

It probably works if you just switch these two methods.

However, in real life, the JDK has semaphores now in the concurrency utils package, and you should use those.

As for learning how things work, looking at the JDK source as a first step is probably a bit challenging (but very good reading after you have reached an initial understanding). Best to find a better article.

Upvotes: 3

user1907906
user1907906

Reputation:

Use java.util.concurrent.Semaphore.

A counting semaphore. Conceptually, a semaphore maintains a set of permits. Each acquire() blocks if necessary until a permit is available, and then takes it. Each release() adds a permit, potentially releasing a blocking acquirer. However, no actual permit objects are used; the Semaphore just keeps a count of the number available and acts accordingly.

Grep the code.

Upvotes: 1

Related Questions