Java- Binary Semaphore

2.Binary Semaphore(Mutex)

A semaphore initialized to one, and which is used such that it only has at most one permit available, can serve as a mutual exclusion lock. This is more commonly known as a binary semaphore, because it only has two states: one permit available, or zero permits available.

When used in this way, the binary semaphore has the property (unlike many Lock implementations), that the “lock” can be released by a thread other than the owner (as semaphores have no notion of ownership). This can be useful in some specialized contexts, such as deadlock recovery.

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.

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.

public class SemaphoreTest {

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

	static class MyLockerThread extends Thread {

 String name = "";

 MyLockerThread(String name) {
 	this.name = name;
 }

 public void run() {

 	try {

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

  semaphore.acquire();
  System.out.println(name + " : got the permit!");

  try {

  	for (int i = 1; i <= 5; i++) {
 System.out.println(name + " : is performing operation " + i 
    + ", available Semaphore permits : "
    + semaphore.availablePermits());
   // sleep 1 second
   Thread.sleep(1000);
  	}

  } 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());
  }

 	} catch (InterruptedException e) {
  e.printStackTrace();
 	}
 }

	}

	public static void main(String[] args) {

	System.out.println("Total available Semaphore permits : " + semaphore.availablePermits());

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

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

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

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

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

 MyLockerThread t6 = new MyLockerThread("F");
 t6.start();

	}
}