Tuesday, July 30

Semaphore in java concurrency package

What is Semaphore?

Let us understand simple concept of semaphore with an real time practical example .

Everyone at some point of time would have worked on database connection pool. In connection pool we maintain maximum number of connections allowed. So how do we control that. 

Let's say maximum number of allowed connection for a database is 10 and If 10 connection exhaust next thread will have to wait until one of the connection gets released. 

Semaphore provides a very simple way to implement this . 

Semaphore is nothing but a way of code synchronization with a specific counter. 

Let's understand this with a code snippet 

Public class ConnectionManager {

Semaphore sem =new Semaphore(10);

    public Connection getConnection(){
                 sem.acquire();
                 useConnection();
                 sem.release();
           }

    public void useConnection(){
          }



Through semaphone we maintain the counter limit for connection as 10. Any thread that needs database connection will invoke getConnection() method . 
When sem.acquire() is invoked sem counter is decreased by one . Everytime sem.acquire() method is invoked sem counter is decreased by one. So every thread that will invoke getConnection() method will decrease the sem counter by one.

When counter reaches 0 , sem.acquire() returns false and connection can not be obtained as maximum limit of allowed connection is already reached. 

Now every time sem.release() method is invoked sem counter is increased by one . This means it makes the connection available for reuse . So Client may continue trying to acquire the connection and may succeed if sem counter value become greater than 0

So semaphore helps in managing the maximum no of permits through a counter . Its value changes with critical area access acquire and release. 

That's how semaphore works. It just a better and clean way (with much lesser lines of code) to implement synchronization for situations where a counter based implementation can be useful.


No comments:

Post a Comment