SlideShare uma empresa Scribd logo
1 de 36
Effective Java - Concurrency


                 fli@telenav.cn
The scope of the topic



                                      Multiply-Thread
                      Concurrency




Multiply-Core   Parallel      Distributed     Multiply-Box
                                              (Process/JVM)
The scope of the topic




                              Scala
                       ….

                   Concurrency
                                      Erlang
                     java
                                CSP




             Multiply-Thread Programming in java
Outline

 Warm-up
    Counter
 What’s concurrency programming
    Shared Data/Coordination : safe(correctness)
    Performance : scalability
 After JDK5 concurrency
    Lock
    Synchronizers
    Executor/Concurrent Collections/ Atomic
 Why it’s hard
    Java Memory Model
Warm-up

     Counter
@NotThreadSafe
public class Counter {
        private int count = 0; //shared data

         public void increment() {
                count++;
         }

         public int getCount() {
                return count;
         }
}
                     Thread A: Retrieve c =0 .
                     Thread B: Retrieve c = 0 .
                     Thread A: Increment retrieved value; result is 1.
                     Thread B: Increment retrieved value; result is 1.
                     Thread A: Store result in c; c is now 1.
                     Thread B: Store result in c; c is now 1.
Warm-up

     Counter
@NotThreadSafe
public class Counter {
        private int count = 0; //shared data

         public synchronized void increment() {//write protected by lock
                count++;
         }

         public int getCount() {
                return count;
         }
}
Warm-up

     Counter
@ThreadSafe
public class Counter {
        private int count = 0; //shared data

         public synchronized void increment() {
                count++;
         }

         public synchronized int getCount() {
                return count;
         }
}

           get need to be synchronized for the class to be thread-safe,
           to ensure that no updates are lost,and that all threads see
            the most recent value of the counter. (Visibility)
Warm-up

     Counter
@ThreadSafe
public class Counter {
        private volatile int count = 0; //shared data

         public synchronized void increment() {
                count++;
         }

         public int getCount() {
                return count;
         }
}

        uses volatile to guarantee the visibility of the current result
        where locks(synchronzied)only allow one thread to access a value at once,
        volatile reads allow more than one, you get a higher degree of sharing
What’s concurrency programming

 Why concurrency (purpose)
    Multitasking, Exploit multiple cores or CPUs
    Multi-threading good for blocking for I/O or other blocking ops
 Concurrency programming
    Shared Data between threads
    Coordination between threads
    Avoid performance even poor than non-concurrent program
What’s concurrency programming

 Shared Data
      Lock/Mutual
      Atomicity
      Visibility
      Safe Publication
 Coordination
    Wait/Notify
 Performance(scalable)
    Lock contention
What’s concurrency programming

•    Atomicity
     •   Check-then-act

          if (foo != null) // Another thread could set foo to null
             foo.doSomething();

                                       •synchronized
                                       •ConcurrentHashMap.putIfAbsent lock

     •   Read-modify-write


          ++numRequests; // Really three separate actions even if volatile



                                        •synchronized
                                        •AtomicInteger.getAndSet     cmpxchgl
What’s concurrency programming

•    Visibility
                            Never-Stop Thread, windows JDK6: java –server StopThread
@NotThreadSafe
public class StopThread
{
           private static boolean stopRequested;

            public static void main(String[] args) throws InterruptedException
            {
                      Thread backgroudThread = new Thread(new Runnable() {
                               public void run()
                               {
                                         int i = 0;
                                         while (!stopRequested)
                                                   i++;
                               }
                      });
                      backgroudThread.start();

                     TimeUnit.SECONDS.sleep(1);
                     stopRequested = true;
                                                                  //Compiler Optimization
                                                                  if (!stopRequested)
            }                                                         while(true)
}                                                                            i++;
What’s concurrency programming

•    Visibility

@ThreadSafe
public class StopThread
{
            private static   volatile   boolean stopRequested;

            public static void main(String[] args) throws InterruptedException
            {
                      Thread backgroundThread = new Thread(new Runnable() {
                               public void run()
                               {
                                         int i = 0;
                                         while (!stopRequested)
                                                   i++;
                               }
                      });
                      backgroundThread.start();

                     TimeUnit.SECONDS.sleep(1);
                     stopRequested = true;

            }
}
                                 What’s volatile ?
What’s concurrency programming
•      Visibility : volatile

    JLS 8.3.1.4 volatile Fields
    A field may be declared volatile, in which case the Java memory model (§17)
    ensures that all threads see a consistent value for the variable.

    JLS 17.4.4 Synchronization Order
    A write to a volatile variable (§8.3.1.4) v synchronizes-with all subsequent
    reads of v by any thread (where subsequent is defined according to the
    synchronization order).

    JLS 17.4.5 Happens-before Order
    If one action happens-before another, then the first is visible to and
    ordered before the second.

    If an action x synchronizes-with a following action y, then we also have
    hb(x, y).

                                       Under Hook: Memory Barrier
What’s concurrency programming

     Safe Publication : final

class FinalFieldExample {
     final int x;
     int y;
     static FinalFieldExample f;
     public FinalFieldExample(){                 Re-order
            x = 3;                               it's quite natural to store a pointer to a
            y = 4;
      }                                          block of memory, and then advance the
                                                 pointer as you're writing data to that block
      static void writer() {
             f = new FinalFieldExample();
       }

      static void reader() {
              if (f != null) {
                     int i = f.x; // guaranteed to see 3
                     int j = f.y; // could see 0
              }
       }

      ...
}
What’s concurrency programming

     Safe Publication : final

class FinalFieldExample {
     final int x;                            Allocate Memory           Allocate Memory
     int y;
     static FinalFieldExample f;
     public FinalFieldExample(){               Filed initiation          Filed initiation
            x = 3;
            y = 4;
      }                                     Execute Constructor         Assign variable
      static void writer() {
             f = new FinalFieldExample();     Assign variable         Execute Constructor
       }

      static void reader() {
              if (f != null) {
                     int i = f.x; // guaranteed to see 3
                     int j = f.y; // could see 0
              }
       }                                Single-Thread,  re-order does not matter
      ...                               1) Thread1.writer() //the java statement is finished
}                                       2) Thread1.reader()
                                        If Multiply-Thread, re-order may be the evil
                                        1) Thread1.writer() Thread2.reader()
What’s concurrency programming

     Safe Publication : final

class FinalFieldExample {
     final int x;                                    What’s final ?
     int y;
     static FinalFieldExample f;
     public FinalFieldExample(){
            x = 3;
            y = 4;
      }

      static void writer() {
             f = new FinalFieldExample();
       }

      static void reader() {
              if (f != null) {
                     int i = f.x; // guaranteed to see 3
                     int j = f.y; // could see 0
              }
       }

      ...
}
What’s concurrency programming
•      Safe Publication : final

    JLS 8.3.1.2 final Fields
    A blank final instance variable must be definitely assigned (§16.9) at the end
    of every constructor (§8.8) of the class in which it is declared;
    otherwise a compile-time error occurs.

    17.5.1 Semantics of Final Fields
    The semantics for final fields are as follows. Let o be an object, and c be
    a constructor for o in which f is written. A freeze action on a final field f of o
    takes place when c exits, either normally or abruptly.
    JLS 17.5.3 Subsequent Modification of Final Fields
    An implementation may provide a way to execute a block of code in a
    final field safe context. If an object is constructed within a final field
    safe context, the reads of a final field of that object will not be reordered
    with modifications of that final field that occur within that final field safe
    context.
What’s concurrency programming

 Safe Publication : Double-Checked Locking

// Broken multithreaded version "Double-Checked Locking" idiom
class Foo {
     private Helper helper = null;
     public Helper getHelper() {
            if (helper == null)
                 synchronized(this) {
                        if (helper == null)
                                helper = new Helper();
             }
         return helper;
      }
      //    other functions and members...
}
What’s concurrency programming

 Safe Publication : Double-Checked Locking

@ThreadSafe
class Foo {
     private volatile Helper helper = null;
     public Helper getHelper() {
            if (helper == null)
                 synchronized(this) {
                        if (helper == null)
                                helper = new Helper();
             }
         return helper;
      }
      //    other functions and members...
}
What’s concurrency programming

 Safe Publication : Double-Checked Locking


     @ThreadSafe // use class initialization
     class HelperSingleton {
               static Helper singleton = new Helper();
     }




 @ThreadSafe // Lazy load
 class Foo {
           private static class HelperHolder {
                     public static Helper helper = new Helper();
           }

             public static Helper getHelper() {
                       return HelperHolder.helper;
             }
 }
What’s concurrency programming

 Safe Publication : Double-Checked Locking


     @ThreadSafe
     class Foo {
                   private volatile Helper helper = null;
                   public Helper getHelper() {
                       Helper result = helper; //local variable, for better performance
                       if (result == null) {
                           synchronized(this) {
                               result = helper;
                               if (result == null) {
                                   helper = result = new Helper();
                               }
                           }
                       }
                       return result;
                   }

                   // other functions and members...
              }




                   Variant of DDL, each has it’s own standard point
What’s concurrency programming

     Safe Publication

    public class Cache {
            private final Thread cleanerThread;
            public Cache() {
                  cleanerThread = new Thread(new Cleaner(this));        // this escapes again!
                  cleanerThread.start();
                  // ….
             }

                // Clean will call back to this method
                public void cleanup() { // clean up Cache }
    }


//Careful progmramming                                        //FactoryMethod Pattern
@ThreadSafe                                                   @ThreadSafe
public Cache() {                                              public class Cache {
    cleanerThread = new Thread(new Cleaner(this);             // ...
                                                                   public static Cache newCache() {
        // ….                                                           Cache cache = new Cache();
                                                                        cache.startCleanerThread();
        cleanerThread.start();   //last statement                       return cache;
        }                                                            }
}                                                             }


                                            More safely published method (see book JCIP)
What’s concurrency programming

  Cooperation: Object.wait and notify


//Standard   Idiom for using the wait method
final Object obj = new Object(); // Do not change your lock object refrence

//Thread 1
synchronized(obj) {   // You must synchronize.
    while(! someCondition()) // Always wait in a loop.
         {
            obj.wait(); //Release lock, and reacquires on wakeup
         }
}
// Thread 2
synchronized(obj) { // Synchronize here too!
     satisfyCondition();
     obj.notifyAll();
}
What’s concurrency programming

•    Performance
     •   Lock contention
          –   Multiply-Thread acquires and wait for 1 lock
          –   Starvation
     •   DeadLock /LiveLock
          –   DeadLock : both are waiting the other to release resources
          –   LiveLock : both are run-able and no one make progress
     •   Spin Lock
          –   Check and Sleep, wasting cpu cycle
 Reduce Lock contention
     •   Use local variables or thread-local storage (Careful  memory leak)
     •   Get rid of expensive calculations while in locks
     •   Lock striping (ConcurrentHashMap)
     •   atomic operations/
     •   Reader-Writer Locks
     •   Avoid Object-pooling (Object-creation is expensive)
     •   Avoid hotspots
JDK5 Concurrency

 Lock
Java provides basic locking via synchronized
Good for many situations, but some issues
      Single monitor per object (single wait/notify condition)
      Not possible to interrupt thread waiting for lock
      Not possible to time-out when waiting for a lock
      Block structured approach
        • Acquiring multiple locks is complex
        • Advanced techniques not possible
               synchronized             Lock
               Acquire_Lock_1           Acquire_Lock_1
                 Acquire_Lock_2         Acquire_Lock_2
                 Release_Lock_2         Release_Lock_1
               Release_Lock_1           Release_Lock_2


 New Lock interface addresses these issues
JDK5 Concurrency

 Lock

     void lock()
                        Acquires the lock.
     void
            lockInterruptibly()
                      Acquires the lock unless the current thread is interrupted.

Condition
            newCondition()
                      Returns a new Condition instance that is bound to this Lock instance.

 boolean
            tryLock()
                        Acquires the lock only if it is free at the time of invocation.

 boolean
            tryLock(long time, TimeUnit unit)
                      Acquires the lock if it is free within the given waiting time and the
            current thread has not been interrupted.


     void unlock()
                        Releases the lock.
JDK5 Concurrency

 ReentrantLock
    Rentrant means lock holder reacquire the lock: e.g recur method

    Lock l = new ReentrantLock();
    l.lock();
    try {
            // access the resource protected by this lock
    }
    finally {
        l.unlock();
    }




 ReentrantReadWriteLock
    Lock downgrading. Upgrading is not allowed
       • Release read lock first , acquire write lock
       • Writer starvation ?
JDK5 Concurrency

 Condition (Object.wait and notify in explicit lock)
 private final Lock lock = new ReentrantLock();
 private final Condition condition = lock.newCondition();

 public void waitTillChange() {
     lock.lock();
     try {
         while(! someCondition()) condition.await();
     } finally {
        lock.unlock();
     }
 }
 public void change() {
     lock.lock();
     try {
        satisfyCondition();
        condition.signalAll();
     } finally {
      lock.unlock();
     }
 }
JDK5 Concurrency

•    Synchronizers (Higher-level concurrency utilities to Object.wait and notify)
     •   Semaphore
     •   CountDownLatch
          –   Spawn sub-worker and wait for sub-worker
              E.g getAds, spawn 3 worker to get ads from different vendor
                     getAdsFromCitySearch
                     getAdsFromGoogle
                     getAdsFromTeleNav
     •   CyclicBarrier
     •   Exchanger
     •   Phaser (1.7)
     •   ForkJoinPool (1.7)
JDK5 Concurrency

•    Executor/Concurrent Collections/ Atomic

     •    BlockingQueue (producer-consumer queues)

                           Throws
                                       Special value      Blocks        Times out
                          exception
                                                                      offer(e, time,
         Insert         add(e)         offer(e)        put(e)
                                                                      unit)
                                                                      poll(time,
         Remove         remove()       poll()          take()
                                                                      unit)
         Examine        element()      peek()          not applicable not applicable




                   A lot of things are not covered today, worth to explore and use …
Why it’s hard

 The “evil”
    Cache Coherency
       • Processor /Memory
           – A CPU does not always fetch memory values from RAM
       • Processor/Processor




    Reordering
       • Processor : rearrange the execution order of machine instructions
       • Compiler Optimizations : rearrange the order of the statement
       • Memory : rearrange the order in which writes are committed to memory cells
Why it’s hard

 Ordering


       within-thread
       From the point of view of the thread performing the actions in a
       method, instructions proceed in the normal as-if-serial manner that
       applies in sequential programming languages.

       between-thread
       From the point of view of other threads that might be "spying" on
       this thread by concurrently running unsynchronized methods,
       almost anything can happen. The only useful constraint is that the
       relative orderings of synchronized methods and blocks, as well as
       operations on volatile fields, are always preserved
Why it’s hard

 Java Memory Model
    address three intertwined issues
       • Atomicity
       • Visibility
       • Ordering
    Notation
       • Program orders (Intra-Thread)
       • Synchronize-with
       • Happen-Before (HB)
            – synchronized
            – volatile
            – final
References

 http://www.slideshare.net/sjlee0/robust-and-scalable-concurrent-
  programming-lesson-from-the-trenches
 http://www.slideshare.net/caroljmcdonald/java-concurrency-memory-
  model-and-trends-4961797
 http://www.slideshare.net/alexmiller/java-concurrency-gotchas-3666977
 Effective Java

Mais conteúdo relacionado

Mais procurados

Java 5 concurrency
Java 5 concurrencyJava 5 concurrency
Java 5 concurrencypriyank09
 
Java 8 - Stamped Lock
Java 8 - Stamped LockJava 8 - Stamped Lock
Java 8 - Stamped LockHaim Yadid
 
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...Sachintha Gunasena
 
Inter threadcommunication.38
Inter threadcommunication.38Inter threadcommunication.38
Inter threadcommunication.38myrajendra
 
Java concurrency
Java concurrencyJava concurrency
Java concurrencyducquoc_vn
 
Inter thread communication & runnable interface
Inter thread communication & runnable interfaceInter thread communication & runnable interface
Inter thread communication & runnable interfacekeval_thummar
 
Actor Concurrency
Actor ConcurrencyActor Concurrency
Actor ConcurrencyAlex Miller
 
Concurrency in Java
Concurrency in  JavaConcurrency in  Java
Concurrency in JavaAllan Huang
 
Qt Framework Events Signals Threads
Qt Framework Events Signals ThreadsQt Framework Events Signals Threads
Qt Framework Events Signals ThreadsNeera Mital
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronizationpriyabogra1
 
Clojure concurrency
Clojure concurrencyClojure concurrency
Clojure concurrencyAlex Navis
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with javaHoang Nguyen
 
Grand Central Dispatch
Grand Central DispatchGrand Central Dispatch
Grand Central Dispatchcqtt191
 
Java multi threading
Java multi threadingJava multi threading
Java multi threadingRaja Sekhar
 
[Java concurrency]01.thread management
[Java concurrency]01.thread management[Java concurrency]01.thread management
[Java concurrency]01.thread managementxuehan zhu
 
Blocks & GCD
Blocks & GCDBlocks & GCD
Blocks & GCDrsebbe
 

Mais procurados (20)

Java 5 concurrency
Java 5 concurrencyJava 5 concurrency
Java 5 concurrency
 
The Java memory model made easy
The Java memory model made easyThe Java memory model made easy
The Java memory model made easy
 
Java 8 - Stamped Lock
Java 8 - Stamped LockJava 8 - Stamped Lock
Java 8 - Stamped Lock
 
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
 
Inter threadcommunication.38
Inter threadcommunication.38Inter threadcommunication.38
Inter threadcommunication.38
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Inter thread communication & runnable interface
Inter thread communication & runnable interfaceInter thread communication & runnable interface
Inter thread communication & runnable interface
 
Actor Concurrency
Actor ConcurrencyActor Concurrency
Actor Concurrency
 
Concurrency in Java
Concurrency in  JavaConcurrency in  Java
Concurrency in Java
 
Qt Framework Events Signals Threads
Qt Framework Events Signals ThreadsQt Framework Events Signals Threads
Qt Framework Events Signals Threads
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronization
 
04 threads
04 threads04 threads
04 threads
 
Clojure concurrency
Clojure concurrencyClojure concurrency
Clojure concurrency
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Thread
ThreadThread
Thread
 
Grand Central Dispatch
Grand Central DispatchGrand Central Dispatch
Grand Central Dispatch
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
 
[Java concurrency]01.thread management
[Java concurrency]01.thread management[Java concurrency]01.thread management
[Java concurrency]01.thread management
 
Blocks & GCD
Blocks & GCDBlocks & GCD
Blocks & GCD
 

Destaque

Dzone core java concurrency -_
Dzone core java concurrency -_Dzone core java concurrency -_
Dzone core java concurrency -_Surendra Sirvi
 
Working With Concurrency In Java 8
Working With Concurrency In Java 8Working With Concurrency In Java 8
Working With Concurrency In Java 8Heartin Jacob
 
Modern Java Concurrency
Modern Java ConcurrencyModern Java Concurrency
Modern Java ConcurrencyBen Evans
 
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
 
Java c человеческим (и даже богатым) лицом / Филипп Дельгядо
Java c человеческим (и даже богатым) лицом / Филипп ДельгядоJava c человеческим (и даже богатым) лицом / Филипп Дельгядо
Java c человеческим (и даже богатым) лицом / Филипп ДельгядоOntico
 
Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Martin Toshev
 
Concurrency: Best Practices
Concurrency: Best PracticesConcurrency: Best Practices
Concurrency: Best PracticesIndicThreads
 
Robust and Scalable Concurrent Programming: Lesson from the Trenches
Robust and Scalable Concurrent Programming: Lesson from the TrenchesRobust and Scalable Concurrent Programming: Lesson from the Trenches
Robust and Scalable Concurrent Programming: Lesson from the TrenchesSangjin Lee
 
Legend of Java Concurrency/Parallelism
Legend of Java Concurrency/ParallelismLegend of Java Concurrency/Parallelism
Legend of Java Concurrency/ParallelismYuichi Sakuraba
 
More Than Java Concurrency
More Than Java ConcurrencyMore Than Java Concurrency
More Than Java ConcurrencyFuqiang Wang
 
Concurrency & Parallel Programming
Concurrency & Parallel ProgrammingConcurrency & Parallel Programming
Concurrency & Parallel ProgrammingRamazan AYYILDIZ
 
Parallel Programming in .NET
Parallel Programming in .NETParallel Programming in .NET
Parallel Programming in .NETSANKARSAN BOSE
 
Java Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyJava Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyAnton Keks
 
Realtime Apache Hadoop at Facebook
Realtime Apache Hadoop at FacebookRealtime Apache Hadoop at Facebook
Realtime Apache Hadoop at Facebookparallellabs
 
Java concurrency in practice
Java concurrency in practiceJava concurrency in practice
Java concurrency in practiceMikalai Alimenkou
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Javaparag
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaRaghu nath
 

Destaque (17)

Dzone core java concurrency -_
Dzone core java concurrency -_Dzone core java concurrency -_
Dzone core java concurrency -_
 
Working With Concurrency In Java 8
Working With Concurrency In Java 8Working With Concurrency In Java 8
Working With Concurrency In Java 8
 
Modern Java Concurrency
Modern Java ConcurrencyModern Java Concurrency
Modern Java Concurrency
 
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
 
Java c человеческим (и даже богатым) лицом / Филипп Дельгядо
Java c человеческим (и даже богатым) лицом / Филипп ДельгядоJava c человеческим (и даже богатым) лицом / Филипп Дельгядо
Java c человеческим (и даже богатым) лицом / Филипп Дельгядо
 
Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Concurrency Utilities in Java 8
Concurrency Utilities in Java 8
 
Concurrency: Best Practices
Concurrency: Best PracticesConcurrency: Best Practices
Concurrency: Best Practices
 
Robust and Scalable Concurrent Programming: Lesson from the Trenches
Robust and Scalable Concurrent Programming: Lesson from the TrenchesRobust and Scalable Concurrent Programming: Lesson from the Trenches
Robust and Scalable Concurrent Programming: Lesson from the Trenches
 
Legend of Java Concurrency/Parallelism
Legend of Java Concurrency/ParallelismLegend of Java Concurrency/Parallelism
Legend of Java Concurrency/Parallelism
 
More Than Java Concurrency
More Than Java ConcurrencyMore Than Java Concurrency
More Than Java Concurrency
 
Concurrency & Parallel Programming
Concurrency & Parallel ProgrammingConcurrency & Parallel Programming
Concurrency & Parallel Programming
 
Parallel Programming in .NET
Parallel Programming in .NETParallel Programming in .NET
Parallel Programming in .NET
 
Java Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyJava Course 10: Threads and Concurrency
Java Course 10: Threads and Concurrency
 
Realtime Apache Hadoop at Facebook
Realtime Apache Hadoop at FacebookRealtime Apache Hadoop at Facebook
Realtime Apache Hadoop at Facebook
 
Java concurrency in practice
Java concurrency in practiceJava concurrency in practice
Java concurrency in practice
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Java
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 

Semelhante a Effective java - concurrency

Java concurrency begining
Java concurrency   beginingJava concurrency   begining
Java concurrency beginingmaksym220889
 
.NET Multithreading and File I/O
.NET Multithreading and File I/O.NET Multithreading and File I/O
.NET Multithreading and File I/OJussi Pohjolainen
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/MultitaskingSasha Kravchuk
 
Medical Image Processing Strategies for multi-core CPUs
Medical Image Processing Strategies for multi-core CPUsMedical Image Processing Strategies for multi-core CPUs
Medical Image Processing Strategies for multi-core CPUsDaniel Blezek
 
Java synchronizers
Java synchronizersJava synchronizers
Java synchronizersts_v_murthy
 
Java and the machine - Martijn Verburg and Kirk Pepperdine
Java and the machine - Martijn Verburg and Kirk PepperdineJava and the machine - Martijn Verburg and Kirk Pepperdine
Java and the machine - Martijn Verburg and Kirk PepperdineJAX London
 
Java 7 JUG Summer Camp
Java 7 JUG Summer CampJava 7 JUG Summer Camp
Java 7 JUG Summer Campjulien.ponge
 
Java programming PPT. .pptx
Java programming PPT.                 .pptxJava programming PPT.                 .pptx
Java programming PPT. .pptxcreativegamerz00
 
Lec7!JavaThreads.ppt
Lec7!JavaThreads.pptLec7!JavaThreads.ppt
Lec7!JavaThreads.pptssuserec53e73
 
Threads and concurrency in Java 1.5
Threads and concurrency in Java 1.5Threads and concurrency in Java 1.5
Threads and concurrency in Java 1.5Peter Antman
 
Java 7 at SoftShake 2011
Java 7 at SoftShake 2011Java 7 at SoftShake 2011
Java 7 at SoftShake 2011julien.ponge
 
Core Java Programming Language (JSE) : Chapter XII - Threads
Core Java Programming Language (JSE) : Chapter XII -  ThreadsCore Java Programming Language (JSE) : Chapter XII -  Threads
Core Java Programming Language (JSE) : Chapter XII - ThreadsWebStackAcademy
 

Semelhante a Effective java - concurrency (20)

Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in Java
 
Concurrency gotchas
Concurrency gotchasConcurrency gotchas
Concurrency gotchas
 
Java concurrency begining
Java concurrency   beginingJava concurrency   begining
Java concurrency begining
 
.NET Multithreading and File I/O
.NET Multithreading and File I/O.NET Multithreading and File I/O
.NET Multithreading and File I/O
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/Multitasking
 
Medical Image Processing Strategies for multi-core CPUs
Medical Image Processing Strategies for multi-core CPUsMedical Image Processing Strategies for multi-core CPUs
Medical Image Processing Strategies for multi-core CPUs
 
concurrency_c#_public
concurrency_c#_publicconcurrency_c#_public
concurrency_c#_public
 
Java 7 LavaJUG
Java 7 LavaJUGJava 7 LavaJUG
Java 7 LavaJUG
 
Java synchronizers
Java synchronizersJava synchronizers
Java synchronizers
 
Java and the machine - Martijn Verburg and Kirk Pepperdine
Java and the machine - Martijn Verburg and Kirk PepperdineJava and the machine - Martijn Verburg and Kirk Pepperdine
Java and the machine - Martijn Verburg and Kirk Pepperdine
 
Java 7 JUG Summer Camp
Java 7 JUG Summer CampJava 7 JUG Summer Camp
Java 7 JUG Summer Camp
 
JAVA SE 7
JAVA SE 7JAVA SE 7
JAVA SE 7
 
Thread 1
Thread 1Thread 1
Thread 1
 
Java programming PPT. .pptx
Java programming PPT.                 .pptxJava programming PPT.                 .pptx
Java programming PPT. .pptx
 
Lec7!JavaThreads.ppt
Lec7!JavaThreads.pptLec7!JavaThreads.ppt
Lec7!JavaThreads.ppt
 
Lec7!JavaThreads.ppt
Lec7!JavaThreads.pptLec7!JavaThreads.ppt
Lec7!JavaThreads.ppt
 
Threads and concurrency in Java 1.5
Threads and concurrency in Java 1.5Threads and concurrency in Java 1.5
Threads and concurrency in Java 1.5
 
Java 7 at SoftShake 2011
Java 7 at SoftShake 2011Java 7 at SoftShake 2011
Java 7 at SoftShake 2011
 
Core Java Programming Language (JSE) : Chapter XII - Threads
Core Java Programming Language (JSE) : Chapter XII -  ThreadsCore Java Programming Language (JSE) : Chapter XII -  Threads
Core Java Programming Language (JSE) : Chapter XII - Threads
 
Introduction+To+Java+Concurrency
Introduction+To+Java+ConcurrencyIntroduction+To+Java+Concurrency
Introduction+To+Java+Concurrency
 

Mais de feng lee

Guice in athena
Guice in athenaGuice in athena
Guice in athenafeng lee
 
Bloom filter
Bloom filterBloom filter
Bloom filterfeng lee
 
Hadoop 安装
Hadoop 安装Hadoop 安装
Hadoop 安装feng lee
 
Axis2 client memory leak
Axis2 client memory leakAxis2 client memory leak
Axis2 client memory leakfeng lee
 
Mysql story in poi dedup
Mysql story in poi dedupMysql story in poi dedup
Mysql story in poi dedupfeng lee
 

Mais de feng lee (6)

Guice in athena
Guice in athenaGuice in athena
Guice in athena
 
Bloom filter
Bloom filterBloom filter
Bloom filter
 
Hadoop 安装
Hadoop 安装Hadoop 安装
Hadoop 安装
 
Axis2 client memory leak
Axis2 client memory leakAxis2 client memory leak
Axis2 client memory leak
 
Mysql story in poi dedup
Mysql story in poi dedupMysql story in poi dedup
Mysql story in poi dedup
 
Maven
MavenMaven
Maven
 

Último

Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 

Último (20)

Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 

Effective java - concurrency

  • 1. Effective Java - Concurrency fli@telenav.cn
  • 2. The scope of the topic Multiply-Thread Concurrency Multiply-Core Parallel Distributed Multiply-Box (Process/JVM)
  • 3. The scope of the topic Scala …. Concurrency Erlang java CSP Multiply-Thread Programming in java
  • 4. Outline  Warm-up  Counter  What’s concurrency programming  Shared Data/Coordination : safe(correctness)  Performance : scalability  After JDK5 concurrency  Lock  Synchronizers  Executor/Concurrent Collections/ Atomic  Why it’s hard  Java Memory Model
  • 5. Warm-up  Counter @NotThreadSafe public class Counter { private int count = 0; //shared data public void increment() { count++; } public int getCount() { return count; } } Thread A: Retrieve c =0 . Thread B: Retrieve c = 0 . Thread A: Increment retrieved value; result is 1. Thread B: Increment retrieved value; result is 1. Thread A: Store result in c; c is now 1. Thread B: Store result in c; c is now 1.
  • 6. Warm-up  Counter @NotThreadSafe public class Counter { private int count = 0; //shared data public synchronized void increment() {//write protected by lock count++; } public int getCount() { return count; } }
  • 7. Warm-up  Counter @ThreadSafe public class Counter { private int count = 0; //shared data public synchronized void increment() { count++; } public synchronized int getCount() { return count; } } get need to be synchronized for the class to be thread-safe, to ensure that no updates are lost,and that all threads see the most recent value of the counter. (Visibility)
  • 8. Warm-up  Counter @ThreadSafe public class Counter { private volatile int count = 0; //shared data public synchronized void increment() { count++; } public int getCount() { return count; } } uses volatile to guarantee the visibility of the current result where locks(synchronzied)only allow one thread to access a value at once, volatile reads allow more than one, you get a higher degree of sharing
  • 9. What’s concurrency programming  Why concurrency (purpose)  Multitasking, Exploit multiple cores or CPUs  Multi-threading good for blocking for I/O or other blocking ops  Concurrency programming  Shared Data between threads  Coordination between threads  Avoid performance even poor than non-concurrent program
  • 10. What’s concurrency programming  Shared Data  Lock/Mutual  Atomicity  Visibility  Safe Publication  Coordination  Wait/Notify  Performance(scalable)  Lock contention
  • 11. What’s concurrency programming • Atomicity • Check-then-act if (foo != null) // Another thread could set foo to null foo.doSomething(); •synchronized •ConcurrentHashMap.putIfAbsent lock • Read-modify-write ++numRequests; // Really three separate actions even if volatile •synchronized •AtomicInteger.getAndSet cmpxchgl
  • 12. What’s concurrency programming • Visibility Never-Stop Thread, windows JDK6: java –server StopThread @NotThreadSafe public class StopThread { private static boolean stopRequested; public static void main(String[] args) throws InterruptedException { Thread backgroudThread = new Thread(new Runnable() { public void run() { int i = 0; while (!stopRequested) i++; } }); backgroudThread.start(); TimeUnit.SECONDS.sleep(1); stopRequested = true; //Compiler Optimization if (!stopRequested) } while(true) } i++;
  • 13. What’s concurrency programming • Visibility @ThreadSafe public class StopThread { private static volatile boolean stopRequested; public static void main(String[] args) throws InterruptedException { Thread backgroundThread = new Thread(new Runnable() { public void run() { int i = 0; while (!stopRequested) i++; } }); backgroundThread.start(); TimeUnit.SECONDS.sleep(1); stopRequested = true; } } What’s volatile ?
  • 14. What’s concurrency programming • Visibility : volatile JLS 8.3.1.4 volatile Fields A field may be declared volatile, in which case the Java memory model (§17) ensures that all threads see a consistent value for the variable. JLS 17.4.4 Synchronization Order A write to a volatile variable (§8.3.1.4) v synchronizes-with all subsequent reads of v by any thread (where subsequent is defined according to the synchronization order). JLS 17.4.5 Happens-before Order If one action happens-before another, then the first is visible to and ordered before the second. If an action x synchronizes-with a following action y, then we also have hb(x, y). Under Hook: Memory Barrier
  • 15. What’s concurrency programming  Safe Publication : final class FinalFieldExample { final int x; int y; static FinalFieldExample f; public FinalFieldExample(){ Re-order x = 3; it's quite natural to store a pointer to a y = 4; } block of memory, and then advance the pointer as you're writing data to that block static void writer() { f = new FinalFieldExample(); } static void reader() { if (f != null) { int i = f.x; // guaranteed to see 3 int j = f.y; // could see 0 } } ... }
  • 16. What’s concurrency programming  Safe Publication : final class FinalFieldExample { final int x; Allocate Memory Allocate Memory int y; static FinalFieldExample f; public FinalFieldExample(){ Filed initiation Filed initiation x = 3; y = 4; } Execute Constructor Assign variable static void writer() { f = new FinalFieldExample(); Assign variable Execute Constructor } static void reader() { if (f != null) { int i = f.x; // guaranteed to see 3 int j = f.y; // could see 0 } } Single-Thread, re-order does not matter ... 1) Thread1.writer() //the java statement is finished } 2) Thread1.reader() If Multiply-Thread, re-order may be the evil 1) Thread1.writer() Thread2.reader()
  • 17. What’s concurrency programming  Safe Publication : final class FinalFieldExample { final int x; What’s final ? int y; static FinalFieldExample f; public FinalFieldExample(){ x = 3; y = 4; } static void writer() { f = new FinalFieldExample(); } static void reader() { if (f != null) { int i = f.x; // guaranteed to see 3 int j = f.y; // could see 0 } } ... }
  • 18. What’s concurrency programming • Safe Publication : final JLS 8.3.1.2 final Fields A blank final instance variable must be definitely assigned (§16.9) at the end of every constructor (§8.8) of the class in which it is declared; otherwise a compile-time error occurs. 17.5.1 Semantics of Final Fields The semantics for final fields are as follows. Let o be an object, and c be a constructor for o in which f is written. A freeze action on a final field f of o takes place when c exits, either normally or abruptly. JLS 17.5.3 Subsequent Modification of Final Fields An implementation may provide a way to execute a block of code in a final field safe context. If an object is constructed within a final field safe context, the reads of a final field of that object will not be reordered with modifications of that final field that occur within that final field safe context.
  • 19. What’s concurrency programming  Safe Publication : Double-Checked Locking // Broken multithreaded version "Double-Checked Locking" idiom class Foo { private Helper helper = null; public Helper getHelper() { if (helper == null) synchronized(this) { if (helper == null) helper = new Helper(); } return helper; } // other functions and members... }
  • 20. What’s concurrency programming  Safe Publication : Double-Checked Locking @ThreadSafe class Foo { private volatile Helper helper = null; public Helper getHelper() { if (helper == null) synchronized(this) { if (helper == null) helper = new Helper(); } return helper; } // other functions and members... }
  • 21. What’s concurrency programming  Safe Publication : Double-Checked Locking @ThreadSafe // use class initialization class HelperSingleton { static Helper singleton = new Helper(); } @ThreadSafe // Lazy load class Foo { private static class HelperHolder { public static Helper helper = new Helper(); } public static Helper getHelper() { return HelperHolder.helper; } }
  • 22. What’s concurrency programming  Safe Publication : Double-Checked Locking @ThreadSafe class Foo { private volatile Helper helper = null; public Helper getHelper() { Helper result = helper; //local variable, for better performance if (result == null) { synchronized(this) { result = helper; if (result == null) { helper = result = new Helper(); } } } return result; } // other functions and members... } Variant of DDL, each has it’s own standard point
  • 23. What’s concurrency programming  Safe Publication public class Cache { private final Thread cleanerThread; public Cache() { cleanerThread = new Thread(new Cleaner(this)); // this escapes again! cleanerThread.start(); // …. } // Clean will call back to this method public void cleanup() { // clean up Cache } } //Careful progmramming //FactoryMethod Pattern @ThreadSafe @ThreadSafe public Cache() { public class Cache { cleanerThread = new Thread(new Cleaner(this); // ... public static Cache newCache() { // …. Cache cache = new Cache(); cache.startCleanerThread(); cleanerThread.start(); //last statement return cache; } } } } More safely published method (see book JCIP)
  • 24. What’s concurrency programming  Cooperation: Object.wait and notify //Standard Idiom for using the wait method final Object obj = new Object(); // Do not change your lock object refrence //Thread 1 synchronized(obj) { // You must synchronize. while(! someCondition()) // Always wait in a loop. { obj.wait(); //Release lock, and reacquires on wakeup } } // Thread 2 synchronized(obj) { // Synchronize here too! satisfyCondition(); obj.notifyAll(); }
  • 25. What’s concurrency programming • Performance • Lock contention – Multiply-Thread acquires and wait for 1 lock – Starvation • DeadLock /LiveLock – DeadLock : both are waiting the other to release resources – LiveLock : both are run-able and no one make progress • Spin Lock – Check and Sleep, wasting cpu cycle  Reduce Lock contention • Use local variables or thread-local storage (Careful  memory leak) • Get rid of expensive calculations while in locks • Lock striping (ConcurrentHashMap) • atomic operations/ • Reader-Writer Locks • Avoid Object-pooling (Object-creation is expensive) • Avoid hotspots
  • 26. JDK5 Concurrency  Lock Java provides basic locking via synchronized Good for many situations, but some issues  Single monitor per object (single wait/notify condition)  Not possible to interrupt thread waiting for lock  Not possible to time-out when waiting for a lock  Block structured approach • Acquiring multiple locks is complex • Advanced techniques not possible synchronized Lock Acquire_Lock_1 Acquire_Lock_1 Acquire_Lock_2 Acquire_Lock_2 Release_Lock_2 Release_Lock_1 Release_Lock_1 Release_Lock_2  New Lock interface addresses these issues
  • 27. JDK5 Concurrency  Lock void lock() Acquires the lock. void lockInterruptibly() Acquires the lock unless the current thread is interrupted. Condition newCondition() Returns a new Condition instance that is bound to this Lock instance. boolean tryLock() Acquires the lock only if it is free at the time of invocation. boolean tryLock(long time, TimeUnit unit) Acquires the lock if it is free within the given waiting time and the current thread has not been interrupted. void unlock() Releases the lock.
  • 28. JDK5 Concurrency  ReentrantLock  Rentrant means lock holder reacquire the lock: e.g recur method Lock l = new ReentrantLock(); l.lock(); try { // access the resource protected by this lock } finally { l.unlock(); }  ReentrantReadWriteLock  Lock downgrading. Upgrading is not allowed • Release read lock first , acquire write lock • Writer starvation ?
  • 29. JDK5 Concurrency  Condition (Object.wait and notify in explicit lock) private final Lock lock = new ReentrantLock(); private final Condition condition = lock.newCondition(); public void waitTillChange() { lock.lock(); try { while(! someCondition()) condition.await(); } finally { lock.unlock(); } } public void change() { lock.lock(); try { satisfyCondition(); condition.signalAll(); } finally { lock.unlock(); } }
  • 30. JDK5 Concurrency • Synchronizers (Higher-level concurrency utilities to Object.wait and notify) • Semaphore • CountDownLatch – Spawn sub-worker and wait for sub-worker E.g getAds, spawn 3 worker to get ads from different vendor getAdsFromCitySearch getAdsFromGoogle getAdsFromTeleNav • CyclicBarrier • Exchanger • Phaser (1.7) • ForkJoinPool (1.7)
  • 31. JDK5 Concurrency • Executor/Concurrent Collections/ Atomic • BlockingQueue (producer-consumer queues) Throws Special value Blocks Times out exception offer(e, time, Insert add(e) offer(e) put(e) unit) poll(time, Remove remove() poll() take() unit) Examine element() peek() not applicable not applicable A lot of things are not covered today, worth to explore and use …
  • 32. Why it’s hard  The “evil”  Cache Coherency • Processor /Memory – A CPU does not always fetch memory values from RAM • Processor/Processor  Reordering • Processor : rearrange the execution order of machine instructions • Compiler Optimizations : rearrange the order of the statement • Memory : rearrange the order in which writes are committed to memory cells
  • 33. Why it’s hard  Ordering within-thread From the point of view of the thread performing the actions in a method, instructions proceed in the normal as-if-serial manner that applies in sequential programming languages. between-thread From the point of view of other threads that might be "spying" on this thread by concurrently running unsynchronized methods, almost anything can happen. The only useful constraint is that the relative orderings of synchronized methods and blocks, as well as operations on volatile fields, are always preserved
  • 34. Why it’s hard  Java Memory Model  address three intertwined issues • Atomicity • Visibility • Ordering  Notation • Program orders (Intra-Thread) • Synchronize-with • Happen-Before (HB) – synchronized – volatile – final
  • 35.
  • 36. References  http://www.slideshare.net/sjlee0/robust-and-scalable-concurrent- programming-lesson-from-the-trenches  http://www.slideshare.net/caroljmcdonald/java-concurrency-memory- model-and-trends-4961797  http://www.slideshare.net/alexmiller/java-concurrency-gotchas-3666977  Effective Java