nawazish-stackoverflow
nawazish-stackoverflow

Reputation: 283

Unexpected behavior of java.concurrent.Semaphore

I am in a situation where I need to use Semaphore from the java.concurrent package so that I may be able to restrict the number of threads taking hold of a certain resource. Following is the very basic setup (code):

    package semaphor;

    import java.util.concurrent.Semaphore;

    /**
     * Created by NawazishMohammad on 15-04-2015.
     */
    public class SemaphoreTester {
       public static void main (String [] args){
           new Thread(new MyRunnable(), "T1").start();
           new Thread(new MyRunnable(), "T2").start();
           new Thread(new MyRunnable(), "T3").start();
           new Thread(new MyRunnable(), "T4").start();
       }
    }

    class MyRunnable implements Runnable{

        @Override
        public void run() {
            semaphoreStatus();
        }

        public void semaphoreStatus(){
            System.out.println("Thread waiting for permit: "+Thread.currentThread().getName());
            Semaphore sem = new Semaphore(2);
            try {
                sem.acquire();
                System.out.println("Thread got permit: " + Thread.currentThread().getName());
                System.out.println("Thread releasing permit: "+Thread.currentThread().getName());
                sem.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }


        }

}

I am getting the following output

Thread waiting for permit: T1
Thread waiting for permit: T2
Thread waiting for permit: T3
Thread waiting for permit: T4
Thread got permit: T3
Thread got permit: T4
Thread got permit: T2
Thread got permit: T1
Thread releasing permit: T2
Thread releasing permit: T4
Thread releasing permit: T3
Thread releasing permit: T1

Note that although I have instantiated Semaphore for total concurrent thread count of two "new Semaphore(2);", implying that at a time only 2 threads can have access to a particular resource, I can find all 4 threads: T1-T4 having acquired Semaphore permit (and hence access to the restricted resource). Could anyone please clarify my misunderstanding, if any, about java.concurrent.Semaphore since I do not expect the output:

Thread got permit: T3
Thread got permit: T4
Thread got permit: T2
Thread got permit: T1 

I understand that Semaphore, at any instance, cannot tender more than "2" permits (for this example) to any number of threads that might be waiting.

Upvotes: 2

Views: 97

Answers (1)

esaj
esaj

Reputation: 16035

You are creating a new semaphore in each thread, meaning that each thread will see a different Semaphore. Instead of calling Semaphore sem = new Semaphore(2); inside semaphoreStatus(), you should construct the Semaphore outside of the threads and then share it with them.

Upvotes: 6

Related Questions