Java Threads — Semaphores & Mutex

Waqas Memon
2 min readApr 12, 2018

--

Semaphores in java are like Monitors and locks that provide mutual exclusivity to multiple threads and make threads wait on certain condition to be true.

Semaphores start with a permit counter, which works as number of threads allowed to access a synchronized resource. Every time a thread acquires a semaphore, it decrements permit counter by 1, and it increments permit counter by 1 when a thread releases a semaphore.

A Mutex theoretically is same as Semaphore, but it only allows 1 permit or 1 thread to access the synchronized resource at a time.

java.util.concurrent.Semaphore

It has two constructors, and both are important if you want to maintain certain order.

public Semaphore(int permits);
public Semaphore(int permits, boolean fair);
  1. Permits: Number of threads allowed to acquire locks (access to synch. block). With permits only, and no fair policy, you actually tell Semaphore to give access to any thread in any order.
  2. Fair: true value here makes sure that access is given in the order in which a thread requests access and is waiting in queue.

Let’s understand semaphores with following code snippet which starts two threads, both threads trying to access one object synchronously, i.e. counter and each thread incrementing counter by 1 such that, one thread only prints odd numbers and other thread only prints even numbers.
In this example, our
Semaphore is same as a Mutex.
[there are many ways to achieve same output, but thats a different topic, i.e.
Using wait() and notify()]

public class NumberPrinterSemaphores {
static int counter = 0;
static Semaphore semaphore = new Semaphore(1, true);
static class OddEvenNumberPrinterThread implements Runnable{
@Override
public void run() {
while (counter<9){
try {
synchronized(this){
semaphore.acquire();
counter++;
String tName = Thread.currentThread().getName();
System.out.println(tName + " --> "+ counter);
semaphore.release();
}
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
public static void main(String[] args) throws Exception{ Thread t1 = new Thread(new OddEvenNumberPrinterThread());
Thread t2 = new Thread(new OddEvenNumberPrinterThread());
t1.start();
t2.start();

}
}

Output

Thread-0 --> 1
Thread-1 --> 2
Thread-0 --> 3
Thread-1 --> 4
Thread-0 --> 5
Thread-1 --> 6
Thread-0 --> 7
Thread-1 --> 8
Thread-0 --> 9
Thread-1 --> 10

--

--