SlideShare una empresa de Scribd logo
1 de 57
Descargar para leer sin conexión
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
• Shared Data
• Coordination
• Performance

{

• Locking
• Visibility
• Atomicity
• Safe Publication
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
• Calendar
• Matcher

• Random
• Pattern
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() {
Attempt to avoid synchronization
if(instance == null) {
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) {
synchronized(Singleton.class) {
if(instance == null) {
instance = new Singleton();
}
}
}
return instance;
}

READ
READ
WRITE
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)) {
// already present, return existing
table.get(key);
return null;

}

} else {
// doesn't exist, create new value
return table.put(key, value);
}

READ
READ
WRITE
Composing atomic actions
public Object putIfAbsent(
Hashtable table, Object key, Object value) {
Hashtable is
thread-safe

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

}

} else {
// doesn't exist, create new value
return table.put(key, value);
}

READ
READ
WRITE
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()
• call Thread.suspend() or Thread.resume()

All monitors unlocked by ThreadDeath

Can lead to deadlock

• call Thread.destroy()
• call Thread.run()
• use ThreadGroups

Not implemented (or safe)

Wonʼt start Thread! Still in caller Thread.
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
• Performance

{

• Deadlock
• Spin wait
• Thread contention
Deadlock
// Thread 1
synchronized(lock1) {
synchronized(lock2) {
// stuff
}
}
// Thread 2
synchronized(lock2) {
synchronized(lock1) {
// stuff
}
}

Classic deadlock.
Deadlock avoidance
• Lock splitting
• Lock ordering
• Lock timeout
• tryLock
Spin wait
// Not efficient
private volatile boolean flag = false;
public void waitTillChange() {
while(! flag) {
Spin on flag, waiting for
Thread.sleep(100);
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();
}
}
public void change() {
lock.lock();
try {
flag = true;
condition.signalAll();
} finally { lock.unlock(); } }

Better but longer.
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)

Bucket 0

Bucket 1

Hash f(x)

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
Blog
Concurrency
links

http://twitter.com/puredanger
http://tech.puredanger.com
http://concurrency.tumblr.com

Refcard

http://refcardz.dzone.com/refcardz/
core-java-concurrency

Slides

http://slideshare.net/alexmiller

Más contenido relacionado

La actualidad más candente

Refactoring Jdbc Programming
Refactoring Jdbc ProgrammingRefactoring Jdbc Programming
Refactoring Jdbc Programmingchanwook Park
 
[Greach 17] make concurrency groovy again
[Greach 17] make concurrency groovy again[Greach 17] make concurrency groovy again
[Greach 17] make concurrency groovy againAlonso Torres
 
Getting started with Clojure
Getting started with ClojureGetting started with Clojure
Getting started with ClojureJohn Stevenson
 
Repetition is bad, repetition is bad.
Repetition is bad, repetition is bad.Repetition is bad, repetition is bad.
Repetition is bad, repetition is bad.Michele Giacobazzi
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good TestsTomek Kaczanowski
 
Java осень 2012 лекция 2
Java осень 2012 лекция 2Java осень 2012 лекция 2
Java осень 2012 лекция 2Technopark
 
JDBC - JPA - Spring Data
JDBC - JPA - Spring DataJDBC - JPA - Spring Data
JDBC - JPA - Spring DataArturs Drozdovs
 
Actor Concurrency
Actor ConcurrencyActor Concurrency
Actor ConcurrencyAlex Miller
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commandsphanleson
 
4java Basic Syntax
4java Basic Syntax4java Basic Syntax
4java Basic SyntaxAdil Jafri
 
Java OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBCJava OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBCOUM SAOKOSAL
 

La actualidad más candente (19)

04 Data Access
04 Data Access04 Data Access
04 Data Access
 
Sam wd programs
Sam wd programsSam wd programs
Sam wd programs
 
Refactoring Jdbc Programming
Refactoring Jdbc ProgrammingRefactoring Jdbc Programming
Refactoring Jdbc Programming
 
Ejb3 Dan Hinojosa
Ejb3 Dan HinojosaEjb3 Dan Hinojosa
Ejb3 Dan Hinojosa
 
[Greach 17] make concurrency groovy again
[Greach 17] make concurrency groovy again[Greach 17] make concurrency groovy again
[Greach 17] make concurrency groovy again
 
Getting started with Clojure
Getting started with ClojureGetting started with Clojure
Getting started with Clojure
 
Java
JavaJava
Java
 
Lect04
Lect04Lect04
Lect04
 
Repetition is bad, repetition is bad.
Repetition is bad, repetition is bad.Repetition is bad, repetition is bad.
Repetition is bad, repetition is bad.
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
 
Java осень 2012 лекция 2
Java осень 2012 лекция 2Java осень 2012 лекция 2
Java осень 2012 лекция 2
 
Xm lparsers
Xm lparsersXm lparsers
Xm lparsers
 
Java Programming - 08 java threading
Java Programming - 08 java threadingJava Programming - 08 java threading
Java Programming - 08 java threading
 
JDBC - JPA - Spring Data
JDBC - JPA - Spring DataJDBC - JPA - Spring Data
JDBC - JPA - Spring Data
 
IKH331-07-java-rmi
IKH331-07-java-rmiIKH331-07-java-rmi
IKH331-07-java-rmi
 
Actor Concurrency
Actor ConcurrencyActor Concurrency
Actor Concurrency
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commands
 
4java Basic Syntax
4java Basic Syntax4java Basic Syntax
4java Basic Syntax
 
Java OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBCJava OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBC
 

Destacado

Casco insurance claims handling, If P&C insurance case study
Casco insurance claims handling, If P&C insurance case studyCasco insurance claims handling, If P&C insurance case study
Casco insurance claims handling, If P&C insurance case studyMihails Galuška
 
Psm 280 A Best Practices In Advancing Customer Marketing Innovations
Psm 280 A Best Practices In Advancing Customer Marketing  InnovationsPsm 280 A Best Practices In Advancing Customer Marketing  Innovations
Psm 280 A Best Practices In Advancing Customer Marketing InnovationsCameron Tew
 
Супермаркет услуг interinformer.com (для продавцов)
Супермаркет услуг interinformer.com (для продавцов)Супермаркет услуг interinformer.com (для продавцов)
Супермаркет услуг interinformer.com (для продавцов)Mihails Galuška
 
People Jam!
People Jam!People Jam!
People Jam!anshul2
 
Hippocrates 2.0
Hippocrates 2.0Hippocrates 2.0
Hippocrates 2.0Cristiano
 
Systems Of The Body
Systems Of The BodySystems Of The Body
Systems Of The BodyToekneeH
 
Hol webinar summary
Hol webinar summaryHol webinar summary
Hol webinar summaryCameron Tew
 
Elconceptodedisciplinaescolar.roberto l´hotelleríe
Elconceptodedisciplinaescolar.roberto l´hotelleríeElconceptodedisciplinaescolar.roberto l´hotelleríe
Elconceptodedisciplinaescolar.roberto l´hotelleríeRonald Heisele
 
Debt Management, Collection on Ultimus BPM platform
Debt Management, Collection on Ultimus BPM platformDebt Management, Collection on Ultimus BPM platform
Debt Management, Collection on Ultimus BPM platformMihails Galuška
 
CASCO insurance claims handling
CASCO insurance claims handlingCASCO insurance claims handling
CASCO insurance claims handlingMihails Galuška
 
Medical Science Liaison Webinarv 2009
Medical Science Liaison  Webinarv  2009Medical Science Liaison  Webinarv  2009
Medical Science Liaison Webinarv 2009Cameron Tew
 
Sales Force Short Version
Sales Force Short VersionSales Force Short Version
Sales Force Short VersionCameron Tew
 

Destacado (15)

Casco insurance claims handling, If P&C insurance case study
Casco insurance claims handling, If P&C insurance case studyCasco insurance claims handling, If P&C insurance case study
Casco insurance claims handling, If P&C insurance case study
 
Java7 Features
Java7 FeaturesJava7 Features
Java7 Features
 
Psm 280 A Best Practices In Advancing Customer Marketing Innovations
Psm 280 A Best Practices In Advancing Customer Marketing  InnovationsPsm 280 A Best Practices In Advancing Customer Marketing  Innovations
Psm 280 A Best Practices In Advancing Customer Marketing Innovations
 
Супермаркет услуг interinformer.com (для продавцов)
Супермаркет услуг interinformer.com (для продавцов)Супермаркет услуг interinformer.com (для продавцов)
Супермаркет услуг interinformer.com (для продавцов)
 
People Jam!
People Jam!People Jam!
People Jam!
 
Hippocrates 2.0
Hippocrates 2.0Hippocrates 2.0
Hippocrates 2.0
 
Systems Of The Body
Systems Of The BodySystems Of The Body
Systems Of The Body
 
Hol webinar summary
Hol webinar summaryHol webinar summary
Hol webinar summary
 
Elconceptodedisciplinaescolar.roberto l´hotelleríe
Elconceptodedisciplinaescolar.roberto l´hotelleríeElconceptodedisciplinaescolar.roberto l´hotelleríe
Elconceptodedisciplinaescolar.roberto l´hotelleríe
 
Test
TestTest
Test
 
Debt Management, Collection on Ultimus BPM platform
Debt Management, Collection on Ultimus BPM platformDebt Management, Collection on Ultimus BPM platform
Debt Management, Collection on Ultimus BPM platform
 
Java basics
Java basicsJava basics
Java basics
 
CASCO insurance claims handling
CASCO insurance claims handlingCASCO insurance claims handling
CASCO insurance claims handling
 
Medical Science Liaison Webinarv 2009
Medical Science Liaison  Webinarv  2009Medical Science Liaison  Webinarv  2009
Medical Science Liaison Webinarv 2009
 
Sales Force Short Version
Sales Force Short VersionSales Force Short Version
Sales Force Short Version
 

Similar a Concurrency gotchas

Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency GotchasAlex Miller
 
Effective java - concurrency
Effective java - concurrencyEffective java - concurrency
Effective java - concurrencyfeng lee
 
Javaoneconcurrencygotchas 090610192215 Phpapp02
Javaoneconcurrencygotchas 090610192215 Phpapp02Javaoneconcurrencygotchas 090610192215 Phpapp02
Javaoneconcurrencygotchas 090610192215 Phpapp02Tarun Kumar
 
Concurrency Antipatterns In IDEA
Concurrency Antipatterns In IDEAConcurrency Antipatterns In IDEA
Concurrency Antipatterns In IDEAcdracm
 
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...julien.ponge
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in Practiceericbeyeler
 
.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
 
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch
 
AST Transformations at JFokus
AST Transformations at JFokusAST Transformations at JFokus
AST Transformations at JFokusHamletDRC
 
Use of Apache Commons and Utilities
Use of Apache Commons and UtilitiesUse of Apache Commons and Utilities
Use of Apache Commons and UtilitiesPramod Kumar
 
A topology of memory leaks on the JVM
A topology of memory leaks on the JVMA topology of memory leaks on the JVM
A topology of memory leaks on the JVMRafael Winterhalter
 
第1回 チキチキ『( ゜ェ゜)・;'.、ゴフッ』 - シングルトンパターン(Java)
第1回 チキチキ『( ゜ェ゜)・;'.、ゴフッ』 - シングルトンパターン(Java)第1回 チキチキ『( ゜ェ゜)・;'.、ゴフッ』 - シングルトンパターン(Java)
第1回 チキチキ『( ゜ェ゜)・;'.、ゴフッ』 - シングルトンパターン(Java)潤一 加藤
 
Ast transformations
Ast transformationsAst transformations
Ast transformationsHamletDRC
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on AndroidTomáš Kypta
 

Similar a Concurrency gotchas (20)

Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency Gotchas
 
Effective java - concurrency
Effective java - concurrencyEffective java - concurrency
Effective java - concurrency
 
Javaoneconcurrencygotchas 090610192215 Phpapp02
Javaoneconcurrencygotchas 090610192215 Phpapp02Javaoneconcurrencygotchas 090610192215 Phpapp02
Javaoneconcurrencygotchas 090610192215 Phpapp02
 
Concurrency Antipatterns In IDEA
Concurrency Antipatterns In IDEAConcurrency Antipatterns In IDEA
Concurrency Antipatterns In IDEA
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in Java
 
04 threads
04 threads04 threads
04 threads
 
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in Practice
 
.NET Multithreading and File I/O
.NET Multithreading and File I/O.NET Multithreading and File I/O
.NET Multithreading and File I/O
 
Java Concurrency
Java ConcurrencyJava Concurrency
Java Concurrency
 
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
 
AST Transformations at JFokus
AST Transformations at JFokusAST Transformations at JFokus
AST Transformations at JFokus
 
Use of Apache Commons and Utilities
Use of Apache Commons and UtilitiesUse of Apache Commons and Utilities
Use of Apache Commons and Utilities
 
A topology of memory leaks on the JVM
A topology of memory leaks on the JVMA topology of memory leaks on the JVM
A topology of memory leaks on the JVM
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Java 7 LavaJUG
Java 7 LavaJUGJava 7 LavaJUG
Java 7 LavaJUG
 
第1回 チキチキ『( ゜ェ゜)・;'.、ゴフッ』 - シングルトンパターン(Java)
第1回 チキチキ『( ゜ェ゜)・;'.、ゴフッ』 - シングルトンパターン(Java)第1回 チキチキ『( ゜ェ゜)・;'.、ゴフッ』 - シングルトンパターン(Java)
第1回 チキチキ『( ゜ェ゜)・;'.、ゴフッ』 - シングルトンパターン(Java)
 
concurrency_c#_public
concurrency_c#_publicconcurrency_c#_public
concurrency_c#_public
 
Ast transformations
Ast transformationsAst transformations
Ast transformations
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on Android
 

Último

ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfVanessa Camilleri
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...Nguyen Thanh Tu Collection
 
week 1 cookery 8 fourth - quarter .pptx
week 1 cookery 8  fourth  -  quarter .pptxweek 1 cookery 8  fourth  -  quarter .pptx
week 1 cookery 8 fourth - quarter .pptxJonalynLegaspi2
 
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxSayali Powar
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvRicaMaeCastro1
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataBabyAnnMotar
 
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...DhatriParmar
 
How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17Celine George
 
Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1GloryAnnCastre1
 
4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptxmary850239
 
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxDIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxMichelleTuguinay1
 
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...DhatriParmar
 
Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWQuiz Club NITW
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxlancelewisportillo
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxkarenfajardo43
 
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptxMan or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptxDhatriParmar
 

Último (20)

ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdf
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
 
week 1 cookery 8 fourth - quarter .pptx
week 1 cookery 8  fourth  -  quarter .pptxweek 1 cookery 8  fourth  -  quarter .pptx
week 1 cookery 8 fourth - quarter .pptx
 
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped data
 
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
Blowin' in the Wind of Caste_ Bob Dylan's Song as a Catalyst for Social Justi...
 
Paradigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTAParadigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTA
 
How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17
 
Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1
 
4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx
 
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxDIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
 
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
 
Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITW
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
 
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptxMan or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
 

Concurrency gotchas

  • 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 • Shared Data • Coordination • Performance { • Locking • Visibility • Atomicity • Safe Publication
  • 5. Unprotected Field Access A What happens if we modify data without locking?
  • 6.
  • 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 • Calendar • Matcher • Random • Pattern
  • 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() { Attempt to avoid synchronization if(instance == null) { 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) { synchronized(Singleton.class) { if(instance == null) { instance = new Singleton(); } } } return instance; } READ READ WRITE
  • 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)) { // already present, return existing table.get(key); return null; } } else { // doesn't exist, create new value return table.put(key, value); } READ READ WRITE
  • 33. Composing atomic actions public Object putIfAbsent( Hashtable table, Object key, Object value) { Hashtable is thread-safe if(table.containsKey(key)) { // already present, return existing table.get(key); return null; } } else { // doesn't exist, create new value return table.put(key, value); } READ READ WRITE
  • 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() • call Thread.suspend() or Thread.resume() All monitors unlocked by ThreadDeath Can lead to deadlock • call Thread.destroy() • call Thread.run() • use ThreadGroups Not implemented (or safe) Wonʼt start Thread! Still in caller Thread. 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 • Performance { • Deadlock • Spin wait • Thread contention
  • 48. Deadlock // Thread 1 synchronized(lock1) { synchronized(lock2) { // stuff } } // Thread 2 synchronized(lock2) { synchronized(lock1) { // stuff } } Classic deadlock.
  • 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) { Spin on flag, waiting for Thread.sleep(100); 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(); } } public void change() { lock.lock(); try { flag = true; condition.signalAll(); } finally { lock.unlock(); } } Better but longer.
  • 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) Bucket 0 Bucket 1 Hash f(x) 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 }