SlideShare a Scribd company logo
CONCURRENT PROGRAMMING
SYNCHRONIZATION (PART 2)
PROGRAMMAZIONE CONCORRENTE E DISTR.
Università degli Studi di Padova
Dipartimento di Matematica
Corso di Laurea in Informatica, A.A. 2015 – 2016
rcardin@math.unipd.it
Programmazione concorrente e distribuita
SUMMARY
 Conditions
 Volatile variables
 Atomics
 Thread confinement
 Immutability
2Riccardo Cardin
Programmazione concorrente e distribuita
CONDITIONS
 Condition variables
 Often a thread enters a critical section only to
discover that it can’t proceed
A condition is not fulfilled
 We can try to use a lock
3Riccardo Cardin
if (bank.getBalance(from) >= amount) {
// Thread might be deactivated at this point
bank.transfer(from, to, amount);
}
public void transfer(int from, int to, int amount) {
bankLock.lock();
try {
while (accounts[from] < amount) {
// wait
}
// transfer funds
}
No thread can
withdraw money, due
to the acquired lock:
DEADLOCK!!
Programmazione concorrente e distribuita
CONDITIONS
 To avoid unpleasant deadlock, use conditions
 A condition variable is built from a lock
 A thread owning the lock, calls await on the condition
 The lock is released by the thread
 Thread is not made runnable when the lock i available. It stays
deactivated until the condition will be fulfilled
 Wait set for the condition
4Riccardo Cardin
class Bank {
private Condition sufficientFunds;
public Bank() {
// Getting a condition with an evocative name
sufficientFunds = bankLock.newCondition();
}
}
sufficientFunds.await();
Programmazione concorrente e distribuita
CONDITIONS
 When another thread fulfills the condition, it
should notify other awaiting threads
 One of the awaiting thread will be eligible to acquire
the lock and to continue where it left off
 Lock must be available
 The condition may be fulfilled
 Retry to check that condition are met over and over again
 An awaiting thread cannot reactive itself: be carefull!
5Riccardo Cardin
sufficientFunds.signalAll();
while (!(/* ok to proceed */)) {
condition.await();
}
Programmazione concorrente e distribuita
CONDITIONS
 It’s important that some thread calls the
signalAll method eventually
 If no other thread bother to reactivate a waiting thread,
it will neve run again
 DEADLOCK!
 Call signalAll whenever the state of an object changes
6Riccardo Cardin
public void transfer(int from, int to, int amount) {
bankLock.lock();
try {
while (accounts[from] < amount)
sufficientFunds.await();
// transfer funds
sufficientFunds.signalAll();
} finally {
bankLock.unlock();
} }
Programmazione concorrente e distribuita
CONDITIONS
7Riccardo Cardin
Programmazione concorrente e distribuita
CONDITIONS
 Intrinsic locks have a single associated condition
 The wait method adds a thread to the wait set
 The notifyAll method unblocks waiting threads
 Having a single condition per intrinsic lock can be
inefficient
 Which condition has been safisfied? All threads waiting have
to be resumed
8Riccardo Cardin
public synchronized void transfer(int from, int to, int amount)
throws InterruptedException {
while (accounts[from] < amount)
wait(); // wait on intrinsic object lock
// transfer funds
notifyAll(); // notify all threads waiting
}
Programmazione concorrente e distribuita
CONDITIONS PITFALLS
 What should you use in your code, Locks or
synchronized methods
 Neither. In many situation it can be used one of the
mechanisms of the java.util.concurrent package
 i.e. – Blocking queues
 If you have to choose, use synchronized blocks
 Use Lock / Condition if you really need the
additional power that gives to you
 You have to define a custom protocol of synchronization
9Riccardo Cardin
Do not underestimate the powers of the dark side of concurrency
-- Riccardo Cardin
Programmazione concorrente e distribuita
VOLATILE VARIABLES
 Cached values and operations reodering are evil!
 A volatile variable is not cached by threads
 Share the visibility feature of synchronized
 Threads will automatically see the most up-to-date value
 ...but non of the atomicity features
 Possible race-conditions on multiple operations
10Riccardo Cardin
If you write a variable which may next be read by another thread, or
you read a variable which may have last been written by another
thread, you must use synchronization.
-- Brian Goetz
private volatile boolean done;
public boolean isDone() { return done; }
public void setDone() { done = true; }
Programmazione concorrente e distribuita
VOLATILE VARIABLES
 When to use volatile vars instead of locks
 Writes do not depend on its current value
 DO NOT use for implementing counters!
 The variable does not partecipate in invariants with
other variables
 Slightly better performances
11Riccardo Cardin
// Not atomic, you need synchronization
public void flipDone() { done = !done; }
volatile boolean shutdownRequested;
public void shutdown() { shutdownRequested = true; }
public void doWork() {
while (!shutdownRequested) {
// do stuff
}
}
Pattern of use:
status flag
Programmazione concorrente e distribuita
VOLATILE VARIABLES
12Riccardo Cardin
Programmazione concorrente e distribuita
ATOMICS
 There are operations other than setter and
getter provided by volatile variables
 java.util.concurrent.atomic provides classes
that guarantee atomicity of other operations
 AtomicInteger, AtomicBoolean, AtomicLong, ...
13Riccardo Cardin
class AtomicCounter {
private AtomicInteger c = new AtomicInteger(0);
public void increment() {
c.incrementAndGet();
}
public void decrement() {
c.decrementAndGet();
}
public int value() {
return c.get();
}
}
Uses low level CPU
operations, that don’t need
synchronization (CAS,
compare-and-swap)
Programmazione concorrente e distribuita
THREAD CONFINEMENT
 The best solution to concurrency problems is to
not share any mutable state
 Use ThreadLocal helper class to give each thread an
instance of a class
 When thread terminates, value is garbage collected
 Do not use as a replacement for global variables
 Many JDK classes are not thread-safe
 SimpleDateFormat, Random, ...
14Riccardo Cardin
public static final ThreadLocal<SimpleDateFormat> dateFormat =
new ThreadLocal<SimpleDateFormat>() {
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd");
}};
String dateStamp = dateFormat.get().format(new Date());
Programmazione concorrente e distribuita
IMMUTABILITY
 All the problems described so far have to do
with accessing shared mutable state
 If object state cannot be modified, the risks go away
 Immutable object are simple
 There are not different states for complex objects
 Immutable object are safer
 No untrusted code can modify directly object’s state or retain
a reference to modify it later
 Java does not formally defined immutability
 It is not sufficient declaring all fields as final
15Riccardo Cardin
Immutable objects are always thread-safe
-- Brian Goetz
Programmazione concorrente e distribuita
IMMUTABILITY
 An object is immutable if:
 Its state cannot be modified after construction
 So a immutable class has reference only to (effectively)
immutable classes
 All its fields are final
 It is properly constructed
 The this reference does not escape during construction, i.e.
calling code outside the class, and passing this
 Can use mutable state for internal representation
 Are this kind of object useful?
 There is a big difference between an object been immutbale
and the reference to it being immutable
16Riccardo Cardin
Programmazione concorrente e distribuita
IMMUTABILITY
17Riccardo Cardin
Programmazione concorrente e distribuita
IMMUTABILITY
 The final keyword on fields makes possibile
the guarantee on initialization safety
 A more limited version of the const in C++
 No reorder will be done by the compiler
 So, final fields can be accessed without additional
synchronization
 Better maintainability
 It’s time to have a look to an immutable class!
18Riccardo Cardin
Immutable objects can be used safely by any thread without additional
synchronization.
-- Brian Goetz
Programmazione concorrente e distribuita
IMMUTABILITY
19Riccardo Cardin
class OneValueCache {
private final BigInteger lastNumber;
private final BigInteger[] lastFactors;
// Do not use directly a mutable object to construct
// an immutable object
public OneValueCache(BigInteger i, BigInteger[] factors) {
lastNumber = i;
lastFactors = Arrays.copyOf(factors, factors.length);
}
// Do not late ‘escape’ an internal value of the immutable
// object. In this way no other code can maliciously modify
// that state
public BigInteger[] getFactors(BigInteger i) {
if (lastNumber == null || !lastNumber.equals(i))
return null;
else
return Arrays.copyOf(lastFactors, lastFactors.length);
}
}
}
Programmazione concorrente e distribuita
EXAMPLES
20Riccardo Cardin
https://github.com/rcardin/pcd-snippets
Programmazione concorrente e distribuita
REFERENCES
 Chap. 14 «Multithreading», Core Java Volume I - Fundamentals, Cay
Horstmann, Gary Cornell, 2012, Prentice Hall
 Chap. 3 «Sharing Objects», Java Concurrency in Practice, Brian
Goetz, 2006, Addison-Wesley Professional
 Atomic Access
https://docs.oracle.com/javase/tutorial/essential/concurrency/ato
mic.html
 Java theory and practice: Managing volatility
http://www.ibm.com/developerworks/library/j-jtp06197/
 Java theory and practice: Going atomic
http://www.ibm.com/developerworks/library/j-jtp11234/
 What is the difference of Atomic / Volatile / synchronize?
http://stackoverflow.com/questions/9749746/what-is-the-
difference-of-atomic-volatile-synchronize
21Riccardo Cardin

More Related Content

What's hot (19)

PPT
Introduction to-vhdl
Neeraj Gupta
 
PDF
Lecture1
karim_ibrahim
 
PDF
Vhdl introduction
Dhaval Shukla
 
PDF
Close Encounters in MDD: when models meet code
lbergmans
 
PDF
Generics and collections in Java
Gurpreet singh
 
PDF
Concurrency: Best Practices
IndicThreads
 
PPTX
System verilog coverage
Pushpa Yakkala
 
PPT
VHDL - Enumerated Types (Part 3)
Abhilash Nair
 
PDF
Detecting aspect-specific code smells using Ekeko for AspectJ
Coen De Roover
 
PDF
A rendering architecture
Sungkwan Park
 
PDF
INTRODUCTION TO VHDL
karthikpunuru
 
PDF
Kroening et al, v2c a verilog to c translator
sce,bhopal
 
PDF
Ekeko Technology Showdown at SoTeSoLa 2012
Coen De Roover
 
PDF
The SOUL Tool Suite for Querying Programs in Symbiosis with Eclipse
Coen De Roover
 
PDF
Extending and scripting PDT
William Candillon
 
PDF
VHDL course
Ibrahim Mezzah
 
PPT
Strategy and Template Pattern
Jonathan Simon
 
PDF
Introduction to VHDL
Yaser Kalifa
 
Introduction to-vhdl
Neeraj Gupta
 
Lecture1
karim_ibrahim
 
Vhdl introduction
Dhaval Shukla
 
Close Encounters in MDD: when models meet code
lbergmans
 
Generics and collections in Java
Gurpreet singh
 
Concurrency: Best Practices
IndicThreads
 
System verilog coverage
Pushpa Yakkala
 
VHDL - Enumerated Types (Part 3)
Abhilash Nair
 
Detecting aspect-specific code smells using Ekeko for AspectJ
Coen De Roover
 
A rendering architecture
Sungkwan Park
 
INTRODUCTION TO VHDL
karthikpunuru
 
Kroening et al, v2c a verilog to c translator
sce,bhopal
 
Ekeko Technology Showdown at SoTeSoLa 2012
Coen De Roover
 
The SOUL Tool Suite for Querying Programs in Symbiosis with Eclipse
Coen De Roover
 
Extending and scripting PDT
William Candillon
 
VHDL course
Ibrahim Mezzah
 
Strategy and Template Pattern
Jonathan Simon
 
Introduction to VHDL
Yaser Kalifa
 

Viewers also liked (15)

PPTX
Design Pattern Strutturali
Riccardo Cardin
 
PPTX
SOLID - Principles of Object Oriented Design
Riccardo Cardin
 
KEY
Scala For Java Programmers
Enno Runne
 
PPTX
Software architecture patterns
Riccardo Cardin
 
PDF
Presto updates to 0.178
Kai Sasaki
 
PPTX
Diagrammi di Sequenza
Riccardo Cardin
 
PPTX
Errori comuni nei documenti di Analisi dei Requisiti
Riccardo Cardin
 
PPTX
Diagrammi delle Classi
Riccardo Cardin
 
PPTX
Introduzione ai Design Pattern
Riccardo Cardin
 
PPTX
Java - Processing input and output
Riccardo Cardin
 
PPTX
Design pattern architetturali Model View Controller, MVP e MVVM
Riccardo Cardin
 
PPTX
Scala - the good, the bad and the very ugly
Bozhidar Bozhanov
 
PPTX
Java - Collections framework
Riccardo Cardin
 
PPTX
Design Pattern Architetturali - Dependency Injection
Riccardo Cardin
 
PPTX
Java - Sockets
Riccardo Cardin
 
Design Pattern Strutturali
Riccardo Cardin
 
SOLID - Principles of Object Oriented Design
Riccardo Cardin
 
Scala For Java Programmers
Enno Runne
 
Software architecture patterns
Riccardo Cardin
 
Presto updates to 0.178
Kai Sasaki
 
Diagrammi di Sequenza
Riccardo Cardin
 
Errori comuni nei documenti di Analisi dei Requisiti
Riccardo Cardin
 
Diagrammi delle Classi
Riccardo Cardin
 
Introduzione ai Design Pattern
Riccardo Cardin
 
Java - Processing input and output
Riccardo Cardin
 
Design pattern architetturali Model View Controller, MVP e MVVM
Riccardo Cardin
 
Scala - the good, the bad and the very ugly
Bozhidar Bozhanov
 
Java - Collections framework
Riccardo Cardin
 
Design Pattern Architetturali - Dependency Injection
Riccardo Cardin
 
Java - Sockets
Riccardo Cardin
 
Ad

Similar to Java- Concurrent programming - Synchronization (part 2) (20)

PPTX
Concurrency
Ankur Maheshwari
 
PPT
4 Multithreading and Parallel Programming.ppt
MahmoudGad93
 
PPTX
Concurrency
Sandeep Chawla
 
PDF
Concurrency in Java
Lakshmi Narasimhan
 
PDF
Concurrent Programming in Java
Lakshmi Narasimhan
 
DOC
Concurrency Learning From Jdk Source
Kaniska Mandal
 
PPTX
Concurrency Programming in Java - 06 - Thread Synchronization, Liveness, Guar...
Sachintha Gunasena
 
PDF
Concurrency on the JVM
Bernhard Huemer
 
PPT
Threads in Java
Gaurav Aggarwal
 
ODP
Java Concurrency, Memory Model, and Trends
Carol McDonald
 
PPT
Reliable and Concurrent Software - Java language
ssuser2637a1
 
PDF
Java concurrency in practice
Deon Huang
 
PPTX
Basics of Java Concurrency
kshanth2101
 
PDF
Programming with Threads in Java
koji lin
 
PPTX
Multithreading and concurrency in android
Rakesh Jha
 
PPTX
The Java Memory Model
CA Technologies
 
PPT
Shopzilla On Concurrency
Will Gage
 
PDF
Java Tutorials - Concurrency
Christian Rubiales
 
KEY
Modern Java Concurrency (Devoxx Nov/2011)
Martijn Verburg
 
PPTX
Thread & concurrancy
Onkar Deshpande
 
Concurrency
Ankur Maheshwari
 
4 Multithreading and Parallel Programming.ppt
MahmoudGad93
 
Concurrency
Sandeep Chawla
 
Concurrency in Java
Lakshmi Narasimhan
 
Concurrent Programming in Java
Lakshmi Narasimhan
 
Concurrency Learning From Jdk Source
Kaniska Mandal
 
Concurrency Programming in Java - 06 - Thread Synchronization, Liveness, Guar...
Sachintha Gunasena
 
Concurrency on the JVM
Bernhard Huemer
 
Threads in Java
Gaurav Aggarwal
 
Java Concurrency, Memory Model, and Trends
Carol McDonald
 
Reliable and Concurrent Software - Java language
ssuser2637a1
 
Java concurrency in practice
Deon Huang
 
Basics of Java Concurrency
kshanth2101
 
Programming with Threads in Java
koji lin
 
Multithreading and concurrency in android
Rakesh Jha
 
The Java Memory Model
CA Technologies
 
Shopzilla On Concurrency
Will Gage
 
Java Tutorials - Concurrency
Christian Rubiales
 
Modern Java Concurrency (Devoxx Nov/2011)
Martijn Verburg
 
Thread & concurrancy
Onkar Deshpande
 
Ad

More from Riccardo Cardin (7)

PPTX
Design Pattern Comportamentali
Riccardo Cardin
 
PPTX
Design Pattern Creazionali
Riccardo Cardin
 
PPTX
Diagrammi di Attività
Riccardo Cardin
 
PPTX
Diagrammi Use Case
Riccardo Cardin
 
PPTX
Introduzione a UML
Riccardo Cardin
 
PPTX
Mvc e di spring e angular js
Riccardo Cardin
 
PPTX
Reactive programming principles
Riccardo Cardin
 
Design Pattern Comportamentali
Riccardo Cardin
 
Design Pattern Creazionali
Riccardo Cardin
 
Diagrammi di Attività
Riccardo Cardin
 
Diagrammi Use Case
Riccardo Cardin
 
Introduzione a UML
Riccardo Cardin
 
Mvc e di spring e angular js
Riccardo Cardin
 
Reactive programming principles
Riccardo Cardin
 

Recently uploaded (20)

PPTX
Introduction to web development | MERN Stack
JosephLiyon
 
PPTX
IObit Driver Booster Pro 12.4-12.5 license keys 2025-2026
chaudhryakashoo065
 
PDF
What Is an Internal Quality Audit and Why It Matters for Your QMS
BizPortals365
 
PDF
WholeClear Split vCard Software for Split large vCard file
markwillsonmw004
 
PPTX
Android Notifications-A Guide to User-Facing Alerts in Android .pptx
Nabin Dhakal
 
PDF
The Rise of Sustainable Mobile App Solutions by New York Development Firms
ostechnologies16
 
PDF
Dealing with JSON in the relational world
Andres Almiray
 
PDF
AI Software Development Process, Strategies and Challenges
Net-Craft.com
 
PPTX
EO4EU Ocean Monitoring: Maritime Weather Routing Optimsation Use Case
EO4EU
 
PDF
>Nitro Pro Crack 14.36.1.0 + Keygen Free Download [Latest]
utfefguu
 
PPTX
ERP - FICO Presentation BY BSL BOKARO STEEL LIMITED.pptx
ravisranjan
 
PPTX
IDM Crack with Internet Download Manager 6.42 [Latest 2025]
HyperPc soft
 
PPTX
IObit Driver Booster Pro Crack Download Latest Version
chaudhryakashoo065
 
PPTX
CONCEPT OF PROGRAMMING in language .pptx
tamim41
 
PPTX
NeuroStrata: Harnessing Neuro-Symbolic Paradigms for Improved Testability and...
Ivan Ruchkin
 
PDF
IDM Crack with Internet Download Manager 6.42 Build 41
utfefguu
 
PDF
From Chaos to Clarity: Mastering Analytics Governance in the Modern Enterprise
Wiiisdom
 
PPTX
ManageIQ - Sprint 264 Review - Slide Deck
ManageIQ
 
PPTX
IObit Uninstaller Pro 14.3.1.8 Crack Free Download 2025
sdfger qwerty
 
PDF
IObit Uninstaller Pro 14.3.1.8 Crack for Windows Latest
utfefguu
 
Introduction to web development | MERN Stack
JosephLiyon
 
IObit Driver Booster Pro 12.4-12.5 license keys 2025-2026
chaudhryakashoo065
 
What Is an Internal Quality Audit and Why It Matters for Your QMS
BizPortals365
 
WholeClear Split vCard Software for Split large vCard file
markwillsonmw004
 
Android Notifications-A Guide to User-Facing Alerts in Android .pptx
Nabin Dhakal
 
The Rise of Sustainable Mobile App Solutions by New York Development Firms
ostechnologies16
 
Dealing with JSON in the relational world
Andres Almiray
 
AI Software Development Process, Strategies and Challenges
Net-Craft.com
 
EO4EU Ocean Monitoring: Maritime Weather Routing Optimsation Use Case
EO4EU
 
>Nitro Pro Crack 14.36.1.0 + Keygen Free Download [Latest]
utfefguu
 
ERP - FICO Presentation BY BSL BOKARO STEEL LIMITED.pptx
ravisranjan
 
IDM Crack with Internet Download Manager 6.42 [Latest 2025]
HyperPc soft
 
IObit Driver Booster Pro Crack Download Latest Version
chaudhryakashoo065
 
CONCEPT OF PROGRAMMING in language .pptx
tamim41
 
NeuroStrata: Harnessing Neuro-Symbolic Paradigms for Improved Testability and...
Ivan Ruchkin
 
IDM Crack with Internet Download Manager 6.42 Build 41
utfefguu
 
From Chaos to Clarity: Mastering Analytics Governance in the Modern Enterprise
Wiiisdom
 
ManageIQ - Sprint 264 Review - Slide Deck
ManageIQ
 
IObit Uninstaller Pro 14.3.1.8 Crack Free Download 2025
sdfger qwerty
 
IObit Uninstaller Pro 14.3.1.8 Crack for Windows Latest
utfefguu
 

Java- Concurrent programming - Synchronization (part 2)

  • 1. CONCURRENT PROGRAMMING SYNCHRONIZATION (PART 2) PROGRAMMAZIONE CONCORRENTE E DISTR. Università degli Studi di Padova Dipartimento di Matematica Corso di Laurea in Informatica, A.A. 2015 – 2016 [email protected]
  • 2. Programmazione concorrente e distribuita SUMMARY  Conditions  Volatile variables  Atomics  Thread confinement  Immutability 2Riccardo Cardin
  • 3. Programmazione concorrente e distribuita CONDITIONS  Condition variables  Often a thread enters a critical section only to discover that it can’t proceed A condition is not fulfilled  We can try to use a lock 3Riccardo Cardin if (bank.getBalance(from) >= amount) { // Thread might be deactivated at this point bank.transfer(from, to, amount); } public void transfer(int from, int to, int amount) { bankLock.lock(); try { while (accounts[from] < amount) { // wait } // transfer funds } No thread can withdraw money, due to the acquired lock: DEADLOCK!!
  • 4. Programmazione concorrente e distribuita CONDITIONS  To avoid unpleasant deadlock, use conditions  A condition variable is built from a lock  A thread owning the lock, calls await on the condition  The lock is released by the thread  Thread is not made runnable when the lock i available. It stays deactivated until the condition will be fulfilled  Wait set for the condition 4Riccardo Cardin class Bank { private Condition sufficientFunds; public Bank() { // Getting a condition with an evocative name sufficientFunds = bankLock.newCondition(); } } sufficientFunds.await();
  • 5. Programmazione concorrente e distribuita CONDITIONS  When another thread fulfills the condition, it should notify other awaiting threads  One of the awaiting thread will be eligible to acquire the lock and to continue where it left off  Lock must be available  The condition may be fulfilled  Retry to check that condition are met over and over again  An awaiting thread cannot reactive itself: be carefull! 5Riccardo Cardin sufficientFunds.signalAll(); while (!(/* ok to proceed */)) { condition.await(); }
  • 6. Programmazione concorrente e distribuita CONDITIONS  It’s important that some thread calls the signalAll method eventually  If no other thread bother to reactivate a waiting thread, it will neve run again  DEADLOCK!  Call signalAll whenever the state of an object changes 6Riccardo Cardin public void transfer(int from, int to, int amount) { bankLock.lock(); try { while (accounts[from] < amount) sufficientFunds.await(); // transfer funds sufficientFunds.signalAll(); } finally { bankLock.unlock(); } }
  • 7. Programmazione concorrente e distribuita CONDITIONS 7Riccardo Cardin
  • 8. Programmazione concorrente e distribuita CONDITIONS  Intrinsic locks have a single associated condition  The wait method adds a thread to the wait set  The notifyAll method unblocks waiting threads  Having a single condition per intrinsic lock can be inefficient  Which condition has been safisfied? All threads waiting have to be resumed 8Riccardo Cardin public synchronized void transfer(int from, int to, int amount) throws InterruptedException { while (accounts[from] < amount) wait(); // wait on intrinsic object lock // transfer funds notifyAll(); // notify all threads waiting }
  • 9. Programmazione concorrente e distribuita CONDITIONS PITFALLS  What should you use in your code, Locks or synchronized methods  Neither. In many situation it can be used one of the mechanisms of the java.util.concurrent package  i.e. – Blocking queues  If you have to choose, use synchronized blocks  Use Lock / Condition if you really need the additional power that gives to you  You have to define a custom protocol of synchronization 9Riccardo Cardin Do not underestimate the powers of the dark side of concurrency -- Riccardo Cardin
  • 10. Programmazione concorrente e distribuita VOLATILE VARIABLES  Cached values and operations reodering are evil!  A volatile variable is not cached by threads  Share the visibility feature of synchronized  Threads will automatically see the most up-to-date value  ...but non of the atomicity features  Possible race-conditions on multiple operations 10Riccardo Cardin If you write a variable which may next be read by another thread, or you read a variable which may have last been written by another thread, you must use synchronization. -- Brian Goetz private volatile boolean done; public boolean isDone() { return done; } public void setDone() { done = true; }
  • 11. Programmazione concorrente e distribuita VOLATILE VARIABLES  When to use volatile vars instead of locks  Writes do not depend on its current value  DO NOT use for implementing counters!  The variable does not partecipate in invariants with other variables  Slightly better performances 11Riccardo Cardin // Not atomic, you need synchronization public void flipDone() { done = !done; } volatile boolean shutdownRequested; public void shutdown() { shutdownRequested = true; } public void doWork() { while (!shutdownRequested) { // do stuff } } Pattern of use: status flag
  • 12. Programmazione concorrente e distribuita VOLATILE VARIABLES 12Riccardo Cardin
  • 13. Programmazione concorrente e distribuita ATOMICS  There are operations other than setter and getter provided by volatile variables  java.util.concurrent.atomic provides classes that guarantee atomicity of other operations  AtomicInteger, AtomicBoolean, AtomicLong, ... 13Riccardo Cardin class AtomicCounter { private AtomicInteger c = new AtomicInteger(0); public void increment() { c.incrementAndGet(); } public void decrement() { c.decrementAndGet(); } public int value() { return c.get(); } } Uses low level CPU operations, that don’t need synchronization (CAS, compare-and-swap)
  • 14. Programmazione concorrente e distribuita THREAD CONFINEMENT  The best solution to concurrency problems is to not share any mutable state  Use ThreadLocal helper class to give each thread an instance of a class  When thread terminates, value is garbage collected  Do not use as a replacement for global variables  Many JDK classes are not thread-safe  SimpleDateFormat, Random, ... 14Riccardo Cardin public static final ThreadLocal<SimpleDateFormat> dateFormat = new ThreadLocal<SimpleDateFormat>() { protected SimpleDateFormat initialValue() { return new SimpleDateFormat("yyyy-MM-dd"); }}; String dateStamp = dateFormat.get().format(new Date());
  • 15. Programmazione concorrente e distribuita IMMUTABILITY  All the problems described so far have to do with accessing shared mutable state  If object state cannot be modified, the risks go away  Immutable object are simple  There are not different states for complex objects  Immutable object are safer  No untrusted code can modify directly object’s state or retain a reference to modify it later  Java does not formally defined immutability  It is not sufficient declaring all fields as final 15Riccardo Cardin Immutable objects are always thread-safe -- Brian Goetz
  • 16. Programmazione concorrente e distribuita IMMUTABILITY  An object is immutable if:  Its state cannot be modified after construction  So a immutable class has reference only to (effectively) immutable classes  All its fields are final  It is properly constructed  The this reference does not escape during construction, i.e. calling code outside the class, and passing this  Can use mutable state for internal representation  Are this kind of object useful?  There is a big difference between an object been immutbale and the reference to it being immutable 16Riccardo Cardin
  • 17. Programmazione concorrente e distribuita IMMUTABILITY 17Riccardo Cardin
  • 18. Programmazione concorrente e distribuita IMMUTABILITY  The final keyword on fields makes possibile the guarantee on initialization safety  A more limited version of the const in C++  No reorder will be done by the compiler  So, final fields can be accessed without additional synchronization  Better maintainability  It’s time to have a look to an immutable class! 18Riccardo Cardin Immutable objects can be used safely by any thread without additional synchronization. -- Brian Goetz
  • 19. Programmazione concorrente e distribuita IMMUTABILITY 19Riccardo Cardin class OneValueCache { private final BigInteger lastNumber; private final BigInteger[] lastFactors; // Do not use directly a mutable object to construct // an immutable object public OneValueCache(BigInteger i, BigInteger[] factors) { lastNumber = i; lastFactors = Arrays.copyOf(factors, factors.length); } // Do not late ‘escape’ an internal value of the immutable // object. In this way no other code can maliciously modify // that state public BigInteger[] getFactors(BigInteger i) { if (lastNumber == null || !lastNumber.equals(i)) return null; else return Arrays.copyOf(lastFactors, lastFactors.length); } } }
  • 20. Programmazione concorrente e distribuita EXAMPLES 20Riccardo Cardin https://github.com/rcardin/pcd-snippets
  • 21. Programmazione concorrente e distribuita REFERENCES  Chap. 14 «Multithreading», Core Java Volume I - Fundamentals, Cay Horstmann, Gary Cornell, 2012, Prentice Hall  Chap. 3 «Sharing Objects», Java Concurrency in Practice, Brian Goetz, 2006, Addison-Wesley Professional  Atomic Access https://docs.oracle.com/javase/tutorial/essential/concurrency/ato mic.html  Java theory and practice: Managing volatility http://www.ibm.com/developerworks/library/j-jtp06197/  Java theory and practice: Going atomic http://www.ibm.com/developerworks/library/j-jtp11234/  What is the difference of Atomic / Volatile / synchronize? http://stackoverflow.com/questions/9749746/what-is-the- difference-of-atomic-volatile-synchronize 21Riccardo Cardin