Skip to main content

Semaphore in java

Semaphore is a thread synchronization mechanism that can be used -

  • To send signals between threads
  • To guard a critical section for enforcing limited access to the resource
Semaphore in java come with java 1.5 and available under package "java.util.concurrent" 

Below is an example which you can go through to understand how we can enforce a limited number of thread to access a particular section of code at a time.


import java.util.concurrent.Semaphore;

public class SemaphoreExample {
Semaphore semaphore = new Semaphore(2);

private void printLock() {
try {
semaphore.acquire();
System.out.println("Lock acquired by "+Thread.currentThread().getName());
System.out.println("Locks remaining "+semaphore.availablePermits());
Thread.sleep(5000);
} catch (InterruptedException ie) {
ie.printStackTrace();
} finally {
semaphore.release();
System.out.println("Locks release "+Thread.currentThread().getName());
}
}

public static void main(String[] args) {
final SemaphoreExample semaphoreExample = new SemaphoreExample();
Runnable task = () -> semaphoreExample.printLock();
Thread t1 = new Thread(task,"t1");
Thread t2 = new Thread(task,"t1");
Thread t3 = new Thread(task,"t1");
}

}


At a time the semaphore will allow 2 thread and wait to another till it is released.

Thus you can use this to ensure the access of your costly resource by limited number of thread at once.



Comments

Popular posts from this blog

StackOverFlowError and OutOfMemoryError in java

There are two area inside java virtual machine's memory the heap and the  stack . The  stack  memory is used to store local variables and function call while heap memory is used to store objects in  Java The most common cause of StackOverFlowError is too deep or infinite recursion or many local objects / variables creation inside function call in  Java.  According to the java source documentation,  Java throws  java.lang.StackOverflowError   when a stack overflow occurs because an application recurses too deeply. JVM has a given memory allocation for each stack of each thread, and if an attempt to call a method happens to fill this memory, JVM throws an error. Just like it would do if we try to write at index N of an array of length N.  The point to be noted here is that - These are errors not an exceptions. No memory corruption happens due to the error. Stack can not write into the heap space. A StackOverflowError i...

Job Sequencing with Deadlines

Given a set of n jobs Each job i has an integer deadlines di>=0 and a profit pi>0 All jobs requires only one unit time to complete Only one machine is available for processing jobs For job i the profit pi is earned if the job is completed by its deadline.