How to allow multiple threads concurrently access the shared data?

Semaphore

  1. It maintains the no. of permits to access the shared resource. If the no. of permits are 2, then 2 threads can access the shared resource simultaneously without getting blocked.
  2. A thread which needs access to the shared resource must acquire a permit by calling acquire()
  3. If the no. of permits are exhausted, then the thread gets blocked until one of the permits is released by another thread
  4. permit can be released by calling the release() method.


In this example, at any given pt of time, only 2 threads can access the shared thread simultaneously


public class SemaphoreExample {

    Semaphore semaphore = new Semaphore(2);

    public static void main(String[] args) {
        SemaphoreExample semaphoreInstance = new SemaphoreExample();

        new Thread(()->{
            semaphoreInstance.mutualExclusion();
        }, "THREAD-1").start();
        new Thread(()->{
            semaphoreInstance.mutualExclusion();
        }, "THREAD-2").start();
        new Thread(()->{
            semaphoreInstance.mutualExclusion();
        }, "THREAD-3").start();
        new Thread(()->{
            semaphoreInstance.mutualExclusion();
        }, "THREAD-4").start();
    }

    private void mutualExclusion(){
        try{
            semaphore.acquire();
            System.out.println(Thread.currentThread().getName()+" accessing shared resource");
            Thread.sleep(1000);
        }catch(InterruptedException e){
            e.printStackTrace();
        }finally {
            semaphore.release();
            System.out.println(Thread.currentThread().getName()+" released shared resource");
        }
    }
}

Output
THREAD-3 accessing shared resource
THREAD-1 accessing shared resource
THREAD-3 released shared resource
THREAD-4 accessing shared resource
THREAD-1 released shared resource
THREAD-2 accessing shared resource
THREAD-2 released shared resource
THREAD-4 released shared resource

Comments

Popular posts from this blog

Distributed database design using CAP theorem

SQL Analytical Functions - Partition by (to split resultset into groups)

Easy approach to work with files in Java - Java NIO(New input output)