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

Optimal Binary Search using Dynamic Programming

An optimal binary search tree is a binary search tree for which the nodes are arranged on levels such that the tree cost is minimum. If the probabilities of searching for elements of a set are known from accumulated data from past searches, then Binary Search Tree (BST) should be such that the average number of comparisons in a search should be minimum. eg. Lets the elements to be searched are A, B, C, D and probabilities of searching these items are 0.1, 0.2, 0.4 and 0.3 respectively. Lets consider 2 out of 14 possible BST containing these keys. Figure 1 Figure 2 Average number of comparison is calculated as sum of level*probability(key element) for each element of the tree. Lets the level of tree start from 1. Therefore, for figure 1 -     Average number of comparison = 1*0.1 +2*0.2 +3*0.4 +4*0.3  = 2.9                                  ...

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.

Knapsack Problem and Solution using Dynamic Programming

The knapsack problem or rucksack problem is a problem in combinatorial optimization: Given a set of items, each with a weight and a value, determine the number of each item to include in a collection so that the total weight is less than or equal to a given limit and the total value is as large as possible Given a knapsack of capacity m and number of items n of weight w1, w2, w3 ... , wn with profits p1, p2, p3..., pn. Let x1,x2,...,xn is an array that represents the items has been selected or not. If the item i is selected, then xi = 1 If the item i is not selected then x i = 0 In 0/1 knapsack, the item can be selected or completely rejected. The items are not allowed to be broken into smaller parts. The main objective is to place the items into the knapsack so that maximum profit is obtained or find the most valuable subset of items that fits into the knapsack. Constraints: The weight of the items chosen should not exceed the capacity of knapsack. Obj...