Java synchronizers


Published on

An elimentary thought on java synchronizer primitives.

  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Java synchronizers

  1. 1.
  2. 2.  Available synchronizers What is synchronizing Basic nuts and bolts(in java) Various synchronizers Examples
  3. 3.  ReentrantLock (lock, unlock) Condition (await and signal) Semaphore (acquire permits and release) Future (get -<will block initially and auto release once isDone>) CyclicBarrier (await – block until a number later auto release) CountDownLatch (await and countDown)What is the similarity in all of these ???
  4. 4.  Similarity  For eg: lock, acquire, get, await almost mean threads are about to block on a condition  Auto release, release, unlock almost mean a thread is about to be un-blocked. Difference  Some synchronizers work with a shared mode (semaphore) and others work on per thread basis (lock)  Each synchronizer has a separate state/trigger on which block and unblock occurs!
  5. 5.  Acquire and release shared resource on condition Atomically Managing state Acquire while (synchronization state does not allow acquire) { enqueue current thread if not already queued; possibly block current thread; Means to block and un block threads } dequeue current thread if it was queued; Means to queue Release and de-queue update synchronization state; threads if (state may permit a blocked thread to acquire) unblock one or more queued threads;
  6. 6.  Features  Blocking and non-blocking wait  Interruptible wait.  Timed wait  Shared acquires and releases  Exclusive acquire and release  Fair and unfair notification Means (Basic components needed)  Atomically manage state  Enqueue and de-queue threads  Means to block and un-block
  7. 7.  Atomicallymanaged : Use a hardware primitive called compareAndSetState(expected, new)  If the actual value==expected, then assign new value; else spin. Means to block and unblock:  LockSupport.park() and LockSupport.unpark() Enque and de-queue  Non blocked data structures to efficiently manage threads into and out-of the queue.
  8. 8.  So we need some sort of skeletal framework which can take care some basic features using the components Here comes AbstractQueuedSynchronizer [AQS] class which encapsulates the gory details and provides some common functions related to acquire and release However it also allows to override some methods to acquire/release on special conditions.. (advanced features)
  9. 9.  Yes, All the synchronizers actually adapt a specialized version of AQS as an inner class called as Sync. (A beautiful example for Inner classes) Synchronizer’s various methods will ultimately map/call to one Sync class calls. AQS methods are overriden for different purposes  Different state to atomically managed  Fair, unfair policies etc.
  10. 10.  tryAcquire tryRelease trySharedAcquire tryReleaseShared
  11. 11. First extend templateclass Mutex { public static void main(String[] args) { class Sync extends final Mutex mutex = new Mutex(); AbstractQueuedSynchronizer { Runnable r1 = new Runnable() { private static final long serialVersionUID = public void run() { 1L; mutex.lock(); try {System.out.println("r1"); public boolean tryAcquire(int permits) { Thread.sleep(5000); return compareAndSetState(0, 1); } catch (InterruptedException e) { } e.printStackTrace(); } finally { mutex.unlock();; } public boolean tryRelease(int permits) { } setState(0); }; return true; Runnable r2 = new Runnable() { } public void run() { } mutex.lock(); try { System.out.println("r2"); Next, private final Sync sync = new Sync(); Thread.sleep(100); Adapter } catch (InterruptedException e) {e.printStackTrace(); public void lock() { } finally { mutex.unlock(); } sync.acquire(0); } } }; new Thread(r1).start();
  12. 12. A classic primitive that constitutes the method for restricting access to shared resources Imagine waiting on the yellow line at Immigration check counters (how haplessly u crib as u are eager to be called by some one) Imagine bank tellers Some may be fair (throughput is less) and others may be unfair!! But throughput is more
  13. 13.  Semaphores can be seen as permit holders  . Create with initial number of permits  . acquire takes a permit, waiting if necessary  . release adds a permit  . But no actual permits change hands.  . Semaphore just maintains the current count. Canuse for both “locking” and “synchronizing”  . With initial permits=1, can serve as a lock  . Useful in buffers, resource controllers  . Use in designs prone to missed signals  . Semaphores “remember” past signals
  14. 14. class ResourcePool { FairSemaphore available =new FairSemaphore(N); Object[] items = ... ; public Object getItem() throws IE { available.acquire(); return nextAvailable(); } public void returnItem(Object x) { If (unmark(x)) available.release(); } synchronized Object nextAvailable(); synchronized boolean unmark(Object x);}
  15. 15. A latch specifies conditions that once set never change. This provides a way to start several threads and have them wait until a signal is received from a coordinating thread. Think of examination hall; while u await for the START signal!. Or multi-player game before the whistle
  16. 16.  Execute Execute
  17. 17. A barrier offers a common point (called a barrier point) for a set of threads to wait for each other before continuing their execution. An advantage over countdownlatch  Can be reset and rerun repeatedly  Once the barrier is met we could break the barrier  Optionally provides Post barrier routine  Kind of split-merge (however merge will need to wait till all splitters are done!)
  18. 18.  Execute
  19. 19.  Exchanger simplifies the way of communicating between threads, that is, by passing a specific object between two threads. Thats why theres the <V> after the class name. Instead of using Piped streams for stream-based, inter-thread communication (where one side writes and the other reads), Exchanger relies on a single exchange method for the transfer of one-off data between threads. The Exchanger is not a general replacement for the piped model, but their usages are similar
  20. 20.  Execute