SlideShare ist ein Scribd-Unternehmen logo
1 von 21
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

Weitere ähnliche Inhalte

Was ist angesagt?

Introduction to-vhdl
Introduction to-vhdlIntroduction to-vhdl
Introduction to-vhdlNeeraj Gupta
 
Vhdl introduction
Vhdl introductionVhdl introduction
Vhdl introductionDhaval Shukla
 
Close Encounters in MDD: when models meet code
Close Encounters in MDD: when models meet codeClose Encounters in MDD: when models meet code
Close Encounters in MDD: when models meet codelbergmans
 
Generics and collections in Java
Generics and collections in JavaGenerics and collections in Java
Generics and collections in JavaGurpreet singh
 
Concurrency: Best Practices
Concurrency: Best PracticesConcurrency: Best Practices
Concurrency: Best PracticesIndicThreads
 
System verilog coverage
System verilog coverageSystem verilog coverage
System verilog coveragePushpa Yakkala
 
VHDL - Enumerated Types (Part 3)
VHDL - Enumerated Types (Part 3)VHDL - Enumerated Types (Part 3)
VHDL - Enumerated Types (Part 3)Abhilash Nair
 
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
 
A rendering architecture
A rendering architectureA rendering architecture
A rendering architectureSungkwan Park
 
INTRODUCTION TO VHDL
INTRODUCTION    TO    VHDLINTRODUCTION    TO    VHDL
INTRODUCTION TO VHDLkarthikpunuru
 
Kroening et al, v2c a verilog to c translator
Kroening et al, v2c   a verilog to c translatorKroening et al, v2c   a verilog to c translator
Kroening et al, v2c a verilog to c translatorsce,bhopal
 
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
 
Reactive Qt - Ivan Čukić (Qt World Summit 2015)
Reactive Qt - Ivan Čukić (Qt World Summit 2015)Reactive Qt - Ivan Čukić (Qt World Summit 2015)
Reactive Qt - Ivan Čukić (Qt World Summit 2015)Ivan Čukić
 
Extending and scripting PDT
Extending and scripting PDTExtending and scripting PDT
Extending and scripting PDTWilliam Candillon
 
Strategy and Template Pattern
Strategy and Template PatternStrategy and Template Pattern
Strategy and Template PatternJonathan Simon
 
Introduction to VHDL
Introduction to VHDLIntroduction to VHDL
Introduction to VHDLYaser Kalifa
 

Was ist angesagt? (20)

Introduction to-vhdl
Introduction to-vhdlIntroduction to-vhdl
Introduction to-vhdl
 
Introduction to VHDL
Introduction to VHDLIntroduction to VHDL
Introduction to VHDL
 
Lecture1
Lecture1Lecture1
Lecture1
 
Vhdl introduction
Vhdl introductionVhdl introduction
Vhdl introduction
 
Close Encounters in MDD: when models meet code
Close Encounters in MDD: when models meet codeClose Encounters in MDD: when models meet code
Close Encounters in MDD: when models meet code
 
Generics and collections in Java
Generics and collections in JavaGenerics and collections in Java
Generics and collections in Java
 
Concurrency: Best Practices
Concurrency: Best PracticesConcurrency: Best Practices
Concurrency: Best Practices
 
System verilog coverage
System verilog coverageSystem verilog coverage
System verilog coverage
 
VHDL - Enumerated Types (Part 3)
VHDL - Enumerated Types (Part 3)VHDL - Enumerated Types (Part 3)
VHDL - Enumerated Types (Part 3)
 
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
 
A rendering architecture
A rendering architectureA rendering architecture
A rendering architecture
 
INTRODUCTION TO VHDL
INTRODUCTION    TO    VHDLINTRODUCTION    TO    VHDL
INTRODUCTION TO VHDL
 
Kroening et al, v2c a verilog to c translator
Kroening et al, v2c   a verilog to c translatorKroening et al, v2c   a verilog to c translator
Kroening et al, v2c a verilog to c translator
 
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
 
Reactive Qt - Ivan Čukić (Qt World Summit 2015)
Reactive Qt - Ivan Čukić (Qt World Summit 2015)Reactive Qt - Ivan Čukić (Qt World Summit 2015)
Reactive Qt - Ivan Čukić (Qt World Summit 2015)
 
Extending and scripting PDT
Extending and scripting PDTExtending and scripting PDT
Extending and scripting PDT
 
VHDL course
VHDL courseVHDL course
VHDL course
 
Strategy and Template Pattern
Strategy and Template PatternStrategy and Template Pattern
Strategy and Template Pattern
 
Introduction to VHDL
Introduction to VHDLIntroduction to VHDL
Introduction to VHDL
 

Andere mochten auch

Design Pattern Strutturali
Design Pattern StrutturaliDesign Pattern Strutturali
Design Pattern StrutturaliRiccardo Cardin
 
SOLID - Principles of Object Oriented Design
SOLID - Principles of Object Oriented DesignSOLID - Principles of Object Oriented Design
SOLID - Principles of Object Oriented DesignRiccardo Cardin
 
Scala For Java Programmers
Scala For Java ProgrammersScala For Java Programmers
Scala For Java ProgrammersEnno Runne
 
Software architecture patterns
Software architecture patternsSoftware architecture patterns
Software architecture patternsRiccardo Cardin
 
Presto updates to 0.178
Presto updates to 0.178Presto updates to 0.178
Presto updates to 0.178Kai Sasaki
 
Diagrammi di Sequenza
Diagrammi di SequenzaDiagrammi di Sequenza
Diagrammi di SequenzaRiccardo 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
 
Diagrammi delle Classi
Diagrammi delle ClassiDiagrammi delle Classi
Diagrammi delle ClassiRiccardo Cardin
 
Introduzione ai Design Pattern
Introduzione ai Design PatternIntroduzione ai Design Pattern
Introduzione ai Design PatternRiccardo Cardin
 
Java - Processing input and output
Java - Processing input and outputJava - Processing input and output
Java - Processing input and outputRiccardo 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
 
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
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections frameworkRiccardo Cardin
 
Design Pattern Architetturali - Dependency Injection
Design Pattern Architetturali - Dependency InjectionDesign Pattern Architetturali - Dependency Injection
Design Pattern Architetturali - Dependency InjectionRiccardo Cardin
 

Andere mochten auch (15)

Design Pattern Strutturali
Design Pattern StrutturaliDesign Pattern Strutturali
Design Pattern Strutturali
 
SOLID - Principles of Object Oriented Design
SOLID - Principles of Object Oriented DesignSOLID - Principles of Object Oriented Design
SOLID - Principles of Object Oriented Design
 
Scala For Java Programmers
Scala For Java ProgrammersScala For Java Programmers
Scala For Java Programmers
 
Software architecture patterns
Software architecture patternsSoftware architecture patterns
Software architecture patterns
 
Presto updates to 0.178
Presto updates to 0.178Presto updates to 0.178
Presto updates to 0.178
 
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
 
Diagrammi delle Classi
Diagrammi delle ClassiDiagrammi delle Classi
Diagrammi delle Classi
 
Introduzione ai Design Pattern
Introduzione ai Design PatternIntroduzione ai Design Pattern
Introduzione ai Design Pattern
 
Java - Processing input and output
Java - Processing input and outputJava - Processing input and output
Java - Processing input and output
 
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
 
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
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections framework
 
Design Pattern Architetturali - Dependency Injection
Design Pattern Architetturali - Dependency InjectionDesign Pattern Architetturali - Dependency Injection
Design Pattern Architetturali - Dependency Injection
 
Java - Sockets
Java - SocketsJava - Sockets
Java - Sockets
 

Ähnlich wie Java- Concurrent programming - Synchronization (part 2)

Stateful streaming data pipelines
Stateful streaming data pipelinesStateful streaming data pipelines
Stateful streaming data pipelinesTimothy Farkas
 
Native Java with GraalVM
Native Java with GraalVMNative Java with GraalVM
Native Java with GraalVMSylvain Wallez
 
Taming startup dynamics - Magnus Jungsbluth & Domagoj Cosic
Taming startup dynamics - Magnus Jungsbluth & Domagoj CosicTaming startup dynamics - Magnus Jungsbluth & Domagoj Cosic
Taming startup dynamics - Magnus Jungsbluth & Domagoj Cosicmfrancis
 
Android Loaders : Reloaded
Android Loaders : ReloadedAndroid Loaders : Reloaded
Android Loaders : Reloadedcbeyls
 
Checking Oracle VM VirtualBox. Part 1
Checking Oracle VM VirtualBox. Part 1Checking Oracle VM VirtualBox. Part 1
Checking Oracle VM VirtualBox. Part 1Andrey Karpov
 
Exploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App developmentExploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App developmentJayaprakash R
 
Container orchestration from theory to practice
Container orchestration from theory to practiceContainer orchestration from theory to practice
Container orchestration from theory to practiceDocker, Inc.
 
Operating Systems - "Chapter 5 Process Synchronization"
Operating Systems - "Chapter 5 Process Synchronization"Operating Systems - "Chapter 5 Process Synchronization"
Operating Systems - "Chapter 5 Process Synchronization"Ra'Fat Al-Msie'deen
 
DDD Framework for Java: JdonFramework
DDD Framework for Java: JdonFrameworkDDD Framework for Java: JdonFramework
DDD Framework for Java: JdonFrameworkbanq jdon
 
Circuit breakers for Java: Failsafe, Javaslang-Circuitbreaker, Hystrix and Ve...
Circuit breakers for Java: Failsafe, Javaslang-Circuitbreaker, Hystrix and Ve...Circuit breakers for Java: Failsafe, Javaslang-Circuitbreaker, Hystrix and Ve...
Circuit breakers for Java: Failsafe, Javaslang-Circuitbreaker, Hystrix and Ve...Micha Kops
 
Inside AOStA
Inside AOStAInside AOStA
Inside AOStAESUG
 
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...corehard_by
 
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
 
A race of two compilers: GraalVM JIT versus HotSpot JIT C2. Which one offers ...
A race of two compilers: GraalVM JIT versus HotSpot JIT C2. Which one offers ...A race of two compilers: GraalVM JIT versus HotSpot JIT C2. Which one offers ...
A race of two compilers: GraalVM JIT versus HotSpot JIT C2. Which one offers ...J On The Beach
 
Checking the Cross-Platform Framework Cocos2d-x
Checking the Cross-Platform Framework Cocos2d-xChecking the Cross-Platform Framework Cocos2d-x
Checking the Cross-Platform Framework Cocos2d-xAndrey Karpov
 
Container Orchestration from Theory to Practice
Container Orchestration from Theory to PracticeContainer Orchestration from Theory to Practice
Container Orchestration from Theory to PracticeDocker, Inc.
 
Java Performance Tuning
Java Performance TuningJava Performance Tuning
Java Performance TuningMinh Hoang
 

Ähnlich wie Java- Concurrent programming - Synchronization (part 2) (20)

Stateful streaming data pipelines
Stateful streaming data pipelinesStateful streaming data pipelines
Stateful streaming data pipelines
 
Native Java with GraalVM
Native Java with GraalVMNative Java with GraalVM
Native Java with GraalVM
 
Coding style for good synthesis
Coding style for good synthesisCoding style for good synthesis
Coding style for good synthesis
 
Taming startup dynamics - Magnus Jungsbluth & Domagoj Cosic
Taming startup dynamics - Magnus Jungsbluth & Domagoj CosicTaming startup dynamics - Magnus Jungsbluth & Domagoj Cosic
Taming startup dynamics - Magnus Jungsbluth & Domagoj Cosic
 
Android Loaders : Reloaded
Android Loaders : ReloadedAndroid Loaders : Reloaded
Android Loaders : Reloaded
 
Checking Oracle VM VirtualBox. Part 1
Checking Oracle VM VirtualBox. Part 1Checking Oracle VM VirtualBox. Part 1
Checking Oracle VM VirtualBox. Part 1
 
Exploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App developmentExploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App development
 
Container orchestration from theory to practice
Container orchestration from theory to practiceContainer orchestration from theory to practice
Container orchestration from theory to practice
 
Chaincode Use Cases
Chaincode Use Cases Chaincode Use Cases
Chaincode Use Cases
 
Operating Systems - "Chapter 5 Process Synchronization"
Operating Systems - "Chapter 5 Process Synchronization"Operating Systems - "Chapter 5 Process Synchronization"
Operating Systems - "Chapter 5 Process Synchronization"
 
DDD Framework for Java: JdonFramework
DDD Framework for Java: JdonFrameworkDDD Framework for Java: JdonFramework
DDD Framework for Java: JdonFramework
 
Circuit breakers for Java: Failsafe, Javaslang-Circuitbreaker, Hystrix and Ve...
Circuit breakers for Java: Failsafe, Javaslang-Circuitbreaker, Hystrix and Ve...Circuit breakers for Java: Failsafe, Javaslang-Circuitbreaker, Hystrix and Ve...
Circuit breakers for Java: Failsafe, Javaslang-Circuitbreaker, Hystrix and Ve...
 
Inside AOStA
Inside AOStAInside AOStA
Inside AOStA
 
Project02 wit
Project02 witProject02 wit
Project02 wit
 
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
 
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
 
A race of two compilers: GraalVM JIT versus HotSpot JIT C2. Which one offers ...
A race of two compilers: GraalVM JIT versus HotSpot JIT C2. Which one offers ...A race of two compilers: GraalVM JIT versus HotSpot JIT C2. Which one offers ...
A race of two compilers: GraalVM JIT versus HotSpot JIT C2. Which one offers ...
 
Checking the Cross-Platform Framework Cocos2d-x
Checking the Cross-Platform Framework Cocos2d-xChecking the Cross-Platform Framework Cocos2d-x
Checking the Cross-Platform Framework Cocos2d-x
 
Container Orchestration from Theory to Practice
Container Orchestration from Theory to PracticeContainer Orchestration from Theory to Practice
Container Orchestration from Theory to Practice
 
Java Performance Tuning
Java Performance TuningJava Performance Tuning
Java Performance Tuning
 

Mehr von 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
 
Diagrammi di AttivitĂ 
Diagrammi di AttivitĂ Diagrammi di AttivitĂ 
Diagrammi di AttivitĂ Riccardo Cardin
 
Diagrammi Use Case
Diagrammi Use CaseDiagrammi Use Case
Diagrammi Use CaseRiccardo Cardin
 
Introduzione a UML
Introduzione a UMLIntroduzione a UML
Introduzione a UMLRiccardo 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
 

Mehr von 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
 

KĂźrzlich hochgeladen

call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfWilly Marroquin (WillyDevNET)
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park masabamasaba
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456KiaraTiradoMicha
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfkalichargn70th171
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...Nitya salvi
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto GonzĂĄlez Trastoy
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrainmasabamasaba
 

KĂźrzlich hochgeladen (20)

call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 

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 rcardin@math.unipd.it
  • 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