4 Java Concurrent Patterns Advanced m4 Slides
4 Java Concurrent Patterns Advanced m4 Slides
Variables
José Paumard
PHD, JAVA CHAMPION, JAVA ROCK STAR
@JosePaumard https://github.com/JosePaumard
Agenda CASing!
What does compare and swap mean?
And why is it useful?
What is in the JDK to implement CASing?
How and when to use it
CASing = “Compare And Swap”
The starting point is a set of assembly
instructions
Very low level functionalities given by the CPU
That are exposed at the API level so that we can
use them in our applications
What is CASing?
The problem in concurrent programming is the
concurrent access to shared memory
Concurrent Read
/ Write We used synchronization to handle that
But in certain cases, we have more tools
Synchronization has a cost…
T1 Memory T2
read
10L
Synchronized Memory
T1 Memory T2
read
12L
write
Synchronized Memory
T1 Memory T2
12L
read
Synchronized Memory
T1 Memory T2
15L
read
write
We need to write a correct code, so protection by
lock is essential
Concurrent Read But in fact, there is no real concurrency at
/ Write runtime…
This is where CASing can be used
Compare and Swap works with three parameters:
- a location in memory
CASing
- an existing value at that location
- a new value to replace this existing value
If the current value at that address is the expected
value, then it is replaced by the new value and
returns true
CASing
If not, it returns false
All in a single, atomic assembly instruction
// Create an atomic long
AtomicLong counter = new AtomicLong(10L);