SlideShare uma empresa Scribd logo
1 de 39
Baixar para ler offline
Concurrency: Best Practices




Pramod B Nagaraja
IBM India Pvt LTD                       1
Agenda

    Why Concurrency?

    Concurrency Panoramas

    Synchronization
       When and What to synchronize

    Guidelines for designing Concurrent Applications

    Excessive Synchronization

    Synchronization Optimization

    Latches & Barriers

                                                       2
1.0 Why Concurrency
Story so far….


    Most of the applications ran on system with few
    processors

    Relied on faster hardware, rather than
    Software Concurrency/Parallelism, for better
    performance

                                                   3
1.0 Why Concurrency
…Current scenario


    Moore's Law predicts that the number of
    transistors on a chip doubles every two years

    Faster Dual core machines demand
    Concurrency

    Multithreading is the pulse of Java
                                                    4
2.O Concurrency Panoramas
• Atomicity
  – Certain pieces of an application must all be
    executed as one unit




                                                   5
2.O Concurrency Panoramas

    Atomicity
    synchronized int getBalance() {
         return balance;
    }
        synchronized void setBalance(int x) {
         balance = x;}
    void deposit(int x) {              void withdraw(int x) {
         int b = getBalance();           int b = getBalance();
         setBalance(b + x);}             setBalance(b - x);}}
                                                                 6
2.O Concurrency Panoramas

    Visibility
     −   Changes that you make to a value to be
         visible precisely when you intend them to be




                                                        7
2.O Concurrency Panoramas

    Visibility
class LoopMayNeverEnd {
    boolean done = false;
    void work() {           void stopWork() {
      while (!done) {            done = true; }
                            }
           // do work
       }
}
                                                  8
3.0 Synchronization


Things which matter MOST should never be at
      mercy of things which matter LEAST




                                              9
3.1 When to Synchronize
Pitfalls when synchronizing:
     Forgetting to synchronize a resource that
      should be synchronized
     Synchronizing the wrong resource
     Synchronizing too often



                                                  10
3.2 What to Synchronize

    Not just the resource, but also the Transaction
    involving the resource

    Pay attention to Data integrity at multiple
    levels of granularity




                                                  11
3.2 What to Synchronize
private int foo;
  public synchronized int getFoo() {
  return foo;
  }
  public synchronized void setFoo(int f) {
  foo = f;
  }
  setFoo(getFoo() + 1); //not thread safe
                                             12
4. Guidelines for designing
          Concurrent Applications

    4 common concurrency mechanisms generally
    used in combination with each other to safely
    access data from multiple threads
    −   Dynamic Exclusion Through Implicit Locks
    −   Structural Exclusion Through Confinement
    −   Immutability
    −   Cooperation

                                                   13
4.1 Dynamic Exclusion Through
        Implicit Locks
Lock associated with an object is acquired when a
method is declared synchronized.
   public synchronized void setName(String name);


    Limitation
     −   When synchronization is used inappropriately or
         excessively it causes poor performance and
         deadlock.



                                                           14
4.1 Dynamic Exclusion Through
            Implicit Locks

    Best Practice Tip
       Do not perform CPU intensive and I/O operations inside
        synchronized method.
       When possible synchronize on block of code instead of
        synchronizing entire method.
        Ex: synchronize(lock) { //critical section guarded by lock}




                                                                      15
4.2 Structural Exclusion Through
              Confinement

    Thread confinement : Access object from a single
    thread using thread-per-session approach

    Instance confinement : Use encapsulation
    techniques to restrict access to object state from
    multiple threads

    Method confinement : Do not allow an object to
    escape from method by referencing it through local
    variables

                                                         16
4.2 Structural Exclusion Through
              Confinement

    Limitations :
     −   Confinement cannot be relied on unless a design
         is leak proof

    Best Practice Tip :
      Combine        confinement with appropriate locking
         discipline
      Use   ThreadLocal variables to maintain Thread
         Confinement
                                                             17
4.3 Immutability

    Immutable objects do not need additional
    synchronization
                                   afe {
    Public final class ImmutableClass
                            ea d-s
      private final intThr = 100;
                        field1
                   ly
               ent String field2=“FIN”;
      private final
       In her
    ………..
    }
                                               18
4.3 Immutability

    Limitation
    −   In a software application only some classes can
        be immutable.

    Best Practice Tip
    −   Even when class is not fully immutable, declare
        its non changeable fields as final to limit its
        mutability.


                                                          19
4.4 Cooperation
What is purpose of wait-and-notify mechanism?
When one thread needs a certain condition to exist and
another thread can create that condition then we use wait
and notify methods.
                                 Thread 1

              Thread 2               CONDITION MET
                                     STOP!! CONDITION NOT
                                     MET
                                     Thread 1 can
                                     proceed cannot progress
                                     Thread 1

 Thread 2 - “I will meet
 your condition.”

                                                               20
4.4 Cooperation
Limitation
   − When there are multiple waiting threads, you cannot be
     certain which thread is woken up.
   − Due to race conditions there could be missed or early
     notifications.
Best Practice Tip
 Safe to wake up all the threads using notifyAll() method instead
  of waking an arbitrary thread using notify()
 Sometimes condition that caused thread to wait is not achieved
  when wait() returns, therefore put wait() call in a while loop.
 Wait() and notify() must always be called inside synchronized
  code.
                                                                    21
5. Excessive Synchronization

    Poor performance

    Deadlock
       Can occur when multiple threads each acquire
        multiple locks in different orders




                                                       22
5.1 Deadlock
public static Object cacheLock = new Object();
 public static Object tableLock = new Object();
 ...
 public void oneMethod() {          public void anotherMethod() {
  synchronized (cacheLock) {          synchronized (tableLock) {
                                       synchronized (cacheLock) {
       synchronized (tableLock) {        doSomethingElse();
        doSomething(); } } }           }}}



                       Need not be this obvious !!!!
                                                                23
5.1 Deadlock
public void transferMoney(Account fromAccn,
  Account toAccn, Amount amnt) {
    synchronized (fromAccn) {
       synchronized (toAccn) {
         if (fromAccn.hasSufficientBalance(amnt) {
                  fromAccn.debit(amnt);
                  toAccn.credit(amnt);}}}
Thread A : transferMoney(accountOne, accountTwo, amount);
Thread B : transferMoney(accountTwo, accountOne, amount);
                                                            24
5.1 Deadlock
How to avoid Deadlock
     Avoid acquiring more than one lock at a time
     Allow a thread to voluntarily give up its resources if a
      second level or successive lock acquisition fails, this is
      called Two Phase Locking
     Never call a synchronized method of another class from a
      synchronized method
     Follow a fixed order while acquiring and releasing locks
     Induce Lock ordering, if required
       
           Object.identityHashCode() method
                                                                   25
5.1 Deadlock
Banking example revisited
  public void transferMoney(Account fromAccn,
  Account toAccn,Amount amnt) {
  Account firstLck, secondLck;
  if (fromAccn.accountNumber() <
  toAccn.accountNumber()) {
     firstLck = fromAccn;
     secondLck = toAccn;
  } else {
     firstLck = toAccn;
     secondLck = fromAccn; }
                                                26
5.1 Deadlock
synchronized (firstLck) {
 synchronized (secondLck) {
        if (fromAccn.hasSufficientBalance(amnt){
         fromAccn.debit(amnt);
         toAccn.credit(amnt);    }
} } }




                                                   27
6. Synchronization Optimization
JVM optimizes synchronization [under the
 hood]:
     Lock Elision
     Biased Locking
     Lock Coarsening
     Thread Spinning vs Thread Suspending


                                             28
6.1 Synchronization Optimization

    Lock Elision :: Locks on local scope
    references can be elided
    public String concatBuffer(String s1,String s2,String s3) {
        StringBuffer sb = new StringBuffer();
        sb.append(s1);
        sb.append(s2);
        sb.append(s3);
        return sb.toString(); }
                                                                  29
6.2 Synchronization Optimization
• Biased Locking :: Most locks are never
 accessed by more than one thread during
 their life time
  
      Release the lease only if another thread
      attempts to acquire the same lock
  
      Default in Java 6 Hotspot/JIT



                                                 30
6.3 Synchronization Optimization

    Lock coarsening :: Adjacent synchronized
    blocks may be merged into one synchronized
    block
    public static String concatToBuffer(StringBuffer sb, String s1,
     String s2, String s3) {
         sb.append(s1);
         sb.append(s2);
         sb.append(s3);
         return sb.toString();}
                                                                      31
6.4 Synchronization Optimization

    Thread Suspending vs Thread Spinning

    In 1.4.2, spin for (default value of) 10 iterations
    before being suspended

    Adaptive Spinning
       Introduced in 1.6
       Spin duration based on the previous spin attempts
        and state of the lock owner

                                                        32
7.1 Latches

    Latches allows one or more threads to wait
    until a set of operations being performed in
    other threads completes.

    When N concurrent sub-tasks occur, the
    coordinating thread will wait until each sub-
    task is executed



                                                    33
7.1 Latches
class TestLatch {
final CountDownLatch latch = new CountDownLatch(3);
class myThread extends Thread {
    public void run() { task.run();
        latch.countDown()}}
public static void main (String[] args){
    TestLatch tst = new TestLatch();
    tst.new myThread().start();
    tst.new myThread().start();
    tst.new myThread().start();
    latch.await();//Thread execution completed}}
                                                      34
7.2 Barriers

    Barrier allows a set of threads to wait for each
    other at a common barrier point.

    When Barrier point occurs all the threads
    waiting on it are released and run() method of
    Barrier object is called.
class TestBarrier {
    final static int no_of_engines = 4;
    Runnable task = new Runnable() {
            public void run() { flyplane() }}
                                                   35
7.2 Barriers
final CyclicBarrier barrier = new CyclicBarrier(no_of_engines,task);
   class Worker implements Runnable {
       public void run() {
           startEngine();
           barrier.await();} }
public static void main(String[] args) {
        TestBarrier flight = new TestBarrier ();
       for (int i = 0; i < no_of_engines; ++i)
           new Thread(flight.new Worker(i)).start();     }}

                                                                       36
References

    https://www6.software.ibm.com/developerwor
    ks/education/j-concur/index.html

    http://www.infoq.com/articles/java-threading-
    optimizations-p1

    http://www.infoq.com/presentations/goetz-
    concurrency-past-present


                                                    37
Q&A




      38
Thank You !!!!




                 39

Mais conteúdo relacionado

Destaque

Perl 6 for Concurrency and Parallel Computing
Perl 6 for Concurrency and Parallel ComputingPerl 6 for Concurrency and Parallel Computing
Perl 6 for Concurrency and Parallel ComputingAndrew Shitov
 
Save JVM by Yourself: Real War Experiences of OOM
Save JVM by Yourself: Real War Experiences of OOMSave JVM by Yourself: Real War Experiences of OOM
Save JVM by Yourself: Real War Experiences of OOMLeon Chen
 
Lock Interface in Java
Lock Interface in JavaLock Interface in Java
Lock Interface in JavaHome
 
Recipe 黃佳伶 葉愛慧
Recipe 黃佳伶 葉愛慧Recipe 黃佳伶 葉愛慧
Recipe 黃佳伶 葉愛慧10y2try
 
Building a lock profiler on the JVM
Building a lock profiler on the JVMBuilding a lock profiler on the JVM
Building a lock profiler on the JVMPierre Laporte
 
大型网站架构演变
大型网站架构演变大型网站架构演变
大型网站架构演变xiaozhen1900
 
自己的JVM自己救: 解救 OOM 實務經驗談 (JCConf 2015)
自己的JVM自己救: 解救 OOM 實務經驗談  (JCConf 2015)自己的JVM自己救: 解救 OOM 實務經驗談  (JCConf 2015)
自己的JVM自己救: 解救 OOM 實務經驗談 (JCConf 2015)Leon Chen
 
浅谈项目管理(诸葛B2B电商研发部版改)
浅谈项目管理(诸葛B2B电商研发部版改)浅谈项目管理(诸葛B2B电商研发部版改)
浅谈项目管理(诸葛B2B电商研发部版改)诸葛修车网-诸葛商城
 
Thrift+scribe实现分布式日志收集,并与log4j集成
Thrift+scribe实现分布式日志收集,并与log4j集成Thrift+scribe实现分布式日志收集,并与log4j集成
Thrift+scribe实现分布式日志收集,并与log4j集成zhongbing liu
 
Performance Tuning - Understanding Garbage Collection
Performance Tuning - Understanding Garbage CollectionPerformance Tuning - Understanding Garbage Collection
Performance Tuning - Understanding Garbage CollectionHaribabu Nandyal Padmanaban
 
[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronization[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronizationxuehan zhu
 
Effective java - concurrency
Effective java - concurrencyEffective java - concurrency
Effective java - concurrencyfeng lee
 
Java concurrency - Thread pools
Java concurrency - Thread poolsJava concurrency - Thread pools
Java concurrency - Thread poolsmaksym220889
 
淺談 Java GC 原理、調教和 新發展
淺談 Java GC 原理、調教和新發展淺談 Java GC 原理、調教和新發展
淺談 Java GC 原理、調教和 新發展Leon Chen
 

Destaque (20)

Perl 6 for Concurrency and Parallel Computing
Perl 6 for Concurrency and Parallel ComputingPerl 6 for Concurrency and Parallel Computing
Perl 6 for Concurrency and Parallel Computing
 
Save JVM by Yourself: Real War Experiences of OOM
Save JVM by Yourself: Real War Experiences of OOMSave JVM by Yourself: Real War Experiences of OOM
Save JVM by Yourself: Real War Experiences of OOM
 
Lock Interface in Java
Lock Interface in JavaLock Interface in Java
Lock Interface in Java
 
Recipe 黃佳伶 葉愛慧
Recipe 黃佳伶 葉愛慧Recipe 黃佳伶 葉愛慧
Recipe 黃佳伶 葉愛慧
 
App开发过程的演变之路
App开发过程的演变之路App开发过程的演变之路
App开发过程的演变之路
 
Git基础培训
Git基础培训Git基础培训
Git基础培训
 
Nginx+tomcat https 配置
Nginx+tomcat  https 配置Nginx+tomcat  https 配置
Nginx+tomcat https 配置
 
Building a lock profiler on the JVM
Building a lock profiler on the JVMBuilding a lock profiler on the JVM
Building a lock profiler on the JVM
 
大型网站架构演变
大型网站架构演变大型网站架构演变
大型网站架构演变
 
如何更好地设计测试用例-BQConf
如何更好地设计测试用例-BQConf如何更好地设计测试用例-BQConf
如何更好地设计测试用例-BQConf
 
自己的JVM自己救: 解救 OOM 實務經驗談 (JCConf 2015)
自己的JVM自己救: 解救 OOM 實務經驗談  (JCConf 2015)自己的JVM自己救: 解救 OOM 實務經驗談  (JCConf 2015)
自己的JVM自己救: 解救 OOM 實務經驗談 (JCConf 2015)
 
Java多线程技术
Java多线程技术Java多线程技术
Java多线程技术
 
浅谈项目管理(诸葛B2B电商研发部版改)
浅谈项目管理(诸葛B2B电商研发部版改)浅谈项目管理(诸葛B2B电商研发部版改)
浅谈项目管理(诸葛B2B电商研发部版改)
 
Thrift+scribe实现分布式日志收集,并与log4j集成
Thrift+scribe实现分布式日志收集,并与log4j集成Thrift+scribe实现分布式日志收集,并与log4j集成
Thrift+scribe实现分布式日志收集,并与log4j集成
 
Performance Tuning - Understanding Garbage Collection
Performance Tuning - Understanding Garbage CollectionPerformance Tuning - Understanding Garbage Collection
Performance Tuning - Understanding Garbage Collection
 
[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronization[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronization
 
Effective java - concurrency
Effective java - concurrencyEffective java - concurrency
Effective java - concurrency
 
JVM及其调优
JVM及其调优JVM及其调优
JVM及其调优
 
Java concurrency - Thread pools
Java concurrency - Thread poolsJava concurrency - Thread pools
Java concurrency - Thread pools
 
淺談 Java GC 原理、調教和 新發展
淺談 Java GC 原理、調教和新發展淺談 Java GC 原理、調教和新發展
淺談 Java GC 原理、調教和 新發展
 

Semelhante a Concurrency: Best Practices

Java- Concurrent programming - Synchronization (part 1)
Java- Concurrent programming - Synchronization (part 1)Java- Concurrent programming - Synchronization (part 1)
Java- Concurrent programming - Synchronization (part 1)Riccardo Cardin
 
Multi core programming 2
Multi core programming 2Multi core programming 2
Multi core programming 2Robin Aggarwal
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronizationpriyabogra1
 
Distributed computing presentation
Distributed computing presentationDistributed computing presentation
Distributed computing presentationDelhi/NCR HUG
 
Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)choksheak
 
Java concurrency introduction
Java concurrency introductionJava concurrency introduction
Java concurrency introductionyangwm
 
Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in JavaLakshmi Narasimhan
 
Inter Thread Communicationn.pptx
Inter Thread Communicationn.pptxInter Thread Communicationn.pptx
Inter Thread Communicationn.pptxSelvakumarNSNS
 
.NET: Thread Synchronization Constructs
.NET: Thread Synchronization Constructs.NET: Thread Synchronization Constructs
.NET: Thread Synchronization ConstructsSasha Kravchuk
 
Slot03 concurrency2
Slot03 concurrency2Slot03 concurrency2
Slot03 concurrency2Viên Mai
 
chap 7 : Threads (scjp/ocjp)
chap 7 : Threads (scjp/ocjp)chap 7 : Threads (scjp/ocjp)
chap 7 : Threads (scjp/ocjp)It Academy
 

Semelhante a Concurrency: Best Practices (20)

Concurrency
ConcurrencyConcurrency
Concurrency
 
Java- Concurrent programming - Synchronization (part 1)
Java- Concurrent programming - Synchronization (part 1)Java- Concurrent programming - Synchronization (part 1)
Java- Concurrent programming - Synchronization (part 1)
 
Multi core programming 2
Multi core programming 2Multi core programming 2
Multi core programming 2
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronization
 
Distributed computing presentation
Distributed computing presentationDistributed computing presentation
Distributed computing presentation
 
Concurrency
ConcurrencyConcurrency
Concurrency
 
Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)
 
Java concurrency introduction
Java concurrency introductionJava concurrency introduction
Java concurrency introduction
 
Concurrency
ConcurrencyConcurrency
Concurrency
 
Concurrency in Java
Concurrency in JavaConcurrency in Java
Concurrency in Java
 
Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in Java
 
Inter Thread Communicationn.pptx
Inter Thread Communicationn.pptxInter Thread Communicationn.pptx
Inter Thread Communicationn.pptx
 
Thread & concurrancy
Thread & concurrancyThread & concurrancy
Thread & concurrancy
 
.NET: Thread Synchronization Constructs
.NET: Thread Synchronization Constructs.NET: Thread Synchronization Constructs
.NET: Thread Synchronization Constructs
 
The Java Memory Model
The Java Memory ModelThe Java Memory Model
The Java Memory Model
 
04 threads
04 threads04 threads
04 threads
 
Vertx
VertxVertx
Vertx
 
Slot03 concurrency2
Slot03 concurrency2Slot03 concurrency2
Slot03 concurrency2
 
Vertx
VertxVertx
Vertx
 
chap 7 : Threads (scjp/ocjp)
chap 7 : Threads (scjp/ocjp)chap 7 : Threads (scjp/ocjp)
chap 7 : Threads (scjp/ocjp)
 

Mais de IndicThreads

Http2 is here! And why the web needs it
Http2 is here! And why the web needs itHttp2 is here! And why the web needs it
Http2 is here! And why the web needs itIndicThreads
 
Understanding Bitcoin (Blockchain) and its Potential for Disruptive Applications
Understanding Bitcoin (Blockchain) and its Potential for Disruptive ApplicationsUnderstanding Bitcoin (Blockchain) and its Potential for Disruptive Applications
Understanding Bitcoin (Blockchain) and its Potential for Disruptive ApplicationsIndicThreads
 
Go Programming Language - Learning The Go Lang way
Go Programming Language - Learning The Go Lang wayGo Programming Language - Learning The Go Lang way
Go Programming Language - Learning The Go Lang wayIndicThreads
 
Building Resilient Microservices
Building Resilient Microservices Building Resilient Microservices
Building Resilient Microservices IndicThreads
 
App using golang indicthreads
App using golang  indicthreadsApp using golang  indicthreads
App using golang indicthreadsIndicThreads
 
Building on quicksand microservices indicthreads
Building on quicksand microservices  indicthreadsBuilding on quicksand microservices  indicthreads
Building on quicksand microservices indicthreadsIndicThreads
 
How to Think in RxJava Before Reacting
How to Think in RxJava Before ReactingHow to Think in RxJava Before Reacting
How to Think in RxJava Before ReactingIndicThreads
 
Iot secure connected devices indicthreads
Iot secure connected devices indicthreadsIot secure connected devices indicthreads
Iot secure connected devices indicthreadsIndicThreads
 
Real world IoT for enterprises
Real world IoT for enterprisesReal world IoT for enterprises
Real world IoT for enterprisesIndicThreads
 
IoT testing and quality assurance indicthreads
IoT testing and quality assurance indicthreadsIoT testing and quality assurance indicthreads
IoT testing and quality assurance indicthreadsIndicThreads
 
Functional Programming Past Present Future
Functional Programming Past Present FutureFunctional Programming Past Present Future
Functional Programming Past Present FutureIndicThreads
 
Harnessing the Power of Java 8 Streams
Harnessing the Power of Java 8 Streams Harnessing the Power of Java 8 Streams
Harnessing the Power of Java 8 Streams IndicThreads
 
Building & scaling a live streaming mobile platform - Gr8 road to fame
Building & scaling a live streaming mobile platform - Gr8 road to fameBuilding & scaling a live streaming mobile platform - Gr8 road to fame
Building & scaling a live streaming mobile platform - Gr8 road to fameIndicThreads
 
Internet of things architecture perspective - IndicThreads Conference
Internet of things architecture perspective - IndicThreads ConferenceInternet of things architecture perspective - IndicThreads Conference
Internet of things architecture perspective - IndicThreads ConferenceIndicThreads
 
Cars and Computers: Building a Java Carputer
 Cars and Computers: Building a Java Carputer Cars and Computers: Building a Java Carputer
Cars and Computers: Building a Java CarputerIndicThreads
 
Scrap Your MapReduce - Apache Spark
 Scrap Your MapReduce - Apache Spark Scrap Your MapReduce - Apache Spark
Scrap Your MapReduce - Apache SparkIndicThreads
 
Continuous Integration (CI) and Continuous Delivery (CD) using Jenkins & Docker
 Continuous Integration (CI) and Continuous Delivery (CD) using Jenkins & Docker Continuous Integration (CI) and Continuous Delivery (CD) using Jenkins & Docker
Continuous Integration (CI) and Continuous Delivery (CD) using Jenkins & DockerIndicThreads
 
Speed up your build pipeline for faster feedback
Speed up your build pipeline for faster feedbackSpeed up your build pipeline for faster feedback
Speed up your build pipeline for faster feedbackIndicThreads
 
Unraveling OpenStack Clouds
 Unraveling OpenStack Clouds Unraveling OpenStack Clouds
Unraveling OpenStack CloudsIndicThreads
 
Digital Transformation of the Enterprise. What IT leaders need to know!
Digital Transformation of the Enterprise. What IT  leaders need to know!Digital Transformation of the Enterprise. What IT  leaders need to know!
Digital Transformation of the Enterprise. What IT leaders need to know!IndicThreads
 

Mais de IndicThreads (20)

Http2 is here! And why the web needs it
Http2 is here! And why the web needs itHttp2 is here! And why the web needs it
Http2 is here! And why the web needs it
 
Understanding Bitcoin (Blockchain) and its Potential for Disruptive Applications
Understanding Bitcoin (Blockchain) and its Potential for Disruptive ApplicationsUnderstanding Bitcoin (Blockchain) and its Potential for Disruptive Applications
Understanding Bitcoin (Blockchain) and its Potential for Disruptive Applications
 
Go Programming Language - Learning The Go Lang way
Go Programming Language - Learning The Go Lang wayGo Programming Language - Learning The Go Lang way
Go Programming Language - Learning The Go Lang way
 
Building Resilient Microservices
Building Resilient Microservices Building Resilient Microservices
Building Resilient Microservices
 
App using golang indicthreads
App using golang  indicthreadsApp using golang  indicthreads
App using golang indicthreads
 
Building on quicksand microservices indicthreads
Building on quicksand microservices  indicthreadsBuilding on quicksand microservices  indicthreads
Building on quicksand microservices indicthreads
 
How to Think in RxJava Before Reacting
How to Think in RxJava Before ReactingHow to Think in RxJava Before Reacting
How to Think in RxJava Before Reacting
 
Iot secure connected devices indicthreads
Iot secure connected devices indicthreadsIot secure connected devices indicthreads
Iot secure connected devices indicthreads
 
Real world IoT for enterprises
Real world IoT for enterprisesReal world IoT for enterprises
Real world IoT for enterprises
 
IoT testing and quality assurance indicthreads
IoT testing and quality assurance indicthreadsIoT testing and quality assurance indicthreads
IoT testing and quality assurance indicthreads
 
Functional Programming Past Present Future
Functional Programming Past Present FutureFunctional Programming Past Present Future
Functional Programming Past Present Future
 
Harnessing the Power of Java 8 Streams
Harnessing the Power of Java 8 Streams Harnessing the Power of Java 8 Streams
Harnessing the Power of Java 8 Streams
 
Building & scaling a live streaming mobile platform - Gr8 road to fame
Building & scaling a live streaming mobile platform - Gr8 road to fameBuilding & scaling a live streaming mobile platform - Gr8 road to fame
Building & scaling a live streaming mobile platform - Gr8 road to fame
 
Internet of things architecture perspective - IndicThreads Conference
Internet of things architecture perspective - IndicThreads ConferenceInternet of things architecture perspective - IndicThreads Conference
Internet of things architecture perspective - IndicThreads Conference
 
Cars and Computers: Building a Java Carputer
 Cars and Computers: Building a Java Carputer Cars and Computers: Building a Java Carputer
Cars and Computers: Building a Java Carputer
 
Scrap Your MapReduce - Apache Spark
 Scrap Your MapReduce - Apache Spark Scrap Your MapReduce - Apache Spark
Scrap Your MapReduce - Apache Spark
 
Continuous Integration (CI) and Continuous Delivery (CD) using Jenkins & Docker
 Continuous Integration (CI) and Continuous Delivery (CD) using Jenkins & Docker Continuous Integration (CI) and Continuous Delivery (CD) using Jenkins & Docker
Continuous Integration (CI) and Continuous Delivery (CD) using Jenkins & Docker
 
Speed up your build pipeline for faster feedback
Speed up your build pipeline for faster feedbackSpeed up your build pipeline for faster feedback
Speed up your build pipeline for faster feedback
 
Unraveling OpenStack Clouds
 Unraveling OpenStack Clouds Unraveling OpenStack Clouds
Unraveling OpenStack Clouds
 
Digital Transformation of the Enterprise. What IT leaders need to know!
Digital Transformation of the Enterprise. What IT  leaders need to know!Digital Transformation of the Enterprise. What IT  leaders need to know!
Digital Transformation of the Enterprise. What IT leaders need to know!
 

Último

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdfChristopherTHyatt
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 

Último (20)

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 

Concurrency: Best Practices

  • 1. Concurrency: Best Practices Pramod B Nagaraja IBM India Pvt LTD 1
  • 2. Agenda  Why Concurrency?  Concurrency Panoramas  Synchronization  When and What to synchronize  Guidelines for designing Concurrent Applications  Excessive Synchronization  Synchronization Optimization  Latches & Barriers 2
  • 3. 1.0 Why Concurrency Story so far….  Most of the applications ran on system with few processors  Relied on faster hardware, rather than Software Concurrency/Parallelism, for better performance 3
  • 4. 1.0 Why Concurrency …Current scenario  Moore's Law predicts that the number of transistors on a chip doubles every two years  Faster Dual core machines demand Concurrency  Multithreading is the pulse of Java 4
  • 5. 2.O Concurrency Panoramas • Atomicity – Certain pieces of an application must all be executed as one unit 5
  • 6. 2.O Concurrency Panoramas  Atomicity synchronized int getBalance() { return balance; } synchronized void setBalance(int x) { balance = x;} void deposit(int x) { void withdraw(int x) { int b = getBalance(); int b = getBalance(); setBalance(b + x);} setBalance(b - x);}} 6
  • 7. 2.O Concurrency Panoramas  Visibility − Changes that you make to a value to be visible precisely when you intend them to be 7
  • 8. 2.O Concurrency Panoramas  Visibility class LoopMayNeverEnd { boolean done = false; void work() { void stopWork() { while (!done) { done = true; } } // do work } } 8
  • 9. 3.0 Synchronization Things which matter MOST should never be at mercy of things which matter LEAST 9
  • 10. 3.1 When to Synchronize Pitfalls when synchronizing:  Forgetting to synchronize a resource that should be synchronized  Synchronizing the wrong resource  Synchronizing too often 10
  • 11. 3.2 What to Synchronize  Not just the resource, but also the Transaction involving the resource  Pay attention to Data integrity at multiple levels of granularity 11
  • 12. 3.2 What to Synchronize private int foo; public synchronized int getFoo() { return foo; } public synchronized void setFoo(int f) { foo = f; } setFoo(getFoo() + 1); //not thread safe 12
  • 13. 4. Guidelines for designing Concurrent Applications  4 common concurrency mechanisms generally used in combination with each other to safely access data from multiple threads − Dynamic Exclusion Through Implicit Locks − Structural Exclusion Through Confinement − Immutability − Cooperation 13
  • 14. 4.1 Dynamic Exclusion Through Implicit Locks Lock associated with an object is acquired when a method is declared synchronized. public synchronized void setName(String name);  Limitation − When synchronization is used inappropriately or excessively it causes poor performance and deadlock. 14
  • 15. 4.1 Dynamic Exclusion Through Implicit Locks  Best Practice Tip  Do not perform CPU intensive and I/O operations inside synchronized method.  When possible synchronize on block of code instead of synchronizing entire method. Ex: synchronize(lock) { //critical section guarded by lock} 15
  • 16. 4.2 Structural Exclusion Through Confinement  Thread confinement : Access object from a single thread using thread-per-session approach  Instance confinement : Use encapsulation techniques to restrict access to object state from multiple threads  Method confinement : Do not allow an object to escape from method by referencing it through local variables 16
  • 17. 4.2 Structural Exclusion Through Confinement  Limitations : − Confinement cannot be relied on unless a design is leak proof  Best Practice Tip :  Combine confinement with appropriate locking discipline  Use ThreadLocal variables to maintain Thread Confinement 17
  • 18. 4.3 Immutability  Immutable objects do not need additional synchronization afe { Public final class ImmutableClass ea d-s private final intThr = 100; field1 ly ent String field2=“FIN”; private final In her ……….. } 18
  • 19. 4.3 Immutability  Limitation − In a software application only some classes can be immutable.  Best Practice Tip − Even when class is not fully immutable, declare its non changeable fields as final to limit its mutability. 19
  • 20. 4.4 Cooperation What is purpose of wait-and-notify mechanism? When one thread needs a certain condition to exist and another thread can create that condition then we use wait and notify methods. Thread 1 Thread 2 CONDITION MET STOP!! CONDITION NOT MET Thread 1 can proceed cannot progress Thread 1 Thread 2 - “I will meet your condition.” 20
  • 21. 4.4 Cooperation Limitation − When there are multiple waiting threads, you cannot be certain which thread is woken up. − Due to race conditions there could be missed or early notifications. Best Practice Tip  Safe to wake up all the threads using notifyAll() method instead of waking an arbitrary thread using notify()  Sometimes condition that caused thread to wait is not achieved when wait() returns, therefore put wait() call in a while loop.  Wait() and notify() must always be called inside synchronized code. 21
  • 22. 5. Excessive Synchronization  Poor performance  Deadlock  Can occur when multiple threads each acquire multiple locks in different orders 22
  • 23. 5.1 Deadlock public static Object cacheLock = new Object(); public static Object tableLock = new Object(); ... public void oneMethod() { public void anotherMethod() { synchronized (cacheLock) { synchronized (tableLock) { synchronized (cacheLock) { synchronized (tableLock) { doSomethingElse(); doSomething(); } } } }}} Need not be this obvious !!!! 23
  • 24. 5.1 Deadlock public void transferMoney(Account fromAccn, Account toAccn, Amount amnt) { synchronized (fromAccn) { synchronized (toAccn) { if (fromAccn.hasSufficientBalance(amnt) { fromAccn.debit(amnt); toAccn.credit(amnt);}}} Thread A : transferMoney(accountOne, accountTwo, amount); Thread B : transferMoney(accountTwo, accountOne, amount); 24
  • 25. 5.1 Deadlock How to avoid Deadlock  Avoid acquiring more than one lock at a time  Allow a thread to voluntarily give up its resources if a second level or successive lock acquisition fails, this is called Two Phase Locking  Never call a synchronized method of another class from a synchronized method  Follow a fixed order while acquiring and releasing locks  Induce Lock ordering, if required  Object.identityHashCode() method 25
  • 26. 5.1 Deadlock Banking example revisited public void transferMoney(Account fromAccn, Account toAccn,Amount amnt) { Account firstLck, secondLck; if (fromAccn.accountNumber() < toAccn.accountNumber()) { firstLck = fromAccn; secondLck = toAccn; } else { firstLck = toAccn; secondLck = fromAccn; } 26
  • 27. 5.1 Deadlock synchronized (firstLck) { synchronized (secondLck) { if (fromAccn.hasSufficientBalance(amnt){ fromAccn.debit(amnt); toAccn.credit(amnt); } } } } 27
  • 28. 6. Synchronization Optimization JVM optimizes synchronization [under the hood]:  Lock Elision  Biased Locking  Lock Coarsening  Thread Spinning vs Thread Suspending 28
  • 29. 6.1 Synchronization Optimization  Lock Elision :: Locks on local scope references can be elided public String concatBuffer(String s1,String s2,String s3) { StringBuffer sb = new StringBuffer(); sb.append(s1); sb.append(s2); sb.append(s3); return sb.toString(); } 29
  • 30. 6.2 Synchronization Optimization • Biased Locking :: Most locks are never accessed by more than one thread during their life time  Release the lease only if another thread attempts to acquire the same lock  Default in Java 6 Hotspot/JIT 30
  • 31. 6.3 Synchronization Optimization  Lock coarsening :: Adjacent synchronized blocks may be merged into one synchronized block public static String concatToBuffer(StringBuffer sb, String s1, String s2, String s3) { sb.append(s1); sb.append(s2); sb.append(s3); return sb.toString();} 31
  • 32. 6.4 Synchronization Optimization  Thread Suspending vs Thread Spinning  In 1.4.2, spin for (default value of) 10 iterations before being suspended  Adaptive Spinning  Introduced in 1.6  Spin duration based on the previous spin attempts and state of the lock owner 32
  • 33. 7.1 Latches  Latches allows one or more threads to wait until a set of operations being performed in other threads completes.  When N concurrent sub-tasks occur, the coordinating thread will wait until each sub- task is executed 33
  • 34. 7.1 Latches class TestLatch { final CountDownLatch latch = new CountDownLatch(3); class myThread extends Thread { public void run() { task.run(); latch.countDown()}} public static void main (String[] args){ TestLatch tst = new TestLatch(); tst.new myThread().start(); tst.new myThread().start(); tst.new myThread().start(); latch.await();//Thread execution completed}} 34
  • 35. 7.2 Barriers  Barrier allows a set of threads to wait for each other at a common barrier point.  When Barrier point occurs all the threads waiting on it are released and run() method of Barrier object is called. class TestBarrier { final static int no_of_engines = 4; Runnable task = new Runnable() { public void run() { flyplane() }} 35
  • 36. 7.2 Barriers final CyclicBarrier barrier = new CyclicBarrier(no_of_engines,task); class Worker implements Runnable { public void run() { startEngine(); barrier.await();} } public static void main(String[] args) { TestBarrier flight = new TestBarrier (); for (int i = 0; i < no_of_engines; ++i) new Thread(flight.new Worker(i)).start(); }} 36
  • 37. References  https://www6.software.ibm.com/developerwor ks/education/j-concur/index.html  http://www.infoq.com/articles/java-threading- optimizations-p1  http://www.infoq.com/presentations/goetz- concurrency-past-present 37
  • 38. Q&A 38