SlideShare a Scribd company logo
1 of 21
Download to read offline
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

What's hot

Basics of Java Concurrency
Basics of Java ConcurrencyBasics of Java Concurrency
Basics of Java Concurrencykshanth2101
 
Grand Central Dispatch in Objective-C
Grand Central Dispatch in Objective-CGrand Central Dispatch in Objective-C
Grand Central Dispatch in Objective-CPavel Albitsky
 
Java 8 - Stamped Lock
Java 8 - Stamped LockJava 8 - Stamped Lock
Java 8 - Stamped LockHaim Yadid
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency GotchasAlex Miller
 
Clojure concurrency
Clojure concurrencyClojure concurrency
Clojure concurrencyAlex Navis
 
Actor Concurrency
Actor ConcurrencyActor Concurrency
Actor ConcurrencyAlex Miller
 
Inter threadcommunication.38
Inter threadcommunication.38Inter threadcommunication.38
Inter threadcommunication.38myrajendra
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in PracticeAlina Dolgikh
 
Servletand sessiontracking
Servletand sessiontrackingServletand sessiontracking
Servletand sessiontrackingvamsi krishna
 
Deep dive into OSGi Lifecycle Layer
Deep dive into OSGi Lifecycle LayerDeep dive into OSGi Lifecycle Layer
Deep dive into OSGi Lifecycle LayerAruna Karunarathna
 
OSGi Training for Carbon Developers
OSGi Training for Carbon DevelopersOSGi Training for Carbon Developers
OSGi Training for Carbon DevelopersAruna Karunarathna
 
Os practical-presentation
Os practical-presentationOs practical-presentation
Os practical-presentationEmmanuel Garcia
 
Антон Нонко, Классические строки в C++
Антон Нонко, Классические строки в C++Антон Нонко, Классические строки в C++
Антон Нонко, Классические строки в C++Sergey Platonov
 

What's hot (19)

Sysprog 14
Sysprog 14Sysprog 14
Sysprog 14
 
Basics of Java Concurrency
Basics of Java ConcurrencyBasics of Java Concurrency
Basics of Java Concurrency
 
Java Concurrency
Java ConcurrencyJava Concurrency
Java Concurrency
 
Grand Central Dispatch in Objective-C
Grand Central Dispatch in Objective-CGrand Central Dispatch in Objective-C
Grand Central Dispatch in Objective-C
 
Java 8 - Stamped Lock
Java 8 - Stamped LockJava 8 - Stamped Lock
Java 8 - Stamped Lock
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency Gotchas
 
Clojure concurrency
Clojure concurrencyClojure concurrency
Clojure concurrency
 
Actor Concurrency
Actor ConcurrencyActor Concurrency
Actor Concurrency
 
Inter threadcommunication.38
Inter threadcommunication.38Inter threadcommunication.38
Inter threadcommunication.38
 
The Java memory model made easy
The Java memory model made easyThe Java memory model made easy
The Java memory model made easy
 
Computer networkppt4577
Computer networkppt4577Computer networkppt4577
Computer networkppt4577
 
02 - Basics of Qt
02 - Basics of Qt02 - Basics of Qt
02 - Basics of Qt
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in Practice
 
Servletand sessiontracking
Servletand sessiontrackingServletand sessiontracking
Servletand sessiontracking
 
Deep dive into OSGi Lifecycle Layer
Deep dive into OSGi Lifecycle LayerDeep dive into OSGi Lifecycle Layer
Deep dive into OSGi Lifecycle Layer
 
OSGi Training for Carbon Developers
OSGi Training for Carbon DevelopersOSGi Training for Carbon Developers
OSGi Training for Carbon Developers
 
Os practical-presentation
Os practical-presentationOs practical-presentation
Os practical-presentation
 
Антон Нонко, Классические строки в C++
Антон Нонко, Классические строки в C++Антон Нонко, Классические строки в C++
Антон Нонко, Классические строки в C++
 
Qt Rest Server
Qt Rest ServerQt Rest Server
Qt Rest Server
 

Similar to Java synchronizers

Multithreading Presentation
Multithreading PresentationMultithreading Presentation
Multithreading PresentationNeeraj Kaushik
 
Fork and join framework
Fork and join frameworkFork and join framework
Fork and join frameworkMinh Tran
 
Use of Apache Commons and Utilities
Use of Apache Commons and UtilitiesUse of Apache Commons and Utilities
Use of Apache Commons and UtilitiesPramod Kumar
 
Java Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsJava Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsCarol McDonald
 
Deuce STM - CMP'09
Deuce STM - CMP'09Deuce STM - CMP'09
Deuce STM - CMP'09Guy Korland
 
Concurrency in Programming Languages
Concurrency in Programming LanguagesConcurrency in Programming Languages
Concurrency in Programming LanguagesYudong Li
 
Lec7!JavaThreads.ppt
Lec7!JavaThreads.pptLec7!JavaThreads.ppt
Lec7!JavaThreads.pptssuserec53e73
 
ぐだ生 Java入門第ニ回(synchronized and lock)
ぐだ生 Java入門第ニ回(synchronized and lock)ぐだ生 Java入門第ニ回(synchronized and lock)
ぐだ生 Java入門第ニ回(synchronized and lock)Makoto Yamazaki
 
ぐだ生 Java入門第ニ回(synchronized and lock)
ぐだ生 Java入門第ニ回(synchronized and lock)ぐだ生 Java入門第ニ回(synchronized and lock)
ぐだ生 Java入門第ニ回(synchronized and lock)Makoto Yamazaki
 
Introduction to Concurrent Data Structures
Introduction to Concurrent Data StructuresIntroduction to Concurrent Data Structures
Introduction to Concurrent Data StructuresDilum Bandara
 
JAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICESJAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICESNikunj Parekh
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronizationpriyabogra1
 

Similar to Java synchronizers (20)

Concurrency gotchas
Concurrency gotchasConcurrency gotchas
Concurrency gotchas
 
Multithreading Presentation
Multithreading PresentationMultithreading Presentation
Multithreading Presentation
 
Fork and join framework
Fork and join frameworkFork and join framework
Fork and join framework
 
Introduction+To+Java+Concurrency
Introduction+To+Java+ConcurrencyIntroduction+To+Java+Concurrency
Introduction+To+Java+Concurrency
 
Use of Apache Commons and Utilities
Use of Apache Commons and UtilitiesUse of Apache Commons and Utilities
Use of Apache Commons and Utilities
 
Java Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsJava Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and Trends
 
Deuce STM - CMP'09
Deuce STM - CMP'09Deuce STM - CMP'09
Deuce STM - CMP'09
 
Concurrency in Programming Languages
Concurrency in Programming LanguagesConcurrency in Programming Languages
Concurrency in Programming Languages
 
unit-3java.pptx
unit-3java.pptxunit-3java.pptx
unit-3java.pptx
 
Lec7!JavaThreads.ppt
Lec7!JavaThreads.pptLec7!JavaThreads.ppt
Lec7!JavaThreads.ppt
 
Lec7!JavaThreads.ppt
Lec7!JavaThreads.pptLec7!JavaThreads.ppt
Lec7!JavaThreads.ppt
 
ぐだ生 Java入門第ニ回(synchronized and lock)
ぐだ生 Java入門第ニ回(synchronized and lock)ぐだ生 Java入門第ニ回(synchronized and lock)
ぐだ生 Java入門第ニ回(synchronized and lock)
 
Thread
ThreadThread
Thread
 
ぐだ生 Java入門第ニ回(synchronized and lock)
ぐだ生 Java入門第ニ回(synchronized and lock)ぐだ生 Java入門第ニ回(synchronized and lock)
ぐだ生 Java入門第ニ回(synchronized and lock)
 
Introduction to Concurrent Data Structures
Introduction to Concurrent Data StructuresIntroduction to Concurrent Data Structures
Introduction to Concurrent Data Structures
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
JAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICESJAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICES
 
Jist of Java
Jist of JavaJist of Java
Jist of Java
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronization
 
concurrency_c#_public
concurrency_c#_publicconcurrency_c#_public
concurrency_c#_public
 

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