SlideShare uma empresa Scribd logo
1 de 57
Baixar para ler offline
Java Concurrency
        Gotchas


           Alex Miller
Questions to answer

• What are common concurrency problems?
• Why are they problems?
• How do I detect these problems?
• How to I correct these problems?
Areas of Focus

• Shared Data
• Coordination
• Performance
Areas of Focus


                 {
                     • Locking
• Shared Data        • Visibility
                     • Atomicity
• Coordination
                     • Safe Publication
• Performance
Unprotected Field
     Access

              A



What happens if we modify data
      without locking?
Writer




Readers
          Shared state
Locking


  A
Shared Mutable Statics
public class MutableStatics {
                                           FORMAT is mutable
    private static final DateFormat FORMAT =
     DateFormat.getDateInstance(DateFormat.MEDIUM);

    public static Date parse(String str)
    throws ParseException {
      return FORMAT.parse(str);
    }                ...and this mutates it outside synchronization


    public static void main(String arg[])
    throws Exception {
      MutableStatics.parse(“Jan 1, 2000”);
    }
}
Shared mutable statics -
        instance per call
public class MutableStatics {

    public static Date parse(String str)
    throws ParseException {
      DateFormat format =
        DateFormat.getDateInstance(DateFormat.MEDIUM);
      return format.parse(str);
    }

    public static void main(String arg[])
    throws Exception {
      MutableStatics.parse(“Jan 1, 2000”);
    }
}
Shared mutable statics -
          ThreadLocal
public class MutableStatics {
  private static final ThreadLocal<DateFormat> FORMAT
     = new ThreadLocal<DateFormat>() {
       @Override protected DateFormat initialValue() {
         return DateFormat.getDateInstance(
                                    DateFormat.MEDIUM);
       }
  };

    public static Date parse(String str)
    throws ParseException {
      return FORMAT.get().parse(str);
    }
}
Common JDK Examples

Danger!        Safe

• DateFormat   • Random
• Calendar     • Pattern
• Matcher
Synchronization

private int myField;

synchronized( What goes here? ) {
  myField = 0;
}
DO NOT:
      synchronize on null
MyObject obj = null;

synchronized( obj ) { NullPointerException!
  // work
}
DO NOT:
                change instance
MyObject obj = new MyObject();

synchronized( obj ) {
  obj = new MyObject();
    no longer synchronizing
        on same object!
}
DO NOT:
  synch on string literals
private static final String LOCK = “LOCK”;
synchronized( LOCK ) {
  // work
                      What is the scope of LOCK?
}
DO NOT:
synch on autoboxed vals
private static final Integer LOCK = 0;
synchronized( LOCK ) { What is the scope of LOCK?
  // work
}
DO NOT:
synch on ReentrantLock
Lock lock = new ReentrantLock();
synchronized(lock) {
  // ...    Probably not what you meant here
}


Lock lock = new ReentrantLock();
lock.lock();
                  Probably more like this...
try {
  // ...
} finally {
  lock.unlock();
}
What should I lock on?
// The field you’re protecting
private final Map map = ...
synchronized(map) {
  // ...access map
}


// Explicit lock object
private final Object lock = new Object();
synchronized(lock) {
  // ...modify state
}
Visibility
Visibility problems
int x = 5;

Thread 1:
if(x == 5) {
   x = 10;
}

               Thread 2:
               System.out.println(x);
Visibility problems
volatile int x = 5;

Thread 1:
if(x == 5) {
   x = 10;
}

                      Thread 2:
                      System.out.println(x);
Inconsistent
           Synchronization
public class SomeData {
  private final Map data = new HashMap();

    public void set(String key, String value) {
      synchronized(data) {      Protecting writes
        data.put(key, value);
      }
    }

    public String get(String key) {
      return data.get(key);      ...but not reads
    }
}
Double-checked locking
public class Singleton {
  private static Singleton instance;

    public static Singleton getInstance() {
      if(instance == null) {     Attempt to avoid synchronization
        synchronized(Singleton.class) {
          if(instance == null) {
            instance = new Singleton();
          }
        }
      }
      return instance;
    }
}
Double-checked locking
public class Singleton {
  private static Singleton instance;

    public static Singleton getInstance() {
      if(instance == null) {                  READ
        synchronized(Singleton.class) {
          if(instance == null) {              READ
            instance = new Singleton();       WRITE
          }
        }
      }
      return instance;
    }
}
Double-checked locking
          - volatile
public class Singleton {
  private static volatile Singleton instance;

    public static Singleton getInstance() {
      if(instance == null) {
        synchronized(Singleton.class) {
          if(instance == null) {
            instance = new Singleton();
          }
        }
      }
      return instance;
    }
}
Double-checked locking
     - initialize on demand
public class Singleton {
  private static class SingletonHolder {
    private static final Singleton instance
        = new Singleton();
  }

    public static Singleton getInstance() {
      return SingletonHolder.instance;
    }
}
volatile arrays
public final class VolatileArray {

    private volatile boolean[] vals;

    public void flip(int i) {
                              Is the value of vals[i]
      vals[i] = true;         visible to other threads?
    }

    public boolean flipped(int i) {
      return vals[i];
    }
}
Atomicity
Volatile counter
public class Counter {

    private volatile int count;

    public int next() {
      return count++;     Looks atomic to me!
    }
}
AtomicInteger counter
public class Counter {

    private AtomicInteger count =
      new AtomicInteger();

    public int next() {
      return count.getAndIncrement();
    }                        Really atomic via
}                                encapsulation over
                                 multiple actions
Composing atomic actions
public Object putIfAbsent(
  Hashtable table, Object key, Object value) {
         Hashtable is
         thread-safe

    if(table.containsKey(key)) {                 READ
      // already present, return existing
      table.get(key);                            READ
      return null;

    } else {
      // doesn't exist, create new value         WRITE
      return table.put(key, value);
    }
}
Composing atomic actions
public Object putIfAbsent(
  Hashtable table, Object key, Object value) {
         Hashtable is
         thread-safe

    if(table.containsKey(key)) {                 READ
      // already present, return existing
      table.get(key);                            READ
      return null;

    } else {
      // doesn't exist, create new value         WRITE
      return table.put(key, value);
    }
}
Participate in lock
public Object putIfAbsent(
  Hashtable table, Object key, Object value) {
         Hashtable is
         thread-safe

    synchronized(table) {
      if(table.containsKey(key)) {
        table.get(key);
        return null;
      } else {
        return table.put(key, value);
      }
    }
}
Encapsulated compound
            actions
public Object putIfAbsent(
  ConcurrentHashMap table, Object key, Object value) {

    return table.putIfAbsent(key, value);
}
                                   Encpasulation FTW!
Assignment of
              64 bit values
public class LongAssignment {

    private long x;

    public void setLong(long val) {
      x = val;
                    Looks atomic to me,
    }
                      but is it?
}
Assignment of
    64 bit values - volatile
public class LongAssignment {

    private volatile long x;

    public void setLong(long val) {
      x = val;
    }

}
Safe publication
Listener in constructor
public interface DispatchListener {
  void newFare(Customer customer);
}

public class Taxi
  implements DispatchListener {

    public Taxi(Dispatcher dispatcher) {
      dispatcher.registerListener(this); We just published a
      // other initialization            reference to this...oops!
    }

    public void newFare(Customer customer) {
      // go to new customer’s location
    }
}
Starting thread
             in constructor
public class Cache {

    private final Thread cleanerThread;

    public Cache() {
      cleanerThread = new Thread(new Cleaner(this));
      cleanerThread.start();          this escapes again!
    }

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

    public static Cache newCache() {
      Cache cache = new Cache();
      cache.startCleanerThread();
      return cache;
    }
}
Areas of Focus

• Shared Data
• Coordination
• Performance
                 {   • Threads
                     • Wait/notify
Threads
• THOU SHALT NOT:
 • call Thread.stop() All monitors unlocked by ThreadDeath


 • call Thread.suspend() or Thread.resume()
                                      Can lead to deadlock



 • call Thread.destroy()     Not implemented (or safe)


 • call Thread.run()   Wonʼt start Thread! Still in caller Thread.


 • use ThreadGroups        Use a ThreadPoolExecutor instead.
wait/notify
// Thread 1
synchronized(lock) { You must synchronize.
  while(! someCondition()) { Always wait in a loop.
    lock.wait();
  }
}


// Thread 2
synchronized(lock) { Synchronize here too!
  satisfyCondition();
  lock.notifyAll();
}
Condition is similar
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();
  }                                   Condition is more
                                      flexible than wait/notify.
}
public void change() {
  lock.lock();
  try {
    satisfyCondition();
    condition.signalAll();
  } finally { lock.unlock(); } }
Areas of Focus

• Shared Data
• Coordination       • Deadlock
• Performance    {   • Spin wait
                     • Thread contention
Deadlock
// Thread 1
synchronized(lock1) {
  synchronized(lock2) {
    // stuff
  }
}
                          Classic deadlock.
// Thread 2
synchronized(lock2) {
  synchronized(lock1) {
    // stuff
  }
}
Deadlock avoidance

• Lock splitting
• Lock ordering
• Lock timeout
• tryLock
Spin wait
// Not efficient
private volatile boolean flag = false;

public void waitTillChange() {
  while(! flag) {
    Thread.sleep(100);      Spin on flag, waiting for
                            a change.
  }
}

public void change() {
  flag = true;
}
Replace with Condition
private final Lock lock = new ReentrantLock();
private final Condition condition = lock.newCondition();
private boolean flag = false;

public void waitTillChange() {
  lock.lock();
  try {
    while(! flag) condition.await();
  } finally {
    lock.unlock();                     Better but longer.
  }
}
public void change() {
  lock.lock();
  try {
    flag = true;
    condition.signalAll();
  } finally { lock.unlock(); } }
CountDownLatch
private final CountDownLatch latch =
  new CountDownLatch(1);

public void waitTillChange() {
  latch.await();
}

public void change() {
  latch.countDown();
                                  Coordination classes
}
                                  like CountDownLatch
                                  and CyclicBarrier cover
                                  many common uses
                                  better than Condition.
Lock contention
                         x




                      Hash f(x)




Bucket 0   Bucket 1           Bucket 2   Bucket 3
Lock striping
                                 x




                              Hash g(x)




           Hash f(x)                                 Hash f(x)




Bucket 0           Bucket 1               Bucket 0           Bucket 1
Final Exam
public class StatisticsImpl implements Statistics,
StatisticsImplementor {
  private long queryExecutionCount;

    public synchronized void queryExecuted(
                      String hql, int rows, long time) {
      queryExecutionCount++;
      // ... other stat collection
    }

    public long getQueryExecutionCount() {
      return queryExecutionCount;
    }

    public synchronized void clear() {
      queryExecutionCount = 0;
      // ... clear all other stats
    }
}
Final Exam
public class StatisticsImpl implements Statistics,
StatisticsImplementor {
  private long queryExecutionCount;
                     Single shared lock for ALL stat values
    public synchronized void queryExecuted(
                      String hql, int rows, long time) {
      queryExecutionCount++;
      // ... other stat collection
    }

    public long getQueryExecutionCount() {
      return queryExecutionCount;
                                  Read shared value             Non-atomic read
    }
                                            w/o synchronization of long value
    public synchronized void clear() {
      queryExecutionCount = 0;
                                     Race condition if reading
      // ... clear all other stats   stat and clearing
    }
}
Thanks...
Twitter       http://twitter.com/puredanger
Blog          http://tech.puredanger.com
Concurrency   http://concurrency.tumblr.com
links
              http://refcardz.dzone.com/refcardz/
Refcard
              core-java-concurrency
Slides        http://slideshare.net/alexmiller

Mais conteúdo relacionado

Mais procurados

Docker and Go: why did we decide to write Docker in Go?
Docker and Go: why did we decide to write Docker in Go?Docker and Go: why did we decide to write Docker in Go?
Docker and Go: why did we decide to write Docker in Go?Jérôme Petazzoni
 
Introduction to Kafka Streams
Introduction to Kafka StreamsIntroduction to Kafka Streams
Introduction to Kafka StreamsGuozhang Wang
 
Infrastructure as Code with Terraform and Ansible
Infrastructure as Code with Terraform and AnsibleInfrastructure as Code with Terraform and Ansible
Infrastructure as Code with Terraform and AnsibleDevOps Meetup Bern
 
Get started with gitops and flux
Get started with gitops and fluxGet started with gitops and flux
Get started with gitops and fluxLibbySchulze1
 
How to monitor your micro-service with Prometheus?
How to monitor your micro-service with Prometheus?How to monitor your micro-service with Prometheus?
How to monitor your micro-service with Prometheus?Wojciech Barczyński
 
Deep Dive into Kubernetes - Part 1
Deep Dive into Kubernetes - Part 1Deep Dive into Kubernetes - Part 1
Deep Dive into Kubernetes - Part 1Imesh Gunaratne
 
Ansible presentation
Ansible presentationAnsible presentation
Ansible presentationJohn Lynch
 
Comprehensive Terraform Training
Comprehensive Terraform TrainingComprehensive Terraform Training
Comprehensive Terraform TrainingYevgeniy Brikman
 
Microservices with Java, Spring Boot and Spring Cloud
Microservices with Java, Spring Boot and Spring CloudMicroservices with Java, Spring Boot and Spring Cloud
Microservices with Java, Spring Boot and Spring CloudEberhard Wolff
 
Apache Kafka 0.8 basic training - Verisign
Apache Kafka 0.8 basic training - VerisignApache Kafka 0.8 basic training - Verisign
Apache Kafka 0.8 basic training - VerisignMichael Noll
 
Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안
Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안
Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안SANG WON PARK
 
Comparing Native Java REST API Frameworks - Seattle JUG 2022
Comparing Native Java REST API Frameworks - Seattle JUG 2022Comparing Native Java REST API Frameworks - Seattle JUG 2022
Comparing Native Java REST API Frameworks - Seattle JUG 2022Matt Raible
 
Containers Anywhere with OpenShift by Red Hat
Containers Anywhere with OpenShift by Red HatContainers Anywhere with OpenShift by Red Hat
Containers Anywhere with OpenShift by Red HatAmazon Web Services
 
Apache Flink and what it is used for
Apache Flink and what it is used forApache Flink and what it is used for
Apache Flink and what it is used forAljoscha Krettek
 

Mais procurados (20)

Docker and Go: why did we decide to write Docker in Go?
Docker and Go: why did we decide to write Docker in Go?Docker and Go: why did we decide to write Docker in Go?
Docker and Go: why did we decide to write Docker in Go?
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
JHipster overview
JHipster overviewJHipster overview
JHipster overview
 
Introduction to Kafka Streams
Introduction to Kafka StreamsIntroduction to Kafka Streams
Introduction to Kafka Streams
 
Infrastructure as Code with Terraform and Ansible
Infrastructure as Code with Terraform and AnsibleInfrastructure as Code with Terraform and Ansible
Infrastructure as Code with Terraform and Ansible
 
Get started with gitops and flux
Get started with gitops and fluxGet started with gitops and flux
Get started with gitops and flux
 
DevSecOps: What Why and How : Blackhat 2019
DevSecOps: What Why and How : Blackhat 2019DevSecOps: What Why and How : Blackhat 2019
DevSecOps: What Why and How : Blackhat 2019
 
Introduction to docker
Introduction to dockerIntroduction to docker
Introduction to docker
 
How to monitor your micro-service with Prometheus?
How to monitor your micro-service with Prometheus?How to monitor your micro-service with Prometheus?
How to monitor your micro-service with Prometheus?
 
Ansible
AnsibleAnsible
Ansible
 
Deep Dive into Kubernetes - Part 1
Deep Dive into Kubernetes - Part 1Deep Dive into Kubernetes - Part 1
Deep Dive into Kubernetes - Part 1
 
Ansible presentation
Ansible presentationAnsible presentation
Ansible presentation
 
Comprehensive Terraform Training
Comprehensive Terraform TrainingComprehensive Terraform Training
Comprehensive Terraform Training
 
Microservices with Java, Spring Boot and Spring Cloud
Microservices with Java, Spring Boot and Spring CloudMicroservices with Java, Spring Boot and Spring Cloud
Microservices with Java, Spring Boot and Spring Cloud
 
Apache Kafka 0.8 basic training - Verisign
Apache Kafka 0.8 basic training - VerisignApache Kafka 0.8 basic training - Verisign
Apache Kafka 0.8 basic training - Verisign
 
Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안
Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안
Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안
 
Comparing Native Java REST API Frameworks - Seattle JUG 2022
Comparing Native Java REST API Frameworks - Seattle JUG 2022Comparing Native Java REST API Frameworks - Seattle JUG 2022
Comparing Native Java REST API Frameworks - Seattle JUG 2022
 
Springboot Microservices
Springboot MicroservicesSpringboot Microservices
Springboot Microservices
 
Containers Anywhere with OpenShift by Red Hat
Containers Anywhere with OpenShift by Red HatContainers Anywhere with OpenShift by Red Hat
Containers Anywhere with OpenShift by Red Hat
 
Apache Flink and what it is used for
Apache Flink and what it is used forApache Flink and what it is used for
Apache Flink and what it is used for
 

Destaque

Effective java - concurrency
Effective java - concurrencyEffective java - concurrency
Effective java - concurrencyfeng lee
 
Dzone core java concurrency -_
Dzone core java concurrency -_Dzone core java concurrency -_
Dzone core java concurrency -_Surendra Sirvi
 
[Java concurrency]01.thread management
[Java concurrency]01.thread management[Java concurrency]01.thread management
[Java concurrency]01.thread managementxuehan zhu
 
Caching In The Cloud
Caching In The CloudCaching In The Cloud
Caching In The CloudAlex Miller
 
Innovative Software
Innovative SoftwareInnovative Software
Innovative SoftwareAlex Miller
 
Releasing Relational Data to the Semantic Web
Releasing Relational Data to the Semantic WebReleasing Relational Data to the Semantic Web
Releasing Relational Data to the Semantic WebAlex Miller
 
Scaling Your Cache
Scaling Your CacheScaling Your Cache
Scaling Your CacheAlex Miller
 
Stream Execution with Clojure and Fork/join
Stream Execution with Clojure and Fork/joinStream Execution with Clojure and Fork/join
Stream Execution with Clojure and Fork/joinAlex Miller
 
Project Fortress
Project FortressProject Fortress
Project FortressAlex Miller
 
Groovy concurrency
Groovy concurrencyGroovy concurrency
Groovy concurrencyAlex Miller
 
Scaling Hibernate with Terracotta
Scaling Hibernate with TerracottaScaling Hibernate with Terracotta
Scaling Hibernate with TerracottaAlex Miller
 
Working With Concurrency In Java 8
Working With Concurrency In Java 8Working With Concurrency In Java 8
Working With Concurrency In Java 8Heartin Jacob
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in PracticeAlina Dolgikh
 
Java Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsJava Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsCarol McDonald
 
Cracking clojure
Cracking clojureCracking clojure
Cracking clojureAlex Miller
 
Clojure: The Art of Abstraction
Clojure: The Art of AbstractionClojure: The Art of Abstraction
Clojure: The Art of AbstractionAlex Miller
 
Modern Java Concurrency
Modern Java ConcurrencyModern Java Concurrency
Modern Java ConcurrencyBen Evans
 
Lessons from the intelligent investor
Lessons from the intelligent investorLessons from the intelligent investor
Lessons from the intelligent investorPamela Paikea
 

Destaque (20)

Effective java - concurrency
Effective java - concurrencyEffective java - concurrency
Effective java - concurrency
 
Dzone core java concurrency -_
Dzone core java concurrency -_Dzone core java concurrency -_
Dzone core java concurrency -_
 
[Java concurrency]01.thread management
[Java concurrency]01.thread management[Java concurrency]01.thread management
[Java concurrency]01.thread management
 
Blogging ZOMG
Blogging ZOMGBlogging ZOMG
Blogging ZOMG
 
Caching In The Cloud
Caching In The CloudCaching In The Cloud
Caching In The Cloud
 
Innovative Software
Innovative SoftwareInnovative Software
Innovative Software
 
Releasing Relational Data to the Semantic Web
Releasing Relational Data to the Semantic WebReleasing Relational Data to the Semantic Web
Releasing Relational Data to the Semantic Web
 
Scaling Your Cache
Scaling Your CacheScaling Your Cache
Scaling Your Cache
 
Cold Hard Cache
Cold Hard CacheCold Hard Cache
Cold Hard Cache
 
Stream Execution with Clojure and Fork/join
Stream Execution with Clojure and Fork/joinStream Execution with Clojure and Fork/join
Stream Execution with Clojure and Fork/join
 
Project Fortress
Project FortressProject Fortress
Project Fortress
 
Groovy concurrency
Groovy concurrencyGroovy concurrency
Groovy concurrency
 
Scaling Hibernate with Terracotta
Scaling Hibernate with TerracottaScaling Hibernate with Terracotta
Scaling Hibernate with Terracotta
 
Working With Concurrency In Java 8
Working With Concurrency In Java 8Working With Concurrency In Java 8
Working With Concurrency In Java 8
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in Practice
 
Java Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsJava Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and Trends
 
Cracking clojure
Cracking clojureCracking clojure
Cracking clojure
 
Clojure: The Art of Abstraction
Clojure: The Art of AbstractionClojure: The Art of Abstraction
Clojure: The Art of Abstraction
 
Modern Java Concurrency
Modern Java ConcurrencyModern Java Concurrency
Modern Java Concurrency
 
Lessons from the intelligent investor
Lessons from the intelligent investorLessons from the intelligent investor
Lessons from the intelligent investor
 

Semelhante a Java Concurrency Gotchas

Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency GotchasAlex Miller
 
Javaoneconcurrencygotchas 090610192215 Phpapp02
Javaoneconcurrencygotchas 090610192215 Phpapp02Javaoneconcurrencygotchas 090610192215 Phpapp02
Javaoneconcurrencygotchas 090610192215 Phpapp02Tarun Kumar
 
第1回 チキチキ『( ゜ェ゜)・;'.、ゴフッ』 - シングルトンパターン(Java)
第1回 チキチキ『( ゜ェ゜)・;'.、ゴフッ』 - シングルトンパターン(Java)第1回 チキチキ『( ゜ェ゜)・;'.、ゴフッ』 - シングルトンパターン(Java)
第1回 チキチキ『( ゜ェ゜)・;'.、ゴフッ』 - シングルトンパターン(Java)潤一 加藤
 
.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
 
From Runnable and synchronized To atomically() and parallel()
From Runnable and synchronized To atomically() and parallel()From Runnable and synchronized To atomically() and parallel()
From Runnable and synchronized To atomically() and parallel()José Paumard
 
3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в JavaDEVTYPE
 
Use of Apache Commons and Utilities
Use of Apache Commons and UtilitiesUse of Apache Commons and Utilities
Use of Apache Commons and UtilitiesPramod Kumar
 
Java 5 concurrency
Java 5 concurrencyJava 5 concurrency
Java 5 concurrencypriyank09
 
AST Transformations at JFokus
AST Transformations at JFokusAST Transformations at JFokus
AST Transformations at JFokusHamletDRC
 
Java осень 2012 лекция 2
Java осень 2012 лекция 2Java осень 2012 лекция 2
Java осень 2012 лекция 2Technopark
 
Ast transformations
Ast transformationsAst transformations
Ast transformationsHamletDRC
 
A linked stack is implemented using a standard Node class as follows.pdf
A linked stack is implemented using a standard Node class as follows.pdfA linked stack is implemented using a standard Node class as follows.pdf
A linked stack is implemented using a standard Node class as follows.pdfkisgstin23
 
Java concurrency begining
Java concurrency   beginingJava concurrency   begining
Java concurrency beginingmaksym220889
 
What’s new in C# 6
What’s new in C# 6What’s new in C# 6
What’s new in C# 6Fiyaz Hasan
 
using the code below create a method called getCollisionCount that w.pdf
using the code below create a method called getCollisionCount that w.pdfusing the code below create a method called getCollisionCount that w.pdf
using the code below create a method called getCollisionCount that w.pdfamirthagiftsmadurai
 

Semelhante a Java Concurrency Gotchas (20)

Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency Gotchas
 
Javaoneconcurrencygotchas 090610192215 Phpapp02
Javaoneconcurrencygotchas 090610192215 Phpapp02Javaoneconcurrencygotchas 090610192215 Phpapp02
Javaoneconcurrencygotchas 090610192215 Phpapp02
 
Concurrency gotchas
Concurrency gotchasConcurrency gotchas
Concurrency gotchas
 
第1回 チキチキ『( ゜ェ゜)・;'.、ゴフッ』 - シングルトンパターン(Java)
第1回 チキチキ『( ゜ェ゜)・;'.、ゴフッ』 - シングルトンパターン(Java)第1回 チキチキ『( ゜ェ゜)・;'.、ゴフッ』 - シングルトンパターン(Java)
第1回 チキチキ『( ゜ェ゜)・;'.、ゴフッ』 - シングルトンパターン(Java)
 
.NET Multithreading and File I/O
.NET Multithreading and File I/O.NET Multithreading and File I/O
.NET Multithreading and File I/O
 
From Runnable and synchronized To atomically() and parallel()
From Runnable and synchronized To atomically() and parallel()From Runnable and synchronized To atomically() and parallel()
From Runnable and synchronized To atomically() and parallel()
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java
 
Use of Apache Commons and Utilities
Use of Apache Commons and UtilitiesUse of Apache Commons and Utilities
Use of Apache Commons and Utilities
 
Java 5 concurrency
Java 5 concurrencyJava 5 concurrency
Java 5 concurrency
 
Scala in practice
Scala in practiceScala in practice
Scala in practice
 
AST Transformations at JFokus
AST Transformations at JFokusAST Transformations at JFokus
AST Transformations at JFokus
 
Java осень 2012 лекция 2
Java осень 2012 лекция 2Java осень 2012 лекция 2
Java осень 2012 лекция 2
 
Ast transformations
Ast transformationsAst transformations
Ast transformations
 
Thread
ThreadThread
Thread
 
04 threads
04 threads04 threads
04 threads
 
A linked stack is implemented using a standard Node class as follows.pdf
A linked stack is implemented using a standard Node class as follows.pdfA linked stack is implemented using a standard Node class as follows.pdf
A linked stack is implemented using a standard Node class as follows.pdf
 
Java concurrency begining
Java concurrency   beginingJava concurrency   begining
Java concurrency begining
 
What’s new in C# 6
What’s new in C# 6What’s new in C# 6
What’s new in C# 6
 
using the code below create a method called getCollisionCount that w.pdf
using the code below create a method called getCollisionCount that w.pdfusing the code below create a method called getCollisionCount that w.pdf
using the code below create a method called getCollisionCount that w.pdf
 

Mais de Alex Miller

Clojure/West Overview (12/1/11)
Clojure/West Overview (12/1/11)Clojure/West Overview (12/1/11)
Clojure/West Overview (12/1/11)Alex Miller
 
Concurrent Stream Processing
Concurrent Stream ProcessingConcurrent Stream Processing
Concurrent Stream ProcessingAlex Miller
 
Tree Editing with Zippers
Tree Editing with ZippersTree Editing with Zippers
Tree Editing with ZippersAlex Miller
 
Scaling Your Cache And Caching At Scale
Scaling Your Cache And Caching At ScaleScaling Your Cache And Caching At Scale
Scaling Your Cache And Caching At ScaleAlex Miller
 
Marshmallow Test
Marshmallow TestMarshmallow Test
Marshmallow TestAlex Miller
 
Strange Loop Conference 2009
Strange Loop Conference 2009Strange Loop Conference 2009
Strange Loop Conference 2009Alex Miller
 
Java Collections API
Java Collections APIJava Collections API
Java Collections APIAlex Miller
 
Java Concurrency Idioms
Java Concurrency IdiomsJava Concurrency Idioms
Java Concurrency IdiomsAlex Miller
 
Design Patterns Reconsidered
Design Patterns ReconsideredDesign Patterns Reconsidered
Design Patterns ReconsideredAlex Miller
 
Exploring Terracotta
Exploring TerracottaExploring Terracotta
Exploring TerracottaAlex Miller
 
Actor Concurrency
Actor ConcurrencyActor Concurrency
Actor ConcurrencyAlex Miller
 

Mais de Alex Miller (12)

Clojure/West Overview (12/1/11)
Clojure/West Overview (12/1/11)Clojure/West Overview (12/1/11)
Clojure/West Overview (12/1/11)
 
Concurrent Stream Processing
Concurrent Stream ProcessingConcurrent Stream Processing
Concurrent Stream Processing
 
Tree Editing with Zippers
Tree Editing with ZippersTree Editing with Zippers
Tree Editing with Zippers
 
Scaling Your Cache And Caching At Scale
Scaling Your Cache And Caching At ScaleScaling Your Cache And Caching At Scale
Scaling Your Cache And Caching At Scale
 
Marshmallow Test
Marshmallow TestMarshmallow Test
Marshmallow Test
 
Strange Loop Conference 2009
Strange Loop Conference 2009Strange Loop Conference 2009
Strange Loop Conference 2009
 
Java Collections API
Java Collections APIJava Collections API
Java Collections API
 
Java Concurrency Idioms
Java Concurrency IdiomsJava Concurrency Idioms
Java Concurrency Idioms
 
Design Patterns Reconsidered
Design Patterns ReconsideredDesign Patterns Reconsidered
Design Patterns Reconsidered
 
Java 7 Preview
Java 7 PreviewJava 7 Preview
Java 7 Preview
 
Exploring Terracotta
Exploring TerracottaExploring Terracotta
Exploring Terracotta
 
Actor Concurrency
Actor ConcurrencyActor Concurrency
Actor Concurrency
 

Último

Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
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
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
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
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
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
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
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
 
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
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 

Último (20)

Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
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
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
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
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
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
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
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
 
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
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 

Java Concurrency Gotchas

  • 1. Java Concurrency Gotchas Alex Miller
  • 2. Questions to answer • What are common concurrency problems? • Why are they problems? • How do I detect these problems? • How to I correct these problems?
  • 3. Areas of Focus • Shared Data • Coordination • Performance
  • 4. Areas of Focus { • Locking • Shared Data • Visibility • Atomicity • Coordination • Safe Publication • Performance
  • 5. Unprotected Field Access A What happens if we modify data without locking?
  • 6.
  • 7. Writer Readers Shared state
  • 9. Shared Mutable Statics public class MutableStatics { FORMAT is mutable private static final DateFormat FORMAT = DateFormat.getDateInstance(DateFormat.MEDIUM); public static Date parse(String str) throws ParseException { return FORMAT.parse(str); } ...and this mutates it outside synchronization public static void main(String arg[]) throws Exception { MutableStatics.parse(“Jan 1, 2000”); } }
  • 10. Shared mutable statics - instance per call public class MutableStatics { public static Date parse(String str) throws ParseException { DateFormat format = DateFormat.getDateInstance(DateFormat.MEDIUM); return format.parse(str); } public static void main(String arg[]) throws Exception { MutableStatics.parse(“Jan 1, 2000”); } }
  • 11. Shared mutable statics - ThreadLocal public class MutableStatics { private static final ThreadLocal<DateFormat> FORMAT = new ThreadLocal<DateFormat>() { @Override protected DateFormat initialValue() { return DateFormat.getDateInstance( DateFormat.MEDIUM); } }; public static Date parse(String str) throws ParseException { return FORMAT.get().parse(str); } }
  • 12. Common JDK Examples Danger! Safe • DateFormat • Random • Calendar • Pattern • Matcher
  • 13. Synchronization private int myField; synchronized( What goes here? ) { myField = 0; }
  • 14. DO NOT: synchronize on null MyObject obj = null; synchronized( obj ) { NullPointerException! // work }
  • 15. DO NOT: change instance MyObject obj = new MyObject(); synchronized( obj ) { obj = new MyObject(); no longer synchronizing on same object! }
  • 16. DO NOT: synch on string literals private static final String LOCK = “LOCK”; synchronized( LOCK ) { // work What is the scope of LOCK? }
  • 17. DO NOT: synch on autoboxed vals private static final Integer LOCK = 0; synchronized( LOCK ) { What is the scope of LOCK? // work }
  • 18. DO NOT: synch on ReentrantLock Lock lock = new ReentrantLock(); synchronized(lock) { // ... Probably not what you meant here } Lock lock = new ReentrantLock(); lock.lock(); Probably more like this... try { // ... } finally { lock.unlock(); }
  • 19. What should I lock on? // The field you’re protecting private final Map map = ... synchronized(map) { // ...access map } // Explicit lock object private final Object lock = new Object(); synchronized(lock) { // ...modify state }
  • 21. Visibility problems int x = 5; Thread 1: if(x == 5) { x = 10; } Thread 2: System.out.println(x);
  • 22. Visibility problems volatile int x = 5; Thread 1: if(x == 5) { x = 10; } Thread 2: System.out.println(x);
  • 23. Inconsistent Synchronization public class SomeData { private final Map data = new HashMap(); public void set(String key, String value) { synchronized(data) { Protecting writes data.put(key, value); } } public String get(String key) { return data.get(key); ...but not reads } }
  • 24. Double-checked locking public class Singleton { private static Singleton instance; public static Singleton getInstance() { if(instance == null) { Attempt to avoid synchronization synchronized(Singleton.class) { if(instance == null) { instance = new Singleton(); } } } return instance; } }
  • 25. Double-checked locking public class Singleton { private static Singleton instance; public static Singleton getInstance() { if(instance == null) { READ synchronized(Singleton.class) { if(instance == null) { READ instance = new Singleton(); WRITE } } } return instance; } }
  • 26. Double-checked locking - volatile public class Singleton { private static volatile Singleton instance; public static Singleton getInstance() { if(instance == null) { synchronized(Singleton.class) { if(instance == null) { instance = new Singleton(); } } } return instance; } }
  • 27. Double-checked locking - initialize on demand public class Singleton { private static class SingletonHolder { private static final Singleton instance = new Singleton(); } public static Singleton getInstance() { return SingletonHolder.instance; } }
  • 28. volatile arrays public final class VolatileArray { private volatile boolean[] vals; public void flip(int i) { Is the value of vals[i] vals[i] = true; visible to other threads? } public boolean flipped(int i) { return vals[i]; } }
  • 30. Volatile counter public class Counter { private volatile int count; public int next() { return count++; Looks atomic to me! } }
  • 31. AtomicInteger counter public class Counter { private AtomicInteger count = new AtomicInteger(); public int next() { return count.getAndIncrement(); } Really atomic via } encapsulation over multiple actions
  • 32. Composing atomic actions public Object putIfAbsent( Hashtable table, Object key, Object value) { Hashtable is thread-safe if(table.containsKey(key)) { READ // already present, return existing table.get(key); READ return null; } else { // doesn't exist, create new value WRITE return table.put(key, value); } }
  • 33. Composing atomic actions public Object putIfAbsent( Hashtable table, Object key, Object value) { Hashtable is thread-safe if(table.containsKey(key)) { READ // already present, return existing table.get(key); READ return null; } else { // doesn't exist, create new value WRITE return table.put(key, value); } }
  • 34. Participate in lock public Object putIfAbsent( Hashtable table, Object key, Object value) { Hashtable is thread-safe synchronized(table) { if(table.containsKey(key)) { table.get(key); return null; } else { return table.put(key, value); } } }
  • 35. Encapsulated compound actions public Object putIfAbsent( ConcurrentHashMap table, Object key, Object value) { return table.putIfAbsent(key, value); } Encpasulation FTW!
  • 36. Assignment of 64 bit values public class LongAssignment { private long x; public void setLong(long val) { x = val; Looks atomic to me, } but is it? }
  • 37. Assignment of 64 bit values - volatile public class LongAssignment { private volatile long x; public void setLong(long val) { x = val; } }
  • 39. Listener in constructor public interface DispatchListener { void newFare(Customer customer); } public class Taxi implements DispatchListener { public Taxi(Dispatcher dispatcher) { dispatcher.registerListener(this); We just published a // other initialization reference to this...oops! } public void newFare(Customer customer) { // go to new customer’s location } }
  • 40. Starting thread in constructor public class Cache { private final Thread cleanerThread; public Cache() { cleanerThread = new Thread(new Cleaner(this)); cleanerThread.start(); this escapes again! } // Clean will call back to this method public void cleanup() { // clean up Cache } }
  • 41. Static factory method public class Cache { // ... public static Cache newCache() { Cache cache = new Cache(); cache.startCleanerThread(); return cache; } }
  • 42. Areas of Focus • Shared Data • Coordination • Performance { • Threads • Wait/notify
  • 44. • THOU SHALT NOT: • call Thread.stop() All monitors unlocked by ThreadDeath • call Thread.suspend() or Thread.resume() Can lead to deadlock • call Thread.destroy() Not implemented (or safe) • call Thread.run() Wonʼt start Thread! Still in caller Thread. • use ThreadGroups Use a ThreadPoolExecutor instead.
  • 45. wait/notify // Thread 1 synchronized(lock) { You must synchronize. while(! someCondition()) { Always wait in a loop. lock.wait(); } } // Thread 2 synchronized(lock) { Synchronize here too! satisfyCondition(); lock.notifyAll(); }
  • 46. Condition is similar 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(); } Condition is more flexible than wait/notify. } public void change() { lock.lock(); try { satisfyCondition(); condition.signalAll(); } finally { lock.unlock(); } }
  • 47. Areas of Focus • Shared Data • Coordination • Deadlock • Performance { • Spin wait • Thread contention
  • 48. Deadlock // Thread 1 synchronized(lock1) { synchronized(lock2) { // stuff } } Classic deadlock. // Thread 2 synchronized(lock2) { synchronized(lock1) { // stuff } }
  • 49. Deadlock avoidance • Lock splitting • Lock ordering • Lock timeout • tryLock
  • 50. Spin wait // Not efficient private volatile boolean flag = false; public void waitTillChange() { while(! flag) { Thread.sleep(100); Spin on flag, waiting for a change. } } public void change() { flag = true; }
  • 51. Replace with Condition private final Lock lock = new ReentrantLock(); private final Condition condition = lock.newCondition(); private boolean flag = false; public void waitTillChange() { lock.lock(); try { while(! flag) condition.await(); } finally { lock.unlock(); Better but longer. } } public void change() { lock.lock(); try { flag = true; condition.signalAll(); } finally { lock.unlock(); } }
  • 52. CountDownLatch private final CountDownLatch latch = new CountDownLatch(1); public void waitTillChange() { latch.await(); } public void change() { latch.countDown(); Coordination classes } like CountDownLatch and CyclicBarrier cover many common uses better than Condition.
  • 53. Lock contention x Hash f(x) Bucket 0 Bucket 1 Bucket 2 Bucket 3
  • 54. Lock striping x Hash g(x) Hash f(x) Hash f(x) Bucket 0 Bucket 1 Bucket 0 Bucket 1
  • 55. Final Exam public class StatisticsImpl implements Statistics, StatisticsImplementor { private long queryExecutionCount; public synchronized void queryExecuted( String hql, int rows, long time) { queryExecutionCount++; // ... other stat collection } public long getQueryExecutionCount() { return queryExecutionCount; } public synchronized void clear() { queryExecutionCount = 0; // ... clear all other stats } }
  • 56. Final Exam public class StatisticsImpl implements Statistics, StatisticsImplementor { private long queryExecutionCount; Single shared lock for ALL stat values public synchronized void queryExecuted( String hql, int rows, long time) { queryExecutionCount++; // ... other stat collection } public long getQueryExecutionCount() { return queryExecutionCount; Read shared value Non-atomic read } w/o synchronization of long value public synchronized void clear() { queryExecutionCount = 0; Race condition if reading // ... clear all other stats stat and clearing } }
  • 57. Thanks... Twitter http://twitter.com/puredanger Blog http://tech.puredanger.com Concurrency http://concurrency.tumblr.com links http://refcardz.dzone.com/refcardz/ Refcard core-java-concurrency Slides http://slideshare.net/alexmiller