4
class Semaphore {
   private int count=100;
   public Semaphore(int n) {
      this.count = n;
   }

   public synchronized void acquire() {
      while(count == 0) {
         try {
            wait();
         } catch (InterruptedException e) {
            //keep trying
         }
      }
      count--;
   }

   public synchronized void release() {
      count++;
      notify(); //alert a thread that's blocking on this semaphore
   }
}

Currently I am supporting 100 users. If a request comes from the jsp (Client) and goes through this class, will the Thread (the request from JSP ) wait and notify automatically?

dcn
  • 4,389
  • 2
  • 30
  • 39
Pawan
  • 31,545
  • 102
  • 256
  • 434

2 Answers2

6

I would highly recommend using the java.util.concurrent.Semaphore from the standard library instead of writing a custom Semaphore implementation. Only to mention one reason why this generally is a better idea: notify does not give any FIFO guarantees (from Object.notify()):

The choice is arbitrary and occurs at the discretion of the implementation

dcn
  • 4,389
  • 2
  • 30
  • 39
1

You do not have to write a semaphore yourself.

Take a look at the Java 6 documentation for Semaphore. and this tutorial from Thomas Darimont.

Omnaest
  • 3,096
  • 1
  • 19
  • 18