Threads

Examples on Threads, Concurrencies

BlockingQueue

BlockingQueue is a thread-safe queue where we can enqueue on one end of queue, and dequeue on another end of queue., All BlockingQueue implementions on array or linked queues are thread-safe implementations. Below is a simple usage of BlockingQueue.

Output:

BlockingDeque

BlockingDeque is an extended implementation of queue where we can enqueue or dequeue on both ends of the queue. All BlockingDeque implementions on array or linked queues are thread-safe implementations. Below is a simple usage of BlockingDeque

Output:

CountdownLatch

CountDownLatch is another concurrency class, in which makes one thread wait for other until it reaches the threshold limit mentioned.Reach for the threshold limit, is counted by calling countdown() method present in CountDownLatch class.Every time countdown() method is called, the count is decremented by 1, finally when arrives at zero, the awaiting will stop. Assume …

CountdownLatch Read More »

ForkJoinPool

ForkJoinPool is the core of the concurrency frameworks which follows divide and conquer approach in completing the tasks. Fork – Recursively break the single task into multiple smaller tasks till the threshold. Join – Join the multiple smaller tasks results and produce the output recursively. Initialise the maximum number of worker threads.

RecursiveAction class …

ForkJoinPool Read More »

Reentrant Lock

The ReentrantLock class is an implementation of Lock Interface, which will lock() the execution block for the thread which calls it.Until the locked thread calls the lock.unlock() method, the code block in between will not be available to other Threads…even when it is idle or sleeping or taking long time.Hence the block after lock.lock() is …

Reentrant Lock Read More »

Cyclic Barrier

Assume a the conference call will be opened when 4 users join., Assume until all the users join, that conference call wont be opened even when the less than 4 users join. Below example is a simple illustration of the scenario using Cyclic Barrier.

 Result:

Semaphore

A semaphore maintains a fixed number of threads in executions if exceeds lock can be acquired for that semaphore thread. Below method will get the lock of semaphore within semaphore.availablePermits()

If there are more that fixed threads, it will wait to acquire/get the semaphore lock until it has semaphore.availablepermits() greater than ‘0’.A semaphore initialised to …

Semaphore Read More »