SlideShare a Scribd company logo
By
venkateshamurthyts@gmail.com
 Available synchronizers
 What is synchronizing
 Basic nuts and bolts(in java)
 Various synchronizers
 Examples
 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 ???
 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!
 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;
 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
 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.
 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)
 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.
 tryAcquire
 tryRelease
 trySharedAcquire
 tryReleaseShared
First extend
                                             template
class 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();
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
 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
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);
}
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
 Execute CountDownLatchDemo.java
 Execute SemaphoreTunnel.java
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!)
 Execute   CyclicBarrierDemo.java
 Exchanger simplifies the way of communicating
  between threads, that is, by passing a specific
  object between two threads. That's why there's
  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
 Execute   ExchangerDemo.java
Java synchronizers

More Related Content

DOCX
Java 5 concurrency
PPTX
PPTX
Effective java - concurrency
PDF
Java Concurrency Idioms
PDF
Locks (Concurrency)
PPT
Java util concurrent
PPT
Java concurrency begining
PDF
Java Concurrency Gotchas
Java 5 concurrency
Effective java - concurrency
Java Concurrency Idioms
Locks (Concurrency)
Java util concurrent
Java concurrency begining
Java Concurrency Gotchas

What's hot (19)

ODP
Sysprog 14
PPTX
Basics of Java Concurrency
ODP
Java Concurrency
PPTX
Grand Central Dispatch in Objective-C
PDF
Java 8 - Stamped Lock
PDF
Java Concurrency Gotchas
PPT
Clojure concurrency
PDF
Actor Concurrency
PPT
Inter threadcommunication.38
PPTX
The Java memory model made easy
PPT
Computer networkppt4577
PDF
02 - Basics of Qt
PDF
Java Concurrency in Practice
PDF
Servletand sessiontracking
PPTX
Deep dive into OSGi Lifecycle Layer
PPTX
OSGi Training for Carbon Developers
PDF
Os practical-presentation
PDF
Антон Нонко, Классические строки в C++
PDF
Qt Rest Server
Sysprog 14
Basics of Java Concurrency
Java Concurrency
Grand Central Dispatch in Objective-C
Java 8 - Stamped Lock
Java Concurrency Gotchas
Clojure concurrency
Actor Concurrency
Inter threadcommunication.38
The Java memory model made easy
Computer networkppt4577
02 - Basics of Qt
Java Concurrency in Practice
Servletand sessiontracking
Deep dive into OSGi Lifecycle Layer
OSGi Training for Carbon Developers
Os practical-presentation
Антон Нонко, Классические строки в C++
Qt Rest Server
Ad

Similar to Java synchronizers (20)

PPTX
Concurrency in Java
PPTX
Threading in java - a pragmatic primer
PDF
Monitors and Blocking Synchronization : The Art of Multiprocessor Programming...
PDF
Semaphore in Java with Example.pdf
PPTX
Full solution to bounded buffer
DOC
Concurrency Learning From Jdk Source
ODP
Multithreading Concepts
ODP
Java Concurrency, Memory Model, and Trends
KEY
Modern Java Concurrency
PPTX
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
PPTX
Mutual Exclusion
PPT
Reliable and Concurrent Software - Java language
PPTX
Low-level concurrency (reinvent vehicle)
PDF
Programming with Threads in Java
PDF
Java Concurrency by Example
PDF
Java Concurrency by Example
PDF
[JavaOne 2011] Models for Concurrent Programming
PPT
Dead locks9cm604.39
KEY
ぐだ生 Java入門第ニ回(synchronized and lock)
PDF
CS844 U1 Individual Project
Concurrency in Java
Threading in java - a pragmatic primer
Monitors and Blocking Synchronization : The Art of Multiprocessor Programming...
Semaphore in Java with Example.pdf
Full solution to bounded buffer
Concurrency Learning From Jdk Source
Multithreading Concepts
Java Concurrency, Memory Model, and Trends
Modern Java Concurrency
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
Mutual Exclusion
Reliable and Concurrent Software - Java language
Low-level concurrency (reinvent vehicle)
Programming with Threads in Java
Java Concurrency by Example
Java Concurrency by Example
[JavaOne 2011] Models for Concurrent Programming
Dead locks9cm604.39
ぐだ生 Java入門第ニ回(synchronized and lock)
CS844 U1 Individual Project
Ad

Java synchronizers

  • 2.  Available synchronizers  What is synchronizing  Basic nuts and bolts(in java)  Various synchronizers  Examples
  • 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.  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.  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.  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.  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.  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.  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.  tryAcquire  tryRelease  trySharedAcquire  tryReleaseShared
  • 11. First extend template class 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. 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.  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. 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. 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.  Execute CountDownLatchDemo.java  Execute SemaphoreTunnel.java
  • 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.  Execute CyclicBarrierDemo.java
  • 19.  Exchanger simplifies the way of communicating between threads, that is, by passing a specific object between two threads. That's why there's 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.  Execute ExchangerDemo.java