Posts

Showing posts with the label Concurrency

Exchanger

Exchanger  is a thread-synchronization construct that lets a pair of threads exchange data items. An exchanger is similar to a cyclic barrier whose count is set to 2 but also supports exchange of data when both threads reach the barrier. Exchanger can be handy in solving Producer Consumer pattern where Producer and consumer threads can exchange their data. The java.util.concurrent.Exchanger<V> class implements an exchanger. This class provides an Exchanger() constructor for initializing an exchanger that describes an exchange point and a pair of exchange() methods for performing an exchange. Exchanger has 2 method exchange (V x )  and  V exchange(V x, long timeout, TimeUnit unit) . exchange() method enables two threads to exchange their data between each other in java. If current thread is first one to call exchange() method then it will until one of following things happen: Some other thread calls exchange() method in java, or Some other thread inter...

CountDownLatch

Countdown latch is a thread-synchronization construct that causes one or more threads to wait until a set of operations being performed by other threads finishes. It consists of a count and "cause a thread to wait until the count reaches zero" and "decrement the count" operations. The java.util.concurrent.CountDownLatch class implements a countdown latch. Its CountDownLatch(int count) constructor initializes the countdown latch to the specified count. A thread invokes the void await() method to wait until the count has reached zero (or the thread has been interrupted). Subsequent calls to await() for a zero count return immediately. A thread calls void countDown() to decrement the count. Working using CountDownLatch The await() methods block the current threads until the count reaches 0 due to invocations of the countDown() method by some other thread, after which blocked threads are released. Lets see an example to make the concept more clear : In our ...

Cyclic Barrier

There might be situation where we might have to trigger event only when one or more threads completes certain operation.A cyclic barrier is a thread-synchronization construct that lets a set of threads wait for each other to reach a common barrier point. The barrier is called cyclic because it can be re-used after the waiting threads are released. CyclicBarrier has 2 Constructor : CyclicBarrier(int parties): New CyclicBarrier is created where parties number of thread wait for each other to reach common barrier point, when all threads have reached common barrier point, parties number of waiting threads are released. CyclicBarrier(int parties, Runnable barrierAction): New CyclicBarrier is created where parties number of thread wait for each other to reach common barrier point, when all threads have reached common barrier point, parties number of waiting threads are released and barrierAction (event) is triggered. Either constructor throws java.lang. IllegalArgumentException wh...

Semaphores

Semaphore is a java thread synchronization construct which is used to guard the shared resources by using permits . These permits are sort of counters, which allow access to the shared resource. Thus, to access the resource, a thread must be granted a permit from the semaphore. Each call to the Semaphore's void acquire() method takes one of the available permits or blocks the calling thread when one isn't available. Each call to Semaphore's void release() method returns an available permit, potentially releasing a blocking acquirer thread. Semaphores whose current values can be incremented past 1 are known as counting semaphores , whereas semaphores whose current values can be only 0 or 1 are known as binary semaphores or mutexes . In either case, the current value cannot be negative. Semaphore Constructor : Semaphore(int permit) : where permits is the initial number of permits available.permits is number of threads that can access shared resource at a time. ...

Java Concurrency Utilities : Custom Implementation

Blocking Queue Before implementing , one must know what BlockingQueue is :  Java BlockingQueue interface in the java.util.concurrent package represents a queue which is thread safe to put into, and take instances from.  BlockingQueue is typically used to have on thread produce objects, which another thread consumes. Implementation : public class CustomBlockingQueue { private List queue = new LinkedList(); private int limit = 10; public CustomBlockingQueue(int limit){ this.limit = limit; } public synchronized void enqueue(Object item) throws InterruptedException { while(this.queue.size() == this.limit) { wait(); } notifyAll(); this.queue.add(item); } public synchronized Object dequeue() throws InterruptedException{ while(this.queue.size() == 0){ wait(); } notifyAll(); return this.queue.remove(0); } } Explan...

BlockingQueue

Image
The Java BlockingQueue interface in the java.util.concurrent package represents a queue which is thread safe to put into, and take instances from.  BlockingQueue is typically used to have on thread produce objects, which another thread consumes. Below is the diagram of blockingqueue. The producing thread will keep producing new objects and insert them into the queue, until the queue reaches some upper bound on what it can contain. It's limit, in other words. If the blocking queue reaches its upper limit, the producing thread is blocked while trying to insert the new object. It remains blocked until a consuming thread takes an object out of the queue. The consuming thread keeps taking objects out of the blocking queue, and processes them. If the consuming thread tries to take an object out of an empty queue, the consuming thread is blocked until a producing thread puts an object into the queue. Different methods provided in BlockingQueue API : remove(Object )...

Executor and Executor Service Framework

In Java , a task is a unit of work. To accomplish the work done we need to create a new Thread every time.  There is a performance overhead associated with starting a new thread, and each thread is also allocated some memory for its stack etc. In low level Java threading , we have to follow  task execution policy , in which the thread to which task has been submitted will only execute the task. How does Executor Framework come over the task execution policy and improve performance ? Executor framework provides a way to decouple the task execution policy stages from submition and execution . Instead of starting a new thread for every task to execute concurrently, the task can be passed to a thread pool . As soon as the pool has any idle threads the task is assigned to one of them and executed. Internally the tasks are inserted into a Blocking Queue which the threads in the pool are dequeuing from. When a new task is inserted into the queue one of the idle threads w...