SlideShare a Scribd company logo
Java™ Platform
Concurrency Gotchas


Alex Miller
Terracotta
Questions to answer

>   What are common concurrency problems?
>   Why are they problems?
>   How do I detect these problems?
>   How do I correct these problems?




                                            2
Taxonomy of Concurrency Gotchas

>   Shared Data
>   Coordination
>   Performance




                                  3
Shared Data

>   Locking
>   Visibility
>   Atomicity
>   Safe Publication




                       4
What happens if we modify
  data without locking?




                            5
What happens if we modify
  data without locking?



                   Hint: itʼs not good.




                                          5
6
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 {
                                ...and this mutates it
      return FORMAT.parse(str);
                                outside synchronization
    }

    public static void main(String arg[]) {
      MutableStatics.parse(“Jan 1, 2000”);
    }
}

                                                                 7
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[]) {
      MutableStatics.parse(“Jan 1, 2000”);
    }
}


                                                         8
Synchronization
private int myField;


synchronized( What goes here? ) {
    myField = 0;
}




                                    9
DO NOT synchronize on null
MyObject obj = null;


synchronized( obj ) {   NullPointerException!
    // stuff
}




                                                10
DO NOT change instance
MyObject obj = new MyObject();


synchronized( obj ) {
                            No longer synchronizing
    obj = new MyObject();    on the same object!
}




                                                      11
12
DO NOT synchronize on string literals
private static final String LOCK = “LOCK”;
synchronized( LOCK ) {
                            What is the scope
    // work                    of LOCK?
}




                                                13
DO NOT synchronize on autoboxed instances
private static final Integer LOCK = 0;
synchronized( LOCK ) {
                          What is the scope
    // work                  of LOCK?
}




                                              14
DO NOT synchronize on ReentrantLock
final Lock lock = new ReentrantLock();
synchronized( lock ) {     Probably not what
  // work                   you meant here
}


final Lock lock = new ReentrantLock();
lock.lock();
                               Probably should
try {                           be this instead
  // ...
} finally {
  lock.unlock();
}



                                                  15
What should I lock on?
// The field you are protecting
private final Map map = ...
synchronized(map) {
  // ...access map
}




// Or an explicit lock object
private final Object lock = new Object();
synchronized(lock) {
  // ... modify state
}



                                            16
Visibility




             17
Inconsistent Synchronization
public class SomeData {
  private final Map data = new HashMap();

    public void put(String key, String value) {
      synchronized(data) {
        data.put(key, value);   Modified under synchronization
      }
    }

    public String get(String key) {
      return data.get(key);     Read without synchronization
    }
}



                                                                18
Double-checked locking
public final 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;
    }
}


                                                                           19
Double-checked locking
public final 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;
    }
}


                                                    19
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;
  }



                                                20
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;
    }
}




                                                               21
Racy single-check
public final class String {
  private int hash;              // default to 0
  private final char[] value;    // immutable

    public int hashCode() {
      int h = hash;
      if(h == 0) {
        // ... compute value for h from data
        hash = h;
      }
      return h;
    }
}



                                                   22
volatile arrays
public final class VolatileArray {
  private volatile boolean[] vals;

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

    public boolean flipped(int i) {
      return vals[i];
    }
}




                                                        23
Atomicity




            24
Volatile counter
public class Counter {
    private volatile int count;


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




                                                25
AtomicInteger counter

public class Counter {
    private final AtomicInteger count = new AtomicInteger();


    public int next() {
                                          Really atomic by
        return count.getAndIncrement();   encapsulating
    }                                     multiple actions

}




                                                               26
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 value
      return table.get(key);                          READ
    } else {
      // doesn’t exist, create and return new value
      table.put(key, value);                          WRITE
      return value;
    }
}




                                                              27
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 value
      return table.get(key);                          READ
    } else {
      // doesn’t exist, create and return new value
      table.put(key, value);                          WRITE
      return value;
    }
}




                                                              27
Participate in lock
public Object putIfAbsent(
   Hashtable table, Object key, Object value) {

    synchronized(table) {        Protect with synchronization
      if(table.containsKey(key)) {
        return table.get(key);
      } else {
        table.put(key, value);
        return value;
      }
    }
}




                                                                28
Encapsulated compound actions

public Object putIfAbsent(
    ConcurrentHashMap table, Object key, Object value) {


    table.putIfAbsent(key, value);
}




                                                           29
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?
}




                                          30
Assignment of 64 bit values - volatile
public class LongAssignment {
    private volatile long x;


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




                                         31
Safe publication




                   Intentionally left blank.




                                               32
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
    }
}


                                                                   33
Starting thread in constructor
public class Cache {
  private final Thread cleanerThread;

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

    // Cleaner calls back to this method
    public void cleanup() {
      // clean up Cache
    }
}



                                                                 34
Static factory method
public class Cache {
    // ...


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




                                       35
Coordination

>   Threads
>   wait/notify




                  36
Threads

>   DO NOT:
    • Call Thread.stop()
    • Call Thread.suspend() or Thread.resume()
    • Call Thread.destroy()
    • Call Thread.run()
    • Use ThreadGroups



                                                 37
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();    Update condition!
    lock.notifyAll();
}


                                                              38
Performance

>   Deadlock
>   Spin wait
>   Lock contention




                      39
Deadlock
// Thread 1
synchronized(lock1) {
    synchronized(lock2) {   Classic deadlock.
        // stuff
    }
}


// Thread 2
synchronized(lock2) {
    synchronized(lock1) {
        // stuff
    }
}
                                                40
Deadlock avoidance

>   Lock splitting
>   Lock ordering
>   Lock timeout
>   tryLock




                     41
Spin wait
// Not efficient
private volatile boolean flag = false;


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


public void change() {
    flag = true;
}


                                                  42
Replace with wait/notify
private final Object lock = new Object();
private boolean flag = false;

public void waitTillChange() {
  synchronized(lock) {
    while(! flag)      Wait/notify is far more
      lock.wait();     efficient than spin wait.
  }
}

public void change() {
  synchronized(lock) {
    flag = true;
    lock.notifyAll();
  }
}
                                                  43
Lock contention

                                     x




                                  Hash f(x)




            Bucket 0   Bucket 1           Bucket 2   Bucket 3




                                                                44
Lock striping
                                             x




                                          Hash g(x)




                       Hash f(x)                                 Hash f(x)




            Bucket 0           Bucket 1               Bucket 0           Bucket 1




                                                                                    45
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
    }
}
                                                                      46
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;
                                  Read of shared value
    }
                                  without synchronization
    public synchronized void clear() {
      queryExecutionCount = 0;
      // ... clear all other stats
    }
}
                                                                      46
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;
                                  Read of shared value      Non-atomic read
    }
                                  without synchronization   of long value
    public synchronized void clear() {
      queryExecutionCount = 0;
      // ... clear all other stats
    }
}
                                                                              46
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;
                                  Read of shared value       Non-atomic read
    }
                                  without synchronization    of long value
    public synchronized void clear() {
      queryExecutionCount = 0;
                                       Race condition if reading stat and
      // ... clear all other stats     clearing - could be compound action
    }
}
                                                                               46
Final Exam
public class StatisticsImpl implements Statistics,
StatisticsImplementor {
  private long queryExecutionCount;

  public synchronized void queryExecuted(String hql, int rows, long
time) {
                             Single shared lock for ALL stat values
    queryExecutionCount++;
    // ... other stat collection
  }

    public long getQueryExecutionCount() {
      return queryExecutionCount;
                                  Read of shared value       Non-atomic read
    }
                                  without synchronization    of long value
    public synchronized void clear() {
      queryExecutionCount = 0;
                                       Race condition if reading stat and
      // ... clear all other stats     clearing - could be compound action
    }
}
                                                                               46
Alex Miller
Terracotta

Blog:    http://tech.puredanger.com
Twitter: @puredanger

More Related Content

What's hot

Java synchronizers
Java synchronizersJava synchronizers
Java synchronizers
ts_v_murthy
 
Java concurrency begining
Java concurrency   beginingJava concurrency   begining
Java concurrency beginingmaksym220889
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency Gotchas
Alex Miller
 
Threads
ThreadsThreads
Java 7 at SoftShake 2011
Java 7 at SoftShake 2011Java 7 at SoftShake 2011
Java 7 at SoftShake 2011julien.ponge
 
Java 7 JUG Summer Camp
Java 7 JUG Summer CampJava 7 JUG Summer Camp
Java 7 JUG Summer Camp
julien.ponge
 
AST Transformations at JFokus
AST Transformations at JFokusAST Transformations at JFokus
AST Transformations at JFokusHamletDRC
 
Non blocking io with netty
Non blocking io with nettyNon blocking io with netty
Non blocking io with netty
Zauber
 
Multithreading done right
Multithreading done rightMultithreading done right
Multithreading done right
Platonov Sergey
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronization
priyabogra1
 
Groovy closures
Groovy closuresGroovy closures
Groovy closures
Vijay Shukla
 
Kotlin coroutine - the next step for RxJava developer?
Kotlin coroutine - the next step for RxJava developer?Kotlin coroutine - the next step for RxJava developer?
Kotlin coroutine - the next step for RxJava developer?
Artur Latoszewski
 
Circuit breaker
Circuit breakerCircuit breaker
Circuit breaker
bricemciver
 

What's hot (17)

Java synchronizers
Java synchronizersJava synchronizers
Java synchronizers
 
Java concurrency begining
Java concurrency   beginingJava concurrency   begining
Java concurrency begining
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency Gotchas
 
Threads
ThreadsThreads
Threads
 
Java 7 at SoftShake 2011
Java 7 at SoftShake 2011Java 7 at SoftShake 2011
Java 7 at SoftShake 2011
 
Java 7 JUG Summer Camp
Java 7 JUG Summer CampJava 7 JUG Summer Camp
Java 7 JUG Summer Camp
 
AST Transformations at JFokus
AST Transformations at JFokusAST Transformations at JFokus
AST Transformations at JFokus
 
packet destruction in NS2
packet destruction in NS2packet destruction in NS2
packet destruction in NS2
 
NS2 Shadow Object Construction
NS2 Shadow Object ConstructionNS2 Shadow Object Construction
NS2 Shadow Object Construction
 
Non blocking io with netty
Non blocking io with nettyNon blocking io with netty
Non blocking io with netty
 
Multithreading done right
Multithreading done rightMultithreading done right
Multithreading done right
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronization
 
Groovy closures
Groovy closuresGroovy closures
Groovy closures
 
Kotlin coroutine - the next step for RxJava developer?
Kotlin coroutine - the next step for RxJava developer?Kotlin coroutine - the next step for RxJava developer?
Kotlin coroutine - the next step for RxJava developer?
 
Circuit breaker
Circuit breakerCircuit breaker
Circuit breaker
 
Ds 2 cycle
Ds 2 cycleDs 2 cycle
Ds 2 cycle
 
concurrency_c#_public
concurrency_c#_publicconcurrency_c#_public
concurrency_c#_public
 

Viewers also liked

Lecture on Java Concurrency Day 4 on Feb 18, 2009.
Lecture on Java Concurrency Day 4 on Feb 18, 2009.Lecture on Java Concurrency Day 4 on Feb 18, 2009.
Lecture on Java Concurrency Day 4 on Feb 18, 2009.
Kyung Koo Yoon
 
GPars: Groovy Parallelism for Java
GPars: Groovy Parallelism for JavaGPars: Groovy Parallelism for Java
GPars: Groovy Parallelism for Java
Russel Winder
 
Basics of Java Concurrency
Basics of Java ConcurrencyBasics of Java Concurrency
Basics of Java Concurrency
kshanth2101
 
concurrency gpars
concurrency gparsconcurrency gpars
concurrency gparsPaul King
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
ducquoc_vn
 
groovy and concurrency
groovy and concurrencygroovy and concurrency
groovy and concurrency
Paul King
 
Project Fortress
Project FortressProject Fortress
Project Fortress
Alex Miller
 
Groovy concurrency
Groovy concurrencyGroovy concurrency
Groovy concurrency
Alex Miller
 
Java Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyJava Course 10: Threads and Concurrency
Java Course 10: Threads and Concurrency
Anton Keks
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
Rajesh Ananda Kumar
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in Practice
Alina Dolgikh
 
Java concurrency in practice
Java concurrency in practiceJava concurrency in practice
Java concurrency in practice
Mikalai Alimenkou
 

Viewers also liked (12)

Lecture on Java Concurrency Day 4 on Feb 18, 2009.
Lecture on Java Concurrency Day 4 on Feb 18, 2009.Lecture on Java Concurrency Day 4 on Feb 18, 2009.
Lecture on Java Concurrency Day 4 on Feb 18, 2009.
 
GPars: Groovy Parallelism for Java
GPars: Groovy Parallelism for JavaGPars: Groovy Parallelism for Java
GPars: Groovy Parallelism for Java
 
Basics of Java Concurrency
Basics of Java ConcurrencyBasics of Java Concurrency
Basics of Java Concurrency
 
concurrency gpars
concurrency gparsconcurrency gpars
concurrency gpars
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
groovy and concurrency
groovy and concurrencygroovy and concurrency
groovy and concurrency
 
Project Fortress
Project FortressProject Fortress
Project Fortress
 
Groovy concurrency
Groovy concurrencyGroovy concurrency
Groovy concurrency
 
Java Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyJava Course 10: Threads and Concurrency
Java Course 10: Threads and Concurrency
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in Practice
 
Java concurrency in practice
Java concurrency in practiceJava concurrency in practice
Java concurrency in practice
 

Similar to Java Concurrency Gotchas

Javaoneconcurrencygotchas 090610192215 Phpapp02
Javaoneconcurrencygotchas 090610192215 Phpapp02Javaoneconcurrencygotchas 090610192215 Phpapp02
Javaoneconcurrencygotchas 090610192215 Phpapp02Tarun Kumar
 
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
 
第1回 チキチキ『( ゜ェ゜)・;'.、ゴフッ』 - シングルトンパターン(Java)
第1回 チキチキ『( ゜ェ゜)・;'.、ゴフッ』 - シングルトンパターン(Java)第1回 チキチキ『( ゜ェ゜)・;'.、ゴフッ』 - シングルトンパターン(Java)
第1回 チキチキ『( ゜ェ゜)・;'.、ゴフッ』 - シングルトンパターン(Java)潤一 加藤
 
Use of Apache Commons and Utilities
Use of Apache Commons and UtilitiesUse of Apache Commons and Utilities
Use of Apache Commons and UtilitiesPramod Kumar
 
Scala in practice
Scala in practiceScala in practice
Scala in practice
andyrobinson8
 
3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java
DEVTYPE
 
Objective-C for Beginners
Objective-C for BeginnersObjective-C for Beginners
Objective-C for Beginners
Adam Musial-Bright
 
Effective java - concurrency
Effective java - concurrencyEffective java - concurrency
Effective java - concurrency
feng lee
 
20070329 Java Programing Tips
20070329 Java Programing Tips20070329 Java Programing Tips
20070329 Java Programing TipsShingo Furuyama
 
Concurrency Antipatterns In IDEA
Concurrency Antipatterns In IDEAConcurrency Antipatterns In IDEA
Concurrency Antipatterns In IDEAcdracm
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
Hithem Ahmed
 
K is for Kotlin
K is for KotlinK is for Kotlin
K is for Kotlin
TechMagic
 
OBJECTS IN Object Oriented Programming .ppt
OBJECTS IN Object Oriented Programming .pptOBJECTS IN Object Oriented Programming .ppt
OBJECTS IN Object Oriented Programming .ppt
SaadAsim11
 
Java весна 2013 лекция 2
Java весна 2013 лекция 2Java весна 2013 лекция 2
Java весна 2013 лекция 2Technopark
 
PVS-Studio in 2021 - Error Examples
PVS-Studio in 2021 - Error ExamplesPVS-Studio in 2021 - Error Examples
PVS-Studio in 2021 - Error Examples
Andrey Karpov
 
What’s new in C# 6
What’s new in C# 6What’s new in C# 6
What’s new in C# 6
Fiyaz Hasan
 
Kotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime PerformanceKotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime Performance
intelliyole
 

Similar to Java Concurrency Gotchas (20)

Javaoneconcurrencygotchas 090610192215 Phpapp02
Javaoneconcurrencygotchas 090610192215 Phpapp02Javaoneconcurrencygotchas 090610192215 Phpapp02
Javaoneconcurrencygotchas 090610192215 Phpapp02
 
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()
 
第1回 チキチキ『( ゜ェ゜)・;'.、ゴフッ』 - シングルトンパターン(Java)
第1回 チキチキ『( ゜ェ゜)・;'.、ゴフッ』 - シングルトンパターン(Java)第1回 チキチキ『( ゜ェ゜)・;'.、ゴフッ』 - シングルトンパターン(Java)
第1回 チキチキ『( ゜ェ゜)・;'.、ゴフッ』 - シングルトンパターン(Java)
 
Concurrency gotchas
Concurrency gotchasConcurrency gotchas
Concurrency gotchas
 
Use of Apache Commons and Utilities
Use of Apache Commons and UtilitiesUse of Apache Commons and Utilities
Use of Apache Commons and Utilities
 
Scala in practice
Scala in practiceScala in practice
Scala in practice
 
3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java3. Объекты, классы и пакеты в Java
3. Объекты, классы и пакеты в Java
 
Objective-C for Beginners
Objective-C for BeginnersObjective-C for Beginners
Objective-C for Beginners
 
Effective java - concurrency
Effective java - concurrencyEffective java - concurrency
Effective java - concurrency
 
20070329 Java Programing Tips
20070329 Java Programing Tips20070329 Java Programing Tips
20070329 Java Programing Tips
 
Test Engine
Test EngineTest Engine
Test Engine
 
Concurrency Antipatterns In IDEA
Concurrency Antipatterns In IDEAConcurrency Antipatterns In IDEA
Concurrency Antipatterns In IDEA
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
K is for Kotlin
K is for KotlinK is for Kotlin
K is for Kotlin
 
OBJECTS IN Object Oriented Programming .ppt
OBJECTS IN Object Oriented Programming .pptOBJECTS IN Object Oriented Programming .ppt
OBJECTS IN Object Oriented Programming .ppt
 
Java весна 2013 лекция 2
Java весна 2013 лекция 2Java весна 2013 лекция 2
Java весна 2013 лекция 2
 
Mattbrenner
MattbrennerMattbrenner
Mattbrenner
 
PVS-Studio in 2021 - Error Examples
PVS-Studio in 2021 - Error ExamplesPVS-Studio in 2021 - Error Examples
PVS-Studio in 2021 - Error Examples
 
What’s new in C# 6
What’s new in C# 6What’s new in C# 6
What’s new in C# 6
 
Kotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime PerformanceKotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime Performance
 

More from 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 Processing
Alex 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/join
Alex Miller
 
Cracking clojure
Cracking clojureCracking clojure
Cracking clojure
Alex 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 Web
Alex Miller
 
Clojure: The Art of Abstraction
Clojure: The Art of AbstractionClojure: The Art of Abstraction
Clojure: The Art of Abstraction
Alex Miller
 
Tree Editing with Zippers
Tree Editing with ZippersTree Editing with Zippers
Tree Editing with Zippers
Alex Miller
 
Blogging ZOMG
Blogging ZOMGBlogging ZOMG
Blogging ZOMG
Alex Miller
 
Innovative Software
Innovative SoftwareInnovative Software
Innovative Software
Alex Miller
 
Scaling Your Cache
Scaling Your CacheScaling Your Cache
Scaling Your Cache
Alex Miller
 
Caching In The Cloud
Caching In The CloudCaching In The Cloud
Caching In The Cloud
Alex 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 Scale
Alex Miller
 
Marshmallow Test
Marshmallow TestMarshmallow Test
Marshmallow TestAlex Miller
 
Strange Loop Conference 2009
Strange Loop Conference 2009Strange Loop Conference 2009
Strange Loop Conference 2009
Alex Miller
 
Cold Hard Cache
Cold Hard CacheCold Hard Cache
Cold Hard Cache
Alex Miller
 
Scaling Hibernate with Terracotta
Scaling Hibernate with TerracottaScaling Hibernate with Terracotta
Scaling Hibernate with Terracotta
Alex Miller
 
Java Collections API
Java Collections APIJava Collections API
Java Collections API
Alex Miller
 
Design Patterns Reconsidered
Design Patterns ReconsideredDesign Patterns Reconsidered
Design Patterns Reconsidered
Alex Miller
 
Java 7 Preview
Java 7 PreviewJava 7 Preview
Java 7 Preview
Alex Miller
 
Exploring Terracotta
Exploring TerracottaExploring Terracotta
Exploring Terracotta
Alex Miller
 

More from Alex Miller (20)

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
 
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
 
Cracking clojure
Cracking clojureCracking clojure
Cracking clojure
 
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
 
Clojure: The Art of Abstraction
Clojure: The Art of AbstractionClojure: The Art of Abstraction
Clojure: The Art of Abstraction
 
Tree Editing with Zippers
Tree Editing with ZippersTree Editing with Zippers
Tree Editing with Zippers
 
Blogging ZOMG
Blogging ZOMGBlogging ZOMG
Blogging ZOMG
 
Innovative Software
Innovative SoftwareInnovative Software
Innovative Software
 
Scaling Your Cache
Scaling Your CacheScaling Your Cache
Scaling Your Cache
 
Caching In The Cloud
Caching In The CloudCaching In The Cloud
Caching In The Cloud
 
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
 
Cold Hard Cache
Cold Hard CacheCold Hard Cache
Cold Hard Cache
 
Scaling Hibernate with Terracotta
Scaling Hibernate with TerracottaScaling Hibernate with Terracotta
Scaling Hibernate with Terracotta
 
Java Collections API
Java Collections APIJava Collections API
Java Collections API
 
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
 

Recently uploaded

Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
g2nightmarescribd
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 

Recently uploaded (20)

Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 

Java Concurrency Gotchas

  • 2. Questions to answer > What are common concurrency problems? > Why are they problems? > How do I detect these problems? > How do I correct these problems? 2
  • 3. Taxonomy of Concurrency Gotchas > Shared Data > Coordination > Performance 3
  • 4. Shared Data > Locking > Visibility > Atomicity > Safe Publication 4
  • 5. What happens if we modify data without locking? 5
  • 6. What happens if we modify data without locking? Hint: itʼs not good. 5
  • 7. 6
  • 8. 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 { ...and this mutates it return FORMAT.parse(str); outside synchronization } public static void main(String arg[]) { MutableStatics.parse(“Jan 1, 2000”); } } 7
  • 9. 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[]) { MutableStatics.parse(“Jan 1, 2000”); } } 8
  • 10. Synchronization private int myField; synchronized( What goes here? ) { myField = 0; } 9
  • 11. DO NOT synchronize on null MyObject obj = null; synchronized( obj ) { NullPointerException! // stuff } 10
  • 12. DO NOT change instance MyObject obj = new MyObject(); synchronized( obj ) { No longer synchronizing obj = new MyObject(); on the same object! } 11
  • 13. 12
  • 14. DO NOT synchronize on string literals private static final String LOCK = “LOCK”; synchronized( LOCK ) { What is the scope // work of LOCK? } 13
  • 15. DO NOT synchronize on autoboxed instances private static final Integer LOCK = 0; synchronized( LOCK ) { What is the scope // work of LOCK? } 14
  • 16. DO NOT synchronize on ReentrantLock final Lock lock = new ReentrantLock(); synchronized( lock ) { Probably not what // work you meant here } final Lock lock = new ReentrantLock(); lock.lock(); Probably should try { be this instead // ... } finally { lock.unlock(); } 15
  • 17. What should I lock on? // The field you are protecting private final Map map = ... synchronized(map) { // ...access map } // Or an explicit lock object private final Object lock = new Object(); synchronized(lock) { // ... modify state } 16
  • 19. Inconsistent Synchronization public class SomeData { private final Map data = new HashMap(); public void put(String key, String value) { synchronized(data) { data.put(key, value); Modified under synchronization } } public String get(String key) { return data.get(key); Read without synchronization } } 18
  • 20. Double-checked locking public final 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; } } 19
  • 21. Double-checked locking public final 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; } } 19
  • 22. 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; } 20
  • 23. 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; } } 21
  • 24. Racy single-check public final class String { private int hash; // default to 0 private final char[] value; // immutable public int hashCode() { int h = hash; if(h == 0) { // ... compute value for h from data hash = h; } return h; } } 22
  • 25. volatile arrays public final class VolatileArray { private volatile boolean[] vals; public void flip(int i) { vals[i] = true; Is the value of vals[i] } visible to other threads? public boolean flipped(int i) { return vals[i]; } } 23
  • 26. Atomicity 24
  • 27. Volatile counter public class Counter { private volatile int count; public int next() { return count++; Looks atomic to me! } } 25
  • 28. AtomicInteger counter public class Counter { private final AtomicInteger count = new AtomicInteger(); public int next() { Really atomic by return count.getAndIncrement(); encapsulating } multiple actions } 26
  • 29. 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 value return table.get(key); READ } else { // doesn’t exist, create and return new value table.put(key, value); WRITE return value; } } 27
  • 30. 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 value return table.get(key); READ } else { // doesn’t exist, create and return new value table.put(key, value); WRITE return value; } } 27
  • 31. Participate in lock public Object putIfAbsent( Hashtable table, Object key, Object value) { synchronized(table) { Protect with synchronization if(table.containsKey(key)) { return table.get(key); } else { table.put(key, value); return value; } } } 28
  • 32. Encapsulated compound actions public Object putIfAbsent( ConcurrentHashMap table, Object key, Object value) { table.putIfAbsent(key, value); } 29
  • 33. 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? } 30
  • 34. Assignment of 64 bit values - volatile public class LongAssignment { private volatile long x; public void setLong(long val) { x = val; } } 31
  • 35. Safe publication Intentionally left blank. 32
  • 36. 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 } } 33
  • 37. Starting thread in constructor public class Cache { private final Thread cleanerThread; public Cache() { this escapes again! cleanerThread = new Thread(new Cleaner(this)); cleanerThread.start(); } // Cleaner calls back to this method public void cleanup() { // clean up Cache } } 34
  • 38. Static factory method public class Cache { // ... public static Cache newCache() { Cache cache = new Cache(); cache.startCleanerThread(); return cache; } } 35
  • 39. Coordination > Threads > wait/notify 36
  • 40. Threads > DO NOT: • Call Thread.stop() • Call Thread.suspend() or Thread.resume() • Call Thread.destroy() • Call Thread.run() • Use ThreadGroups 37
  • 41. 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(); Update condition! lock.notifyAll(); } 38
  • 42. Performance > Deadlock > Spin wait > Lock contention 39
  • 43. Deadlock // Thread 1 synchronized(lock1) { synchronized(lock2) { Classic deadlock. // stuff } } // Thread 2 synchronized(lock2) { synchronized(lock1) { // stuff } } 40
  • 44. Deadlock avoidance > Lock splitting > Lock ordering > Lock timeout > tryLock 41
  • 45. Spin wait // Not efficient private volatile boolean flag = false; public void waitTillChange() { while(! flag) { Spin on flag, Thread.sleep(100); waiting for change } } public void change() { flag = true; } 42
  • 46. Replace with wait/notify private final Object lock = new Object(); private boolean flag = false; public void waitTillChange() { synchronized(lock) { while(! flag) Wait/notify is far more lock.wait(); efficient than spin wait. } } public void change() { synchronized(lock) { flag = true; lock.notifyAll(); } } 43
  • 47. Lock contention x Hash f(x) Bucket 0 Bucket 1 Bucket 2 Bucket 3 44
  • 48. Lock striping x Hash g(x) Hash f(x) Hash f(x) Bucket 0 Bucket 1 Bucket 0 Bucket 1 45
  • 49. 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 } } 46
  • 50. 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; Read of shared value } without synchronization public synchronized void clear() { queryExecutionCount = 0; // ... clear all other stats } } 46
  • 51. 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; Read of shared value Non-atomic read } without synchronization of long value public synchronized void clear() { queryExecutionCount = 0; // ... clear all other stats } } 46
  • 52. 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; Read of shared value Non-atomic read } without synchronization of long value public synchronized void clear() { queryExecutionCount = 0; Race condition if reading stat and // ... clear all other stats clearing - could be compound action } } 46
  • 53. Final Exam public class StatisticsImpl implements Statistics, StatisticsImplementor { private long queryExecutionCount; public synchronized void queryExecuted(String hql, int rows, long time) { Single shared lock for ALL stat values queryExecutionCount++; // ... other stat collection } public long getQueryExecutionCount() { return queryExecutionCount; Read of shared value Non-atomic read } without synchronization of long value public synchronized void clear() { queryExecutionCount = 0; Race condition if reading stat and // ... clear all other stats clearing - could be compound action } } 46
  • 54. Alex Miller Terracotta Blog: http://tech.puredanger.com Twitter: @puredanger