SlideShare a Scribd company logo
1 of 27
CONCURRENT PROGRAMMING
SYNCHRONIZATION (PART 1)
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
 Introduction
 Thread-safety
 Race conditions
 Locking
 Locking pitfalls
2Riccardo Cardin
Programmazione concorrente e distribuita
INTRODUCTION
 Threads can reduce development cost and
improve the performance application
 Exploiting multiple processors
 Improved throughput by utilizing available processors
 Simplicity of modeling
 Use every thread to do a specific task is simplier than using
one thread to do them all
 Simplified handling of asynchronous events
 Prevention of server’s stall while it is fulfilling a request
 More reponsive user interfaces
 Use of different threads for GUI and event management
 Event dispatch thread (EDT)
3Riccardo Cardin
Programmazione concorrente e distribuita
INTRODUCTION
 Risks of threads
 Safety hazards
 Without sufficient synchronization, the ordering of
operations in multiple threads is unpredictable
4Riccardo Cardin
public class UnsafeSequence {
private int value;
/** Returns a unique value. */
public int getNext() {
return value++; // Three operations: read, add and store
}
}
With unlucky timing, two
threads could call
getNext and receive the
same value
Programmazione concorrente e distribuita
INTRODUCTION
 Risks of threads
 Liveness hazards
 An activity gets into a state such that it is permanently unable
to make forward progress
 Dining philosophers problem
 Performance hazards
 Poor service time, responsiveness, throughput,
resource consumption, or scalability
 Context switch is not cost free
5Riccardo Cardin
If thread A is waiting for a resource that thread B holds
exclusively, and B never releases it, A will wait forever.
Programmazione concorrente e distribuita
INTRODUCTION
6Riccardo Cardin
Programmazione concorrente e distribuita
THREAD SAFETY
 Writing thread-safe code is about managing
access to shared and mutable state
 Object state is represented by its data
 By Shared, we mean that a variable could be
accessed by multiple threads
 By mutable, that its value could change
 It is far easier to design a class to be thread-safe than
to retrofit it later
7Riccardo Cardin
Whenever more than a thread accesses a given state variable, and one
of them might write to it, they all must coordinate their access to it
using synchronization
-- Brian Goetz
Programmazione concorrente e distribuita
THREAD SAFETY
 There are three ways to fix a mutable shared
variable
 Don’t share the state variable across threads
 Make the state variable immutable
 Use synchronization whenever accessing it
 Object oriented techniques favor thread safety
 Encapsulation
 Immutability
 Clear specification of invariants
8Riccardo Cardin
Stateless objects are always thread-safe.
-- Brian Goetz
Programmazione concorrente e distribuita
THREAD SAFETY
9Riccardo Cardin
Programmazione concorrente e distribuita
RACE CONDITIONS
 Race conditions
 The correctness of a computation depends on
relative timing of multiple threads at runtime
 Atomicity
 A set of statements is not atomic if they are not executed in a
single, indivisible operation
 Read-modifiy-write
 Check-then-act
10Riccardo Cardin
A class is thread-safe if it behaves correctly when accessed from
multiple threads, regardless of the scheduling or interleaving of the
execution of those threads by the runtime environment.
-- Brian Goetz
Programmazione concorrente e distribuita
RACE CONDITIONS
 Read-modify-write race condition
 The value of value is read, then modified adding 1
and finally stored into value variable
 Among the execution of every statement, control flow could
be preempted by another thread
11Riccardo Cardin
public class UnsafeSequence {
private int value;
/** Returns a unique value. */
public int getNext() {
value = value + 1;
return value;
}
}
read value value + 1 store value
Possible preemption
Programmazione concorrente e distribuita
RACE CONDITIONS
 Check-then-act race condition
 Lazy initialization
 The boolean expression depends on a value that is
modified according to it
12Riccardo Cardin
public class LazyInitRace {
private ExpensiveObject instance = null;
public ExpensiveObject getInstance() {
// Check-then-act
if (instance == null)
instance = new ExpensiveObject();
return instance;
}
}
check instance create object store instance
Possible preemption
Programmazione concorrente e distribuita
RACE CONDITIONS
 Compound actions
 Sequences of operations that must be executed
atomically in order to remain thread-safe.
 Read-modify-write and Check-then-act must always be
atomic to be thread-safe
 Atomicity is relative to operation that are executed
on shared state
 The java.util.concurrent.atomic package contains
atomic variable classes for effecting atomic state transitions
13Riccardo Cardin
public class SafeSequence {
private AtomicInteger value;
public int getNext() {
return value.incrementAndGet(); // Atomic read-modify-write
}
}
Programmazione concorrente e distribuita
RACE CONDITIONS
14Riccardo Cardin
Programmazione concorrente e distribuita
SHARING STATE
 Writing correct concurrent programs is primarily
about managing access to shared, mutable state
 It’s all about memory visibility
 We want to ensure that when a thread modifies the state of
an object, other threads can actually see those changes
 If shared state is represented by more than one variable,
atomic classes are not useful
15Riccardo Cardin
public class UnsafeCachedSequence {
private AtomicInteger lastValue;
private AtomicInteger value;
public int getNext() {
// Invariant of the class is not satisfied anymore
lastValue.set(value.get());
return value.incrementAndGet();
}
}
Programmazione concorrente e distribuita
LOCKING
 To preserve state consistency, update related
state variable in a single atomic operation
 Java has a built-in locking mechanism for enforcing
atomicity: synchronized block
 But, it is easier to understand the synchronized
keyword after having seen locks in isolation...
16Riccardo Cardin
synchronized (lock) {
// Access or modify shared state guarded by lock
}
Object that will serve
as lock
Block code to be guarded by
the lock
Programmazione concorrente e distribuita
LOCKING
 Reentrant locking
 Use a Lock to protect a code block
 The construct guarantees that only one thread at time
can enter the critical section
 Always release the lock in a finally block to prevents deadlocks
 The class ReentranctLock implements basic functionalities of
a lock
17Riccardo Cardin
myLock.lock(); // a ReentrantLock object
try {
// Operation in this block are executed atomically
} finally {
// make sure the lock is unlocked even if an
// exceptions thrown
myLock.unlock();
}
Programmazione concorrente e distribuita
LOCKING
 Reentrant locking
 The lock acts as mutual exclusion locks
18Riccardo Cardin
public class SafeCachedSequence {
private Lock lock = new ReentrantLock();
private int lastValue;
private int value;
public int getNext() {
// Invariant of the class is now satisfied
lock.lock();
try {
lastValue = value;
value = value + 1;
int result = value;
} finally {
lock.unlock();
}
return result;
}
}
Now the invariant of
the class is
guaranteed by the
lock: value and
lastValue will always
be updated in a
consistent way
Programmazione concorrente e distribuita
LOCKING
 Reentrant locking
19Riccardo Cardin
Thread 1 Thread 2
getNext getNext
Unsynchronized
Thread 1 Thread 2
getNext
getNext
Synchronized
Programmazione concorrente e distribuita
LOCKING
 Reentrant locking
 Different threads have to synchronize using the same
instance of the lock
 It is called reetrant because a thread can repeatedly
acquire a lock that it already owns
 The lock has a hold count that keeps track of the nested calls
to the lock method
 Prevents deadlocks wrt the subclass mechanism
 Every object in Java (since 1.0) has an intrinsic lock
 The synchronized keyword on a method protects the
access to that method using this reference as lock object
 All method’s code is guarded
20Riccardo Cardin
Programmazione concorrente e distribuita
LOCKING
 Intrinsic locking
 To call the method, a thread must acquire the
intrinsic object lock
 Static synchronized methods use the Class object as lock.
21Riccardo Cardin
public synchronized void method() {
// method body
}
// ...is equivalent to
public void method() {
this.intrinsicLock.lock();
try {
// method body
} finally {
this.intrinsicLock.unlock();
}
}
Programmazione concorrente e distribuita
LOCKING
 Intrinsic locking suffers of performance issues
 Use synchronization by Lock object
 Or synchronized block
 It uses the reference to an object that will serve as lock
22Riccardo Cardin
public class SafeCachedSequence {
private Object lock = new Object();
private int lastValue;
private int value;
public int getNext() {
synchronized (lock) {
lastValue = value;
value = value + 1;
int result = value;
}
return result;
}
}
Programmazione concorrente e distribuita
LOCKING
23Riccardo Cardin
Programmazione concorrente e distribuita
LOCKING PITFALLS
 All the accesses to a mutable shared variable
must be performed with the same lock held
 Not only compound actions
 Not all data needs to be guarded by a lock
 Only mutable data
 All the variables involved in the same invariant
must be guarded by the same lock
 It is not sufficient to use intrinsic lock on every
method
24Riccardo Cardin
// Not thread-safe
if (!vector.contains(element))
vector.add(element);
Programmazione concorrente e distribuita
LOCKING PITFALLS
 Poor concurrency
 Limits by the availability of processing resources, not
by the structure of application itself
 CPU intensive and I/O operations must be outside
synchronized blocks
 Acquiring and releasing a lock has some overhead
 Not break down synchronized blocks too far
25Riccardo Cardin
There is frequently a tension between simplicity and performance.
When implementing a synchronization policy, resist the temptation to
prematurely sacrifice simplicity (potentially compromising safety) for
the sake of performance.
-- Brian Goetz
Programmazione concorrente e distribuita
EXAMPLES
26Riccardo Cardin
https://github.com/rcardin/pcd-snippets
Programmazione concorrente e distribuita
REFERENCES
 Chap. 1 «Introduction», Java Concurrency in Practice, Brian Goetz,
2006, Addison-Wesley Professional
 Chap. 2 «Thread Safety», Java Concurrency in Practice, Brian Goetz,
2006, Addison-Wesley Professional
 Chap. 3 «Sharing Objects», Java Concurrency in Practice, Brian
Goetz, 2006, Addison-Wesley Professional
 Dining philosophers problem
https://en.wikipedia.org/wiki/Dining_philosophers_problem
 Chap. 14 «Multithreading», Core Java Volume I - Fundamentals, Cay
Horstmann, Gary Cornell, 2012, Prentice Hall
 Intrinsic Locks and Synchronization
https://docs.oracle.com/javase/tutorial/essential/concurrency/lock
sync.html
27Riccardo Cardin

More Related Content

What's hot

Java - Processing input and output
Java - Processing input and outputJava - Processing input and output
Java - Processing input and outputRiccardo Cardin
 
Unit I Advanced Java Programming Course
Unit I   Advanced Java Programming CourseUnit I   Advanced Java Programming Course
Unit I Advanced Java Programming Courseparveen837153
 
Managing Binary Compatibility in Scala (Scala Days 2011)
Managing Binary Compatibility in Scala (Scala Days 2011)Managing Binary Compatibility in Scala (Scala Days 2011)
Managing Binary Compatibility in Scala (Scala Days 2011)mircodotta
 
Introduction to-vhdl
Introduction to-vhdlIntroduction to-vhdl
Introduction to-vhdlNeeraj Gupta
 
Advanced Reflection in Java
Advanced Reflection in JavaAdvanced Reflection in Java
Advanced Reflection in Javakim.mens
 
Java session13
Java session13Java session13
Java session13Niit Care
 
Java Faqs useful for freshers and experienced
Java Faqs useful for freshers and experiencedJava Faqs useful for freshers and experienced
Java Faqs useful for freshers and experiencedyearninginjava
 
Detecting aspect-specific code smells using Ekeko for AspectJ
Detecting aspect-specific code smells using Ekeko for AspectJDetecting aspect-specific code smells using Ekeko for AspectJ
Detecting aspect-specific code smells using Ekeko for AspectJCoen De Roover
 
Method Handles in Java
Method Handles in JavaMethod Handles in Java
Method Handles in Javahendersk
 
Ekeko Technology Showdown at SoTeSoLa 2012
Ekeko Technology Showdown at SoTeSoLa 2012Ekeko Technology Showdown at SoTeSoLa 2012
Ekeko Technology Showdown at SoTeSoLa 2012Coen De Roover
 
The SOUL Tool Suite for Querying Programs in Symbiosis with Eclipse
The SOUL Tool Suite for Querying Programs in Symbiosis with EclipseThe SOUL Tool Suite for Querying Programs in Symbiosis with Eclipse
The SOUL Tool Suite for Querying Programs in Symbiosis with EclipseCoen De Roover
 
Javainterview
JavainterviewJavainterview
JavainterviewAmarjit03
 
Java Concurrency Quick Guide
Java Concurrency Quick GuideJava Concurrency Quick Guide
Java Concurrency Quick GuideAnton Shchastnyi
 
System Verilog Functional Coverage
System Verilog Functional CoverageSystem Verilog Functional Coverage
System Verilog Functional Coveragerraimi
 
JavaFX In Practice
JavaFX In PracticeJavaFX In Practice
JavaFX In PracticeRichard Bair
 
Strategy and Template Pattern
Strategy and Template PatternStrategy and Template Pattern
Strategy and Template PatternJonathan Simon
 

What's hot (20)

Java - Processing input and output
Java - Processing input and outputJava - Processing input and output
Java - Processing input and output
 
Unit I Advanced Java Programming Course
Unit I   Advanced Java Programming CourseUnit I   Advanced Java Programming Course
Unit I Advanced Java Programming Course
 
Managing Binary Compatibility in Scala (Scala Days 2011)
Managing Binary Compatibility in Scala (Scala Days 2011)Managing Binary Compatibility in Scala (Scala Days 2011)
Managing Binary Compatibility in Scala (Scala Days 2011)
 
Introduction to-vhdl
Introduction to-vhdlIntroduction to-vhdl
Introduction to-vhdl
 
Advanced Reflection in Java
Advanced Reflection in JavaAdvanced Reflection in Java
Advanced Reflection in Java
 
Introduction to VHDL
Introduction to VHDLIntroduction to VHDL
Introduction to VHDL
 
Java session13
Java session13Java session13
Java session13
 
Java Faqs useful for freshers and experienced
Java Faqs useful for freshers and experiencedJava Faqs useful for freshers and experienced
Java Faqs useful for freshers and experienced
 
Detecting aspect-specific code smells using Ekeko for AspectJ
Detecting aspect-specific code smells using Ekeko for AspectJDetecting aspect-specific code smells using Ekeko for AspectJ
Detecting aspect-specific code smells using Ekeko for AspectJ
 
J3d hibernate
J3d hibernateJ3d hibernate
J3d hibernate
 
Java - Sockets
Java - SocketsJava - Sockets
Java - Sockets
 
Method Handles in Java
Method Handles in JavaMethod Handles in Java
Method Handles in Java
 
Lecture1
Lecture1Lecture1
Lecture1
 
Ekeko Technology Showdown at SoTeSoLa 2012
Ekeko Technology Showdown at SoTeSoLa 2012Ekeko Technology Showdown at SoTeSoLa 2012
Ekeko Technology Showdown at SoTeSoLa 2012
 
The SOUL Tool Suite for Querying Programs in Symbiosis with Eclipse
The SOUL Tool Suite for Querying Programs in Symbiosis with EclipseThe SOUL Tool Suite for Querying Programs in Symbiosis with Eclipse
The SOUL Tool Suite for Querying Programs in Symbiosis with Eclipse
 
Javainterview
JavainterviewJavainterview
Javainterview
 
Java Concurrency Quick Guide
Java Concurrency Quick GuideJava Concurrency Quick Guide
Java Concurrency Quick Guide
 
System Verilog Functional Coverage
System Verilog Functional CoverageSystem Verilog Functional Coverage
System Verilog Functional Coverage
 
JavaFX In Practice
JavaFX In PracticeJavaFX In Practice
JavaFX In Practice
 
Strategy and Template Pattern
Strategy and Template PatternStrategy and Template Pattern
Strategy and Template Pattern
 

Viewers also liked

Java Graphics Programming
Java Graphics ProgrammingJava Graphics Programming
Java Graphics ProgrammingRiccardo Cardin
 
Design Pattern Architetturali - Dependency Injection
Design Pattern Architetturali - Dependency InjectionDesign Pattern Architetturali - Dependency Injection
Design Pattern Architetturali - Dependency InjectionRiccardo Cardin
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections frameworkRiccardo Cardin
 
Scala - the good, the bad and the very ugly
Scala - the good, the bad and the very uglyScala - the good, the bad and the very ugly
Scala - the good, the bad and the very uglyBozhidar Bozhanov
 
Design Pattern Strutturali
Design Pattern StrutturaliDesign Pattern Strutturali
Design Pattern StrutturaliRiccardo Cardin
 
Design pattern architetturali Model View Controller, MVP e MVVM
Design pattern architetturali   Model View Controller, MVP e MVVMDesign pattern architetturali   Model View Controller, MVP e MVVM
Design pattern architetturali Model View Controller, MVP e MVVMRiccardo Cardin
 
Errori comuni nei documenti di Analisi dei Requisiti
Errori comuni nei documenti di Analisi dei RequisitiErrori comuni nei documenti di Analisi dei Requisiti
Errori comuni nei documenti di Analisi dei RequisitiRiccardo Cardin
 
Presto updates to 0.178
Presto updates to 0.178Presto updates to 0.178
Presto updates to 0.178Kai Sasaki
 
Introduzione ai Design Pattern
Introduzione ai Design PatternIntroduzione ai Design Pattern
Introduzione ai Design PatternRiccardo Cardin
 
Software architecture patterns
Software architecture patternsSoftware architecture patterns
Software architecture patternsRiccardo Cardin
 
Scala For Java Programmers
Scala For Java ProgrammersScala For Java Programmers
Scala For Java ProgrammersEnno Runne
 
SOLID - Principles of Object Oriented Design
SOLID - Principles of Object Oriented DesignSOLID - Principles of Object Oriented Design
SOLID - Principles of Object Oriented DesignRiccardo Cardin
 

Viewers also liked (14)

Java Graphics Programming
Java Graphics ProgrammingJava Graphics Programming
Java Graphics Programming
 
Design Pattern Architetturali - Dependency Injection
Design Pattern Architetturali - Dependency InjectionDesign Pattern Architetturali - Dependency Injection
Design Pattern Architetturali - Dependency Injection
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections framework
 
Scala - the good, the bad and the very ugly
Scala - the good, the bad and the very uglyScala - the good, the bad and the very ugly
Scala - the good, the bad and the very ugly
 
Design Pattern Strutturali
Design Pattern StrutturaliDesign Pattern Strutturali
Design Pattern Strutturali
 
Design pattern architetturali Model View Controller, MVP e MVVM
Design pattern architetturali   Model View Controller, MVP e MVVMDesign pattern architetturali   Model View Controller, MVP e MVVM
Design pattern architetturali Model View Controller, MVP e MVVM
 
Diagrammi di Sequenza
Diagrammi di SequenzaDiagrammi di Sequenza
Diagrammi di Sequenza
 
Errori comuni nei documenti di Analisi dei Requisiti
Errori comuni nei documenti di Analisi dei RequisitiErrori comuni nei documenti di Analisi dei Requisiti
Errori comuni nei documenti di Analisi dei Requisiti
 
Presto updates to 0.178
Presto updates to 0.178Presto updates to 0.178
Presto updates to 0.178
 
Introduzione ai Design Pattern
Introduzione ai Design PatternIntroduzione ai Design Pattern
Introduzione ai Design Pattern
 
Diagrammi delle Classi
Diagrammi delle ClassiDiagrammi delle Classi
Diagrammi delle Classi
 
Software architecture patterns
Software architecture patternsSoftware architecture patterns
Software architecture patterns
 
Scala For Java Programmers
Scala For Java ProgrammersScala For Java Programmers
Scala For Java Programmers
 
SOLID - Principles of Object Oriented Design
SOLID - Principles of Object Oriented DesignSOLID - Principles of Object Oriented Design
SOLID - Principles of Object Oriented Design
 

Similar to Java- Concurrent programming - Synchronization (part 1)

Networking and Security in Java
Networking and Security in JavaNetworking and Security in Java
Networking and Security in JavaConestoga Collage
 
Concurrency: Best Practices
Concurrency: Best PracticesConcurrency: Best Practices
Concurrency: Best PracticesIndicThreads
 
Architectural patterns part 3
Architectural patterns part 3Architectural patterns part 3
Architectural patterns part 3assinha
 
Tech Talks_04.07.15_Session 1_Jeni Markishka & Martin Hristov_Concurrent Prog...
Tech Talks_04.07.15_Session 1_Jeni Markishka & Martin Hristov_Concurrent Prog...Tech Talks_04.07.15_Session 1_Jeni Markishka & Martin Hristov_Concurrent Prog...
Tech Talks_04.07.15_Session 1_Jeni Markishka & Martin Hristov_Concurrent Prog...EPAM_Systems_Bulgaria
 
Concurrent programming without synchronization
Concurrent programming without synchronizationConcurrent programming without synchronization
Concurrent programming without synchronizationMartin Hristov
 
Meetup - Singleton & DI/IoC
Meetup - Singleton & DI/IoCMeetup - Singleton & DI/IoC
Meetup - Singleton & DI/IoCDusan Zamurovic
 
Java Performance Tuning
Java Performance TuningJava Performance Tuning
Java Performance TuningMinh Hoang
 
Core Java Programming Language (JSE) : Chapter XII - Threads
Core Java Programming Language (JSE) : Chapter XII -  ThreadsCore Java Programming Language (JSE) : Chapter XII -  Threads
Core Java Programming Language (JSE) : Chapter XII - ThreadsWebStackAcademy
 
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)David McCarter
 
Java 5 concurrency
Java 5 concurrencyJava 5 concurrency
Java 5 concurrencypriyank09
 
Insecure Java Deserialization
Insecure Java DeserializationInsecure Java Deserialization
Insecure Java DeserializationShiv Sahni
 
ADVANCED MALWARE THREATS -- NO HAT 2019 (BERGAMO / ITALY)
ADVANCED MALWARE THREATS --  NO HAT 2019 (BERGAMO / ITALY)ADVANCED MALWARE THREATS --  NO HAT 2019 (BERGAMO / ITALY)
ADVANCED MALWARE THREATS -- NO HAT 2019 (BERGAMO / ITALY)Alexandre Borges
 
JDD 2016 - Michał Balinski, Oleksandr Goldobin - Practical Non Blocking Micro...
JDD 2016 - Michał Balinski, Oleksandr Goldobin - Practical Non Blocking Micro...JDD 2016 - Michał Balinski, Oleksandr Goldobin - Practical Non Blocking Micro...
JDD 2016 - Michał Balinski, Oleksandr Goldobin - Practical Non Blocking Micro...PROIDEA
 
[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronization[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronizationxuehan zhu
 

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

Networking and Security in Java
Networking and Security in JavaNetworking and Security in Java
Networking and Security in Java
 
Concurrency: Best Practices
Concurrency: Best PracticesConcurrency: Best Practices
Concurrency: Best Practices
 
Architectural patterns part 3
Architectural patterns part 3Architectural patterns part 3
Architectural patterns part 3
 
The Java Memory Model
The Java Memory ModelThe Java Memory Model
The Java Memory Model
 
Concurrency
ConcurrencyConcurrency
Concurrency
 
Tech Talks_04.07.15_Session 1_Jeni Markishka & Martin Hristov_Concurrent Prog...
Tech Talks_04.07.15_Session 1_Jeni Markishka & Martin Hristov_Concurrent Prog...Tech Talks_04.07.15_Session 1_Jeni Markishka & Martin Hristov_Concurrent Prog...
Tech Talks_04.07.15_Session 1_Jeni Markishka & Martin Hristov_Concurrent Prog...
 
Concurrent programming without synchronization
Concurrent programming without synchronizationConcurrent programming without synchronization
Concurrent programming without synchronization
 
Introduction+To+Java+Concurrency
Introduction+To+Java+ConcurrencyIntroduction+To+Java+Concurrency
Introduction+To+Java+Concurrency
 
Meetup - Singleton & DI/IoC
Meetup - Singleton & DI/IoCMeetup - Singleton & DI/IoC
Meetup - Singleton & DI/IoC
 
Java Performance Tuning
Java Performance TuningJava Performance Tuning
Java Performance Tuning
 
Core Java Programming Language (JSE) : Chapter XII - Threads
Core Java Programming Language (JSE) : Chapter XII -  ThreadsCore Java Programming Language (JSE) : Chapter XII -  Threads
Core Java Programming Language (JSE) : Chapter XII - Threads
 
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
 
04 threads
04 threads04 threads
04 threads
 
Byte code field report
Byte code field reportByte code field report
Byte code field report
 
Java 5 concurrency
Java 5 concurrencyJava 5 concurrency
Java 5 concurrency
 
Insecure Java Deserialization
Insecure Java DeserializationInsecure Java Deserialization
Insecure Java Deserialization
 
ADVANCED MALWARE THREATS -- NO HAT 2019 (BERGAMO / ITALY)
ADVANCED MALWARE THREATS --  NO HAT 2019 (BERGAMO / ITALY)ADVANCED MALWARE THREATS --  NO HAT 2019 (BERGAMO / ITALY)
ADVANCED MALWARE THREATS -- NO HAT 2019 (BERGAMO / ITALY)
 
JDD 2016 - Michał Balinski, Oleksandr Goldobin - Practical Non Blocking Micro...
JDD 2016 - Michał Balinski, Oleksandr Goldobin - Practical Non Blocking Micro...JDD 2016 - Michał Balinski, Oleksandr Goldobin - Practical Non Blocking Micro...
JDD 2016 - Michał Balinski, Oleksandr Goldobin - Practical Non Blocking Micro...
 
[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronization[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronization
 
Concurrency
ConcurrencyConcurrency
Concurrency
 

More from Riccardo Cardin

Design Pattern Comportamentali
Design Pattern ComportamentaliDesign Pattern Comportamentali
Design Pattern ComportamentaliRiccardo Cardin
 
Design Pattern Creazionali
Design Pattern CreazionaliDesign Pattern Creazionali
Design Pattern CreazionaliRiccardo Cardin
 
Mvc e di spring e angular js
Mvc e di   spring e angular jsMvc e di   spring e angular js
Mvc e di spring e angular jsRiccardo Cardin
 
Reactive programming principles
Reactive programming principlesReactive programming principles
Reactive programming principlesRiccardo Cardin
 

More from Riccardo Cardin (7)

Design Pattern Comportamentali
Design Pattern ComportamentaliDesign Pattern Comportamentali
Design Pattern Comportamentali
 
Design Pattern Creazionali
Design Pattern CreazionaliDesign Pattern Creazionali
Design Pattern Creazionali
 
Diagrammi di Attività
Diagrammi di AttivitàDiagrammi di Attività
Diagrammi di Attività
 
Diagrammi Use Case
Diagrammi Use CaseDiagrammi Use Case
Diagrammi Use Case
 
Introduzione a UML
Introduzione a UMLIntroduzione a UML
Introduzione a UML
 
Mvc e di spring e angular js
Mvc e di   spring e angular jsMvc e di   spring e angular js
Mvc e di spring e angular js
 
Reactive programming principles
Reactive programming principlesReactive programming principles
Reactive programming principles
 

Recently uploaded

VictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics
 
What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesVictoriaMetrics
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLionel Briand
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolsosttopstonverter
 
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4jGraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4jNeo4j
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
Ronisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited CatalogueRonisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited Catalogueitservices996
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdfAndrey Devyatkin
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfRTS corp
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsJean Silva
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slidesvaideheekore1
 
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...Bert Jan Schrijver
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecturerahul_net
 
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingShane Coughlan
 
Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptxVinzoCenzo
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldRoberto Pérez Alcolea
 

Recently uploaded (20)

VictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
 
What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 Updates
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and Repair
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration tools
 
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4jGraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
Ronisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited CatalogueRonisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited Catalogue
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero results
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slides
 
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecture
 
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
 
Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptx
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository world
 

Java- Concurrent programming - Synchronization (part 1)

  • 1. CONCURRENT PROGRAMMING SYNCHRONIZATION (PART 1) 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
  • 2. Programmazione concorrente e distribuita SUMMARY  Introduction  Thread-safety  Race conditions  Locking  Locking pitfalls 2Riccardo Cardin
  • 3. Programmazione concorrente e distribuita INTRODUCTION  Threads can reduce development cost and improve the performance application  Exploiting multiple processors  Improved throughput by utilizing available processors  Simplicity of modeling  Use every thread to do a specific task is simplier than using one thread to do them all  Simplified handling of asynchronous events  Prevention of server’s stall while it is fulfilling a request  More reponsive user interfaces  Use of different threads for GUI and event management  Event dispatch thread (EDT) 3Riccardo Cardin
  • 4. Programmazione concorrente e distribuita INTRODUCTION  Risks of threads  Safety hazards  Without sufficient synchronization, the ordering of operations in multiple threads is unpredictable 4Riccardo Cardin public class UnsafeSequence { private int value; /** Returns a unique value. */ public int getNext() { return value++; // Three operations: read, add and store } } With unlucky timing, two threads could call getNext and receive the same value
  • 5. Programmazione concorrente e distribuita INTRODUCTION  Risks of threads  Liveness hazards  An activity gets into a state such that it is permanently unable to make forward progress  Dining philosophers problem  Performance hazards  Poor service time, responsiveness, throughput, resource consumption, or scalability  Context switch is not cost free 5Riccardo Cardin If thread A is waiting for a resource that thread B holds exclusively, and B never releases it, A will wait forever.
  • 6. Programmazione concorrente e distribuita INTRODUCTION 6Riccardo Cardin
  • 7. Programmazione concorrente e distribuita THREAD SAFETY  Writing thread-safe code is about managing access to shared and mutable state  Object state is represented by its data  By Shared, we mean that a variable could be accessed by multiple threads  By mutable, that its value could change  It is far easier to design a class to be thread-safe than to retrofit it later 7Riccardo Cardin Whenever more than a thread accesses a given state variable, and one of them might write to it, they all must coordinate their access to it using synchronization -- Brian Goetz
  • 8. Programmazione concorrente e distribuita THREAD SAFETY  There are three ways to fix a mutable shared variable  Don’t share the state variable across threads  Make the state variable immutable  Use synchronization whenever accessing it  Object oriented techniques favor thread safety  Encapsulation  Immutability  Clear specification of invariants 8Riccardo Cardin Stateless objects are always thread-safe. -- Brian Goetz
  • 9. Programmazione concorrente e distribuita THREAD SAFETY 9Riccardo Cardin
  • 10. Programmazione concorrente e distribuita RACE CONDITIONS  Race conditions  The correctness of a computation depends on relative timing of multiple threads at runtime  Atomicity  A set of statements is not atomic if they are not executed in a single, indivisible operation  Read-modifiy-write  Check-then-act 10Riccardo Cardin A class is thread-safe if it behaves correctly when accessed from multiple threads, regardless of the scheduling or interleaving of the execution of those threads by the runtime environment. -- Brian Goetz
  • 11. Programmazione concorrente e distribuita RACE CONDITIONS  Read-modify-write race condition  The value of value is read, then modified adding 1 and finally stored into value variable  Among the execution of every statement, control flow could be preempted by another thread 11Riccardo Cardin public class UnsafeSequence { private int value; /** Returns a unique value. */ public int getNext() { value = value + 1; return value; } } read value value + 1 store value Possible preemption
  • 12. Programmazione concorrente e distribuita RACE CONDITIONS  Check-then-act race condition  Lazy initialization  The boolean expression depends on a value that is modified according to it 12Riccardo Cardin public class LazyInitRace { private ExpensiveObject instance = null; public ExpensiveObject getInstance() { // Check-then-act if (instance == null) instance = new ExpensiveObject(); return instance; } } check instance create object store instance Possible preemption
  • 13. Programmazione concorrente e distribuita RACE CONDITIONS  Compound actions  Sequences of operations that must be executed atomically in order to remain thread-safe.  Read-modify-write and Check-then-act must always be atomic to be thread-safe  Atomicity is relative to operation that are executed on shared state  The java.util.concurrent.atomic package contains atomic variable classes for effecting atomic state transitions 13Riccardo Cardin public class SafeSequence { private AtomicInteger value; public int getNext() { return value.incrementAndGet(); // Atomic read-modify-write } }
  • 14. Programmazione concorrente e distribuita RACE CONDITIONS 14Riccardo Cardin
  • 15. Programmazione concorrente e distribuita SHARING STATE  Writing correct concurrent programs is primarily about managing access to shared, mutable state  It’s all about memory visibility  We want to ensure that when a thread modifies the state of an object, other threads can actually see those changes  If shared state is represented by more than one variable, atomic classes are not useful 15Riccardo Cardin public class UnsafeCachedSequence { private AtomicInteger lastValue; private AtomicInteger value; public int getNext() { // Invariant of the class is not satisfied anymore lastValue.set(value.get()); return value.incrementAndGet(); } }
  • 16. Programmazione concorrente e distribuita LOCKING  To preserve state consistency, update related state variable in a single atomic operation  Java has a built-in locking mechanism for enforcing atomicity: synchronized block  But, it is easier to understand the synchronized keyword after having seen locks in isolation... 16Riccardo Cardin synchronized (lock) { // Access or modify shared state guarded by lock } Object that will serve as lock Block code to be guarded by the lock
  • 17. Programmazione concorrente e distribuita LOCKING  Reentrant locking  Use a Lock to protect a code block  The construct guarantees that only one thread at time can enter the critical section  Always release the lock in a finally block to prevents deadlocks  The class ReentranctLock implements basic functionalities of a lock 17Riccardo Cardin myLock.lock(); // a ReentrantLock object try { // Operation in this block are executed atomically } finally { // make sure the lock is unlocked even if an // exceptions thrown myLock.unlock(); }
  • 18. Programmazione concorrente e distribuita LOCKING  Reentrant locking  The lock acts as mutual exclusion locks 18Riccardo Cardin public class SafeCachedSequence { private Lock lock = new ReentrantLock(); private int lastValue; private int value; public int getNext() { // Invariant of the class is now satisfied lock.lock(); try { lastValue = value; value = value + 1; int result = value; } finally { lock.unlock(); } return result; } } Now the invariant of the class is guaranteed by the lock: value and lastValue will always be updated in a consistent way
  • 19. Programmazione concorrente e distribuita LOCKING  Reentrant locking 19Riccardo Cardin Thread 1 Thread 2 getNext getNext Unsynchronized Thread 1 Thread 2 getNext getNext Synchronized
  • 20. Programmazione concorrente e distribuita LOCKING  Reentrant locking  Different threads have to synchronize using the same instance of the lock  It is called reetrant because a thread can repeatedly acquire a lock that it already owns  The lock has a hold count that keeps track of the nested calls to the lock method  Prevents deadlocks wrt the subclass mechanism  Every object in Java (since 1.0) has an intrinsic lock  The synchronized keyword on a method protects the access to that method using this reference as lock object  All method’s code is guarded 20Riccardo Cardin
  • 21. Programmazione concorrente e distribuita LOCKING  Intrinsic locking  To call the method, a thread must acquire the intrinsic object lock  Static synchronized methods use the Class object as lock. 21Riccardo Cardin public synchronized void method() { // method body } // ...is equivalent to public void method() { this.intrinsicLock.lock(); try { // method body } finally { this.intrinsicLock.unlock(); } }
  • 22. Programmazione concorrente e distribuita LOCKING  Intrinsic locking suffers of performance issues  Use synchronization by Lock object  Or synchronized block  It uses the reference to an object that will serve as lock 22Riccardo Cardin public class SafeCachedSequence { private Object lock = new Object(); private int lastValue; private int value; public int getNext() { synchronized (lock) { lastValue = value; value = value + 1; int result = value; } return result; } }
  • 23. Programmazione concorrente e distribuita LOCKING 23Riccardo Cardin
  • 24. Programmazione concorrente e distribuita LOCKING PITFALLS  All the accesses to a mutable shared variable must be performed with the same lock held  Not only compound actions  Not all data needs to be guarded by a lock  Only mutable data  All the variables involved in the same invariant must be guarded by the same lock  It is not sufficient to use intrinsic lock on every method 24Riccardo Cardin // Not thread-safe if (!vector.contains(element)) vector.add(element);
  • 25. Programmazione concorrente e distribuita LOCKING PITFALLS  Poor concurrency  Limits by the availability of processing resources, not by the structure of application itself  CPU intensive and I/O operations must be outside synchronized blocks  Acquiring and releasing a lock has some overhead  Not break down synchronized blocks too far 25Riccardo Cardin There is frequently a tension between simplicity and performance. When implementing a synchronization policy, resist the temptation to prematurely sacrifice simplicity (potentially compromising safety) for the sake of performance. -- Brian Goetz
  • 26. Programmazione concorrente e distribuita EXAMPLES 26Riccardo Cardin https://github.com/rcardin/pcd-snippets
  • 27. Programmazione concorrente e distribuita REFERENCES  Chap. 1 «Introduction», Java Concurrency in Practice, Brian Goetz, 2006, Addison-Wesley Professional  Chap. 2 «Thread Safety», Java Concurrency in Practice, Brian Goetz, 2006, Addison-Wesley Professional  Chap. 3 «Sharing Objects», Java Concurrency in Practice, Brian Goetz, 2006, Addison-Wesley Professional  Dining philosophers problem https://en.wikipedia.org/wiki/Dining_philosophers_problem  Chap. 14 «Multithreading», Core Java Volume I - Fundamentals, Cay Horstmann, Gary Cornell, 2012, Prentice Hall  Intrinsic Locks and Synchronization https://docs.oracle.com/javase/tutorial/essential/concurrency/lock sync.html 27Riccardo Cardin