Showing posts with label Phaser. Show all posts
Showing posts with label Phaser. Show all posts

Sunday, April 13, 2014

Five Synchronizers in Java

Semaphore CountDownLatch CyclicBarrier Phaser Exchanger
You already understand the low-level concurrency constructs (such as the use of the synchronized keyword, Runnable interface, and Thread class for creating threads). In the case of a shared resource that needs to be accessed by multiple threads, access and modifications to the shared resource need to be protected.

When you use the synchronized keyword, you employ mutexes to synchronize between threads for safe shared access. Threads also often needed to coordinate their executions to complete a bigger higher-level task. The wait/ notify pattern is one way to coordinate the execution of multiple threads.

Using APIs for acquiring and releasing locks (using mutexes) or invoking the wait/notify methods on locks are low-level tasks. It is possible to build higher-level abstractions for thread synchronization. These high-level abstractions for synchronizing activities of two or more threads are known as synchronizers. Synchronizers internally make use of the existing low-level APIs for thread coordination.


Five classes help common special-purpose synchronization idioms.

  1. Semaphore is a classic concurrency tool.
    Semaphores are often used to restrict the number of threads than can access some (physical or logical) resource.
  2. CountDownLatch is a very simple yet very common utility for blocking until a given number of signals, events, or conditions hold.
    A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes
  3. A CyclicBarrier is a resettable multiway synchronization point useful in some styles of parallel programming.
    A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point. CyclicBarriers are useful in programs involving a fixed sized party of threads that must occasionally wait for each other. The barrier is called cyclic because it can be re-used after the waiting threads are released.
  4. A Phaser provides a more flexible form of barrier that may be used to control phased computation among multiple threads.
    A reusable synchronization barrier, similar in functionality to CyclicBarrier and CountDownLatch but supporting more flexible usage.
  5. An Exchanger allows two threads to exchange objects at a rendezvous point, and is useful in several pipeline designs.
    A synchronization point at which threads can pair and swap elements within pairs. Each thread presents some object on entry to the exchange method, matches with a partner thread, and receives its partner's object on return. An Exchanger may be viewed as a bidirectional form of a SynchronousQueue. Exchangers may be useful in applications such as genetic algorithms and pipeline designs.


If you know anyone who has started learning Java, why not help them out! Just share this post with them. 
Thanks for studying today!...

Friday, October 11, 2013

Phaser in Java 7 : Concurrency

To really understand what the Phaser class does and why it is useful and how it is different from CountDownLatch, Cyclic Barrier and what problem it is going to solve. Let have a short review of each synchronizers  in terms of 
  • Number of parties : Number of parties is another way of saying number of different threads
  • Reusable : It means you don't have to create a new instance of the barrier ( i.e, Countdownlatch  cyclic barrier, Phaser)  before reusing.
  • Advanceable : It means a thread can arrive and continue doing work without waiting for others threads or without waiting for all threads to complete

CountDownLatch
  • Fixed number of parties 
  • Not reusable as you have to create another CountDownLatch for each synchronize point
  • It is Advanceable as latch.countDown() do the advance and latch.await() do the waiting part
  • Fixed number of parties.
  • Reusable that how it differ from CountDownLatch but all threads must wait for each party to arrive at the barrier.
  • Not advanceable

Phaser
  • Dynamic number of parties
  • Reusable
  • Advanceable : phaser.arrive() that how it advance

Phaser is a useful feature when few independent threads have to work in phases to complete a task. So, a synchronization point is needed for the threads to work on a part of a task, wait for others to complete other part of the task, and do a sync-up before advancing to complete the next part of the task.

Before going for an example, have a look on how Phaser do the registration and Synchronization. There are also other step involved in Phaser such as Termination, Tiering and Monitoring, which we look later may after some time.

Registration : Unlike the case for other barriers, the number of parties registered to synchronize on a phaser may vary over time. Tasks may be registered at any time (using methods register(), bulkRegister(int), or forms of constructors establishing initial numbers of parties), and optionally deregistered upon any arrival (using arriveAndDeregister()).

Synchronization : Like a CyclicBarrier, a Phaser may be repeatedly awaited. Method arriveAndAwaitAdvance() has effect analogous to CyclicBarrier.await. Each generation of a phaser has an associated phase number.The phase number starts at zero, and advances when all parties arrive at the phaser, wrapping around to zero after reaching Integer.MAX_VALUE


Methods in Phaser class


Name
Description
Phaser(int numThreads)
Creates a Phaser object with a given number of threads (parties) to arrive to advance to the next stage; the initial phase is set to 0.
Int register()
Adds a new thread (party) to this Phaser object. Returns the phase current number. Throws an IllegalStateException if the maximum supported parties are already registered.
Int bulkRegister(int numThreads)
Adds numThreads of unarrived parties to this Phaser object. Returns the phase current number. Throws an IllegalStateException if maximum supported parties are already registered
Int arrive()
Arrives at this phase without waiting for other threads to arrive. Returns the arrival phase number. Can throw an IllegalStateException.
Int arriveAndDeregister()
Same as the previous method, but also deregisters from the Phaser object.
Int arriveAndAwaitAdvance()
Arrive at this phase and waits (i.e., blocks) until other threads arrive
Int awaitAdvance(int phase)
Waits (i.e., blocks) until this Phaser object advances to the given phase value.
Int getRegisteredParties()
Returns the number of threads (parties) registered with this Phaser object.
Int getArrivedParties()
Returns the number of threads (parties) arrived at the current phase of the Phaser object
Int getUnarrivedParties()
Returns the number of threads (parties) that have not arrived when compared to the registered parties at the current phase of the Phaser object



Example

Let take an example of processing a delivery order in coffee shop. Assume there are 3 workers: a cook, a waiter, an attendent. To simlify this problem assume each delivery of order consist of 3 food items. Completing a delivery order consists of preparing the three orders one after another. To complete preparing a food item, all three workers—the cook, the helper, and the attendant—should do their part of the work.










Sample Output
Starting to process the order.
cook  doing this work for order 1
attendent  doing this work for order 1
waiter  doing this work for order 1
order 1 completed
attendent  doing this work for order 2
cook  doing this work for order 2
waiter  doing this work for order 2
order 2 completed
attendent  doing this work for order 3
cook  doing this work for order 3
waiter  doing this work for order 3
order 3 completed
Process completed



If you know anyone who has started learning Java, why not help them out! Just share this post with them. Thanks for studying today!...