views:

33

answers:

1

Next is a simple semaphore implementation.

public class Semaphore {
  private boolean signal = false;

  public synchronized void take() {
   this.signal = true;
   this.notify();
  }

  public synchronized void release() throws InterruptedException {
   while (!this.signal) wait();
   this.signal = false;
  }
 }

Is it true, that by calling take() semaphore imitates signal acquisition and wakes up randomly chosen thread (if it actually exists) and by calling release(), if signal was not acquired, semaphore forces current(triggering) thread to wait for a notify() but sets signal acquisition to false?

And does it mean that, if I have single semaphore for 3 threads, I will have to run take() - release() pair for each thread in the part of code, which is not thread safe?

A: 

Yes, as written, take() will wake a randomly chosen thread from those blocked in release(), and release() will wait for a take() call if signal is false on entry. This suggests that you have the names take() and release() backwards: take() should be the blocking call.

This is a binary semaphore as it only has two states. If you use it like a mutex then you will need a take() - release() pair wrapping the code that needs to be isolated. However, in that case you are better off with a plain mutex.

Semaphores have many uses (see the "Little Book of Semaphores"), but are generally harder to use correctly than mutexes and monitors/condition variables.

Anthony Williams
Used mutex. Thanks for advice!
den-javamaniac