X
    Categories: Java Core

Java Mutex Example

Let’s give an example first before going deeper into what Mutex is:

Think of a queue. Doesn’t matter short or long. Now think of a truck that is selling tickets for an amusement park. One person at a time can buy a ticket. When the person has bought the ticket, it is time for the next person in the queue.

How is this little story related to understanding Mutex though? Let me explain.

Mutex allows each thread to have 1 permit. Or in other words, only 1 thread can access the resources at a time. In the analogy above, 2 people cannot buy tickets at the same time. The same thing with Mutex. Only instead of people, it is threads and instead of ticket it is a permit. Same thing more or less..

Mutex is slightly different than Semaphore such that Semaphore allows multiple threads to access resources. Meaning, multiple people can buy tickets at the same time.

Constructors

  1. public Semaphore(int permits);
  2. public Semaphore(int permits, boolean fair);

The first constructor is where we actually can differentiate between Mutex and Semaphore. If we have 1 as a parameter there, that means that only 1 thread will be allowed to acquire locks. Keep in mind that since it doesn’t take the second parameter which is the boolean fair, you are making the Semaphore class give access to any thread in any order.

The second constructor if passed true (fair), makes sure that access is given in the order in which a thread requests access and is waitining in a queue.



Mutex basic code implementation

import java.util.concurrent.Semaphore;

public class MutexDemo {
    
    // create a Semaphore instance that makes it so only 1 thread can access resource at a time
    private static Semaphore mutex = new Semaphore(1);

    static class ThreadDemo extends Thread {

		private String name = "";
	
		public ThreadDemo(String name) {
		    this.name = name;
		}
	
		@Override
		public void run() {
		    try {
                                // check the above mentioned analogy in the article for reference
				System.out.println("How many people can buy a ticket at a time: " + mutex.availablePermits());
				System.out.println(name + " is buying a ticket..."); 
				mutex.acquire();
				try {
					Thread.sleep(1000);
					
					System.out.println(name + " is still buying a ticket. How many people can still buy the ticket alongside him: " + mutex.availablePermits());
				} finally {
					mutex.release();
					System.out.println(name + " bought the ticket.");
					System.out.println("How many people can buy tickets after " + name + " has finished buying the ticket: " + mutex.availablePermits());
				}
		    } catch (Exception e) {
		    	e.printStackTrace();
		    }
		}
    }

    public static void main(String[] args) {

	ThreadDemo thread1 = new ThreadDemo("Bob");
	thread1.start();

	ThreadDemo thread2 = new ThreadDemo("Charlie");
	thread2.start();

	ThreadDemo thread3 = new ThreadDemo("Christie");
	thread3.start();

    }
}

Output

How many people can buy a ticket at a time: 1
Bob is buying a ticket...
How many people can buy a ticket at a time: 0
Charlie is buying a ticket...
How many people can buy a ticket at a time: 0
Christie is buying a ticket...
Bob is still buying a ticket. How many people can still buy the ticket alongside him: 0
Bob bought the ticket.
How many people can buy tickets after Bob has finished buying the ticket: 1
Charlie is still buying a ticket. How many people can still buy the ticket alongside him: 0
Charlie bought the ticket.
How many people can buy tickets after Charlie has finished buying the ticket: 1
Christie is still buying a ticket. How many people can still buy the ticket alongside him: 0
Christie bought the ticket.
How many people can buy tickets after Christie has finished buying the ticket: 1

As you can see from the output, while someone is buying the ticket, nobody else can. This is one of the lines that shows that:

Bob is still buying a ticket. How many people can still buy the ticket alongside him: 0

However, after he “bought” the ticket, straight after that, the other person buys the ticket.

In the end of the day, it comes to acquire() and release(). acquire() is when the person started “buying the ticket” and release() is when the person “bought the ticket”.

4.5 2 votes
Article Rating
ym_coding:
Related Post