Java Interview : Multithreading Part Three

Part three of Java Interview : Multi-threading
Java 1.5 onwards a lot of useful utility classes tailor made to counter a lot of specific scenarios were introduced, i will write about some of the commonly used ones.
Classes like Semaphore, CountDownLatch, CyclicBarrier, Phaser, Exchanger and the Executor Framework are the most famous ones.
Semaphore class is modeled around the concept of the counting semaphore, where a set of permits are maintained. We have the acquire() method which tries to get a permit and blocks until it gets one. The release() method puts the permit back to the pool, here by increasing the permit count. Methods like tryAcquire() provide non-blocking alternative to get the lock. Binary semaphores have only one permit and thus a thread can either be in one state on or off at a single time.
CountDownLatch is a utility that provides methods like await(), basically signalling the threads to wait at a point till the count comes down to 0, before proceeding through a point of execution. So if you initialise a countdownlatch with 3, three threads need to reach a point in execution call countDown() to bring the counter to 0 and then proceed through the await() method.
Similar to the CountDownLatch, we have the CyclicBarrier class which awaits for the threads too, but comes with the added feature of resetting the counter and causing a BarrierBroken Exception. Also it comes with an overloaded constructor which takes a Runnable reference, which runs once the counter has been brought down to Zero.
Phaser class, as by the intuitively given name is useful for dynamically registering parties and synchronizing the threads at specific points so that operations are completed in phases. Generally this is a useful class when the functionality achieves the target in phased manner.
Exchanger is a synchronization utility which is a point at which threads can pair and swap elements within pairs.So in simple terms 2 threads come to this point and exchange their data with one another.


Comments

Popular posts from this blog

Java Interview : Threads

Spring Framework Interview Notes : Part Two Wiring

Card Dealer In Java in Less than 5 minutes