Java Thread – Mutex and Semaphore example

Java multi threads example to show you how to use Semaphore and Mutex to limit the number of threads to access resources.
  1. Semaphores – Restrict the number of threads that can access a resource. Example, limit max 10 connections to access a file simultaneously.
  2. Mutex – Only one thread to access a resource at once. Example, when a client is accessing a file, no one else should have access the same file at the same time.

1. Semaphore

Consider an ATM cubicle with 4 ATMs, Semaphore can make sure only 4 people can access simultaneously.




import java.util.concurrent.Semaphore;
import java.util.stream.IntStream;

/**
 * 
 * @author Amila Silva
 *
 */
public class SemaphorTest {

 // max 4 people
 static Semaphore semaphore = new Semaphore(4);

 static class ATMThread extends Thread {

  String name = "";

  public ATMThread(String name) {
   this.name = name;
  }

  public void run() {

   try {
    System.out.println(name + " acquiring lock...");
    System.out.println(name + " available semaphors  permit now: "
      + semaphore.availablePermits());

    semaphore.acquire();

    System.out.println(name + " Got the permit!");

    IntStream.range(1, 5).forEach(
      i -> {
       System.out.println(name
         + " : is performing operation " + i
         + ", available Semaphore permits : "
         + semaphore.availablePermits()
         + " Thread id: " + this.getId());

       // sleep 1 second
       try {
        Thread.sleep(5000);
       } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
       }

      });

   } catch (Exception e) {
    e.printStackTrace();
   } finally {
    // calling release() after a successful acquire()
    System.out.println(name + " : releasing lock...");

    semaphore.release();
    System.out.println(name
      + " : available Semaphore permits now: "
      + semaphore.availablePermits());

   }
  }
 }

 /**
  * @param args
  */
 public static void main(String[] args) {
  System.out.println("Total available Semaphore permits : "
    + semaphore.availablePermits());

  ATMThread t1 = new ATMThread("A");
  t1.start();

  ATMThread t2 = new ATMThread("B");
  t2.start();

  ATMThread t3 = new ATMThread("C");
  t3.start();

  ATMThread t4 = new ATMThread("D");
  t4.start();

  ATMThread t5 = new ATMThread("E");
  t5.start();

  ATMThread t6 = new ATMThread("F");
  t6.start();
  
  ATMThread t7 = new ATMThread("F");
  t7.start();

 }
}



Observe the output carefully, you will see that there are maximum 4 people (C, B, F, D) to perform an operation at a time, the people A and E are waiting. As soon as one of them release the lock (D and F), A and E will acquire it and resumes immediately.


2. Mutex

Mutex is the Semaphore with an access count of 1. Consider a situation of using lockers in the bank. Usually the rule is that only one person is allowed to enter the locker room.


As it can be seen, only one thread executes at a time here. This is the role of a Mutex.

References

https://www.mkyong.com/java/java-thread-mutex-and-semaphore-example/






Comments

Appsinvo said…
Appsinvo is the Top Mobile App Development Company. With the help of our team passion and hard work we have come a long way and many milestones are still to achieve in the coming days. We serve clients ranging from startups, SMEs to large enterprises.
Top Mobile App Development Company in Qatar

Popular posts from this blog

PostgreSQL bytea and oid

MySQL as Hive metadata store

Microservices Architecture with Spring Boot in 15mins