Five advanced Java Synchronizers you probably don’t know

 

Besides the common synchronize which is based in the lock bit that every Java object has, you have more sophisticated synchronizers in java, such as:

  • Semaphore – Use the concept of a permit to indicate a max number of allowed threads in a place. When you use the value 1, the behavior its similar to synchronize, also called binary semaphore. There is however a big difference here, you acquire a permit on the semaphore, not a locking object, its just a variable to count when a thread acquires a permit and when a thread releases a permit, some kind of a counter. The only thing you really have are threads locking until a permit be available. In the example below, we define 3 as the number of permits, so after 3 acquires the 4 thread will wait for a release before continue its execution.

    • CountDownLatch – Initialize this class with a number (to countdown), and when reaches 0 the thread waiting unblocks and follows its way. (After the await the latch cannot be reused)

 

 

 

  • CyclicBarrier  – This class behaves somehow as the inverse of the CountDownLatch. After N await() the threads blocked can follow their way. (A CyclicBarrier can be reused)

 

  • Phaser – Very complex synchronizer, a mix of CountDownLatch and CyclicBarrier, with lots of customized options. If you need a behavior similar to 2 previous synchronizers but they were not enough you want to deep into this one. It behaves like a CyclicBarrier but you can register a set of threads and at any time deregister, achieving a level of customization not possible with the other synchronizers. Think about the need to wait for threads to arrive before you can continue or start another set of tasks. More information about this at Oracle website:

http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Phaser.html

 

  • Exchanger – The best explanation comes from Oracle doc itself: “A synchronization point at which threads can pair and swap elements within pairs”. One thread wants to send information to other thread and blocks awaiting to send the data, and in EXCHANGE receives what the other thread wants to send too! This behavior happens to both sides!

 

photo credit: My Buffo via photopin cc

3 Comments

  1. Tim says:

    Seems like a decent intro to these classes and how they work. But a much more interesting topic to cover would be WHY you would use these. What are some example use cases where wait & notify just aren’t sufficient, and these classes are more practical?

  2. josedacruz says:

    I will in the future. Thanks for the comment.

  3. Igal says:

    Very good explanations, I very enjoyed your English.

Leave a Reply

Your email address will not be published. Required fields are marked *

Bad Behavior has blocked 154 access attempts in the last 7 days.

Hyper Smash