SlideShare a Scribd company logo
ilJUG	
  Java	
  8	
  Launch	
  Event	
  #2	
  
Stamped	
  Locks	
  	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  
!
Haim Yadid - Performize-IT
About	
  Me:	
  Haim	
  Yadid
•21 Years of SW development experience
•Performance Expert
•Consulting R&D Groups
•Training: Java Performance Optimization
•Organizing : ILJUG
IL	
  JUG
•Israeli Java User Group
•Reborn at 1/14
•Meetup : http://www.meetup.com/IL-JUG
•G+: https://plus.google.com/u/0/communities/110138558454900054301
•Twitter: @il_jug
Synchronization
Synchronized keyword was introduced to the java
language from the beginning
Acquire the lock on any java object
By default
locking object instance on instance methods
Locking the class on static methods
© Copyright Performize IT LTD.
synchronized void foo(){
do something();
}
private Object x = new Object();
void bar() {
synchronized (x) {
do something;
}
}
Volatile keyword
Insures access atomicity
Visibility and order
© Copyright Performize-IT LTD.CPU Profiling: Lock Contention
private volatile long counter;
public long getCounter() {
return counter;
}
public void increment(long amount){
++counter;
}
Contention
•Two threads are considered to be
contended when they try to access same
lock on the same time
•Locking mechanism behaves differently
under contention
• Contention degrades performance
dramatically
ReentrantLock
Introduced in Java5
Part of the java.util.concurrent package
Enhanced flexibility
In Java 5 had better performance (fixed by now)
© Copyright Performize IT LTD.
private final ReentrantLock lock = new ReentrantLock(); // ...
public void m() {
lock.lock(); // block until condition holds
try {
// ... method body
} finally {
lock.unlock()
}
}
ReadWriteLock
Introduced in Java5
Part of the java.util.concurrent package
Two locks work together inside the same lock
Any amount of readers can work concurrently
Write locks are taken exclusively
© Copyright Performize IT LTD.
public void increment(long amount) {
try {
rwlock.writeLock().lock();
counter+=amount;
} finally{
rwlock.writeLock().unlock();
}
}
public long getCounter() {
try {
rwlock.readLock().lock();
return counter;
} finally {
rwlock.readLock().unlock();
}
}
Introduce Fairness
Reentrant locks can work in fair and non fair mode.
Fair mode means that requests to the lock object
are accepted by the order they have been received.
Prevents starvation
Predictable latency
Much slower
© Copyright Performize IT LTD.
private final ReentrantLock lock = new ReentrantLock(true);
Deadlocks
A Deadlock is a severe problem in a Java program
It is a non recoverable situation requires JVM
restart
A cycle of locks held by different thread where each
one is waiting another thread to release a lock.
© Copyright Performize-IT LTD.CPU Profiling: Concurrency problems
Thread A
Lock X
Wait on Y
Thread B
Lock Y
Wait on X
tryLock
With synchronized keyword you are not able to
control how much to wait
Reetrantlock introduces
tryLock() – If lock already taken return false
tryLock(timeout,timeunit) – Waits for a certain amount of
time
Can be a solution to deadlocks
© Copyright Performize-IT LTD.CPU Profiling: Lock Contention
CAS
Other approaches use low level construct such as
compare and swap
Faster than synchronized
Limited in functionality
Can be used to develop complicated mechanism
© Copyright Performize-IT LTD.CPU Profiling: Lock Contention
private final AtomicLong atomic = new AtomicLong();
public void increment(long amount) {
atomic.addAndGet(amount);
}
public long getCounter() {
return atomic.get();
}
J8 - LongAdder
Added to J8 - should be faster on multi threaded
environment compared to AtomicLong
Also a version for DoubleAdder
© Copyright Performize-IT LTD.CPU Profiling: Lock Contention
LongAdder adder = new LongAdder();
public void increment(long amount) {
adder.add(amount);
}
public long getCounter() {
return adder.longValue();
}
J8 - LongAdder Benchmark
Taken from
http://minddotout.wordpress.com/2013/05/11/
java-8-concurrency-longadder/
© Copyright Performize-IT LTD.CPU Profiling: Lock Contention
Stamped	
  Locks	
  	
  
	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  	
  
Pessimistic
Can work the same as read write lock
Assumes contention
Get a stamp from
© Copyright Performize IT LTD.
long stamp = rwlock.writeLock();
try {
counter+= amount;
} finally {
rwlock.unlockWrite(stamp);
}
long stamp = rwlock.readLock();
try {
result = counter;
} finally {
rwlock.unlockRead(stamp);
}
return result;
Optimistic Approach
Optimistic Mechanism
Try perform read if disturbed retry
© Copyright Performize-IT LTD.CPU Profiling: Lock Contention
private StampedLock rwlock = new StampedLock();
!
long stamp = rwlock.tryOptimisticRead();
result = counter;
!
if (rwlock.validate(stamp)) {
return result;
}
Retry
If failed one can retry
© Copyright Performize-IT LTD.CPU Profiling: Lock Contention
for (i=0;i<maxRetries;i++) {
long stamp = rwlock.tryOptimisticRead();
result = counter;
if (rwlock.validate(stamp)) {
return result;
}
}
Micro Benchmark
Original version developed by Tal Weiss (Takipi)
https://github.com/takipi/counters-benchmark.git
Modified benchmark here
https://github.com/lifey/counters-benchmark.git
The two benchmarks are very different and yield different
results ( mine is better :) )
© Copyright Performize IT LTD.
Disclaimer
Beware of micro benchmarks.
Benchmarks can be flawed. Including this one
Under different conditions they may behave differently
They prove nothing for real life application
Benchmark your real life applications as well
Saying that benchmark contains:
Warmup
Average on 10 iterations after warmup
© Copyright Performize IT LTD.
ReaderWriter
A class which with configurable probability either
increases a counter
Reads its value
A single iteration performs it for 200M times
Number of threads is configurable
© Copyright Performize IT LTD.
ReaderWriter
© Copyright Performize IT LTD.
if ((innerCounter % modulo) != 0) { // read

long count = counter.getCounter();

!
if (count > Main.TARGET_NUMBER) {

Main.publish(System.currentTimeMillis());

break;

}
} else { // write 

counter.increment(modulo);

}

innerCounter++;
Different Implementations
Volatile - using volatile keyword
Atomic - AtomicLong
Adder - LongAdder
Synchronized
Stamped (0,1,3,5 optimistic attempts)
RW lock
Fair RW lock
© Copyright Performize IT LTD.
Results 1/2 writes - 1 thread
© Copyright Performize IT LTD.
0
1750
3500
5250
7000
Volatile
Atomic
Adder
Sync
RWLock
Stamped0
Stamped1
Stamped3
Stamped5
Results 1/2 writes
© Copyright Performize IT LTD.
ValueAxis
0
20000
40000
60000
80000
Volatile
Atomic
Adder
Sync
RWLock
Stamped0
Stamped1
Stamped3
Stamped5
1 2 3 4
Results (1/10 writes) - single thread
© Copyright Performize IT LTD.
0
2250
4500
6750
9000
Volatile
Atomic
Adder
Sync
RWLock
Stamped0
Stamped1
Stamped3
Stamped5
Results (1/10 writes)
© Copyright Performize IT LTD.
0
25000
50000
75000
100000
Volatile
Atomic
Adder
Sync
RWLock
Stamped0
Stamped1
Stamped3
Stamped5
Results 1/100 writes
© Copyright Performize IT LTD.
0
10000
20000
30000
40000
Volatile
Atomic
Adder
Sync
RWLock
Stamped0
Stamped1
Stamped3
Stamped5
Results 1/100 writes
© Copyright Performize IT LTD.
0
4000
8000
12000
16000
Volatile
Atomic
Adder
Sync
Stamped1
Stamped3
Stamped5
Insights
RWlocks really suck under high contention.
StampedLocks require at least one optimistic try.
When update probability goes down more than one
retry may be beneficial
RWLock.tryLock is similar to lock
Under low write rate StampedLock with retries can
get close to atomic/volatile
Fair locks are x100 slower than non fair locks under
extreme cases
© Copyright Performize IT LTD.
Additional Reading - LongAddr
http://minddotout.wordpress.com/2013/05/11/
java-8-concurrency-longadder/
http://blog.palominolabs.com/2014/02/10/java-8-
performance-improvements-longadder-vs-
atomiclong/
http://psy-lob-saw.blogspot.co.il/2013/05/using-jmh-
to-benchmark-multi-threaded.html?m=1
http://docs.oracle.com/javase/8/docs/api/java/util/
concurrent/atomic/LongAdder.html
© Copyright Performize IT LTD.
Additional Reading - StampedLock
http://docs.oracle.com/javase/8/docs/api/java/util/
concurrent/locks/StampedLock.html
http://www.takipiblog.com/2014/05/30/java-8-
stampedlocks-vs-readwritelocks-and-synchronized/
http://www.javaspecialists.eu/archive/Issue215.html
© Copyright Performize IT LTD.
Java 8 - Stamped Lock
Thanks + Q&A + Contact Me
© Copyright Performize-IT LTD.
http://il.linkedin.com/in/haimyadid
lifey@performize-it.com
www.performize-it.com
blog.performize-it.com
https://github.com/lifey
@lifeyx

More Related Content

PPTX
Concurrency in Java
PPT
Java concurrency
PPTX
Basics of Java Concurrency
PPT
Java Multithreading and Concurrency
PPTX
Effective java - concurrency
PPTX
Advanced Introduction to Java Multi-Threading - Full (chok)
ODP
Java Concurrency
PDF
Multithreading in Java
Concurrency in Java
Java concurrency
Basics of Java Concurrency
Java Multithreading and Concurrency
Effective java - concurrency
Advanced Introduction to Java Multi-Threading - Full (chok)
Java Concurrency
Multithreading in Java

What's hot (20)

PPTX
Java concurrency - Thread pools
PPT
Inter threadcommunication.38
PPTX
Multi threading
PDF
Introduction+To+Java+Concurrency
PDF
Java Concurrency Gotchas
ODP
Java Concurrency, Memory Model, and Trends
PPTX
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
PPTX
Thread syncronization
PPT
Java multi threading
PDF
Java Multithreading Using Executors Framework
PPT
Java Threads and Concurrency
PPTX
.NET Multithreading/Multitasking
PDF
Java Course 10: Threads and Concurrency
PPTX
Inter thread communication &amp; runnable interface
ODP
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
ODP
Multithreading 101
PPTX
Multi-Threading
PPT
Synchronization.37
PDF
Java Concurrency in Practice
PPT
Python multithreading session 9 - shanmugam
Java concurrency - Thread pools
Inter threadcommunication.38
Multi threading
Introduction+To+Java+Concurrency
Java Concurrency Gotchas
Java Concurrency, Memory Model, and Trends
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
Thread syncronization
Java multi threading
Java Multithreading Using Executors Framework
Java Threads and Concurrency
.NET Multithreading/Multitasking
Java Course 10: Threads and Concurrency
Inter thread communication &amp; runnable interface
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Multithreading 101
Multi-Threading
Synchronization.37
Java Concurrency in Practice
Python multithreading session 9 - shanmugam
Ad

Viewers also liked (14)

PDF
Demistifying OSGi - Colombo Java Meetup 2013
PDF
Why roommates matter
PDF
Kettlebell esercizio military press
PDF
Testimonial for the High Performance Organisation (HPO) Workshop for Generali...
PDF
ADAPTATION OF MANGROVES
PDF
paesi e nazionalità by elenab
PDF
TrinityP3 Webinar Series: Transforming Production for the 21st Century
PPTX
通信プロトコルから見る艦隊これくしょん on 第十回 カーネル/VM探検隊
PPTX
2016 GAP Report® Presentation
DOCX
Relatório Anual De Atividade Não Letiva
PDF
Building cities with women in mind
PPT
Problem set 2 4b3
PDF
A Guide to CIO Advisory Services
PDF
Barcamp2013
Demistifying OSGi - Colombo Java Meetup 2013
Why roommates matter
Kettlebell esercizio military press
Testimonial for the High Performance Organisation (HPO) Workshop for Generali...
ADAPTATION OF MANGROVES
paesi e nazionalità by elenab
TrinityP3 Webinar Series: Transforming Production for the 21st Century
通信プロトコルから見る艦隊これくしょん on 第十回 カーネル/VM探検隊
2016 GAP Report® Presentation
Relatório Anual De Atividade Não Letiva
Building cities with women in mind
Problem set 2 4b3
A Guide to CIO Advisory Services
Barcamp2013
Ad

Similar to Java 8 - Stamped Lock (20)

DOCX
Java 5 concurrency
PPTX
Concurrency
PDF
Java Concurrency by Example
PDF
Java Concurrency by Example
PPT
Hs java open_party
PDF
Study effective java item 78 synchronize access to mutable data
PDF
Concurrency gotchas
DOC
Concurrency Learning From Jdk Source
PDF
Concurrency on the JVM
PDF
Programming with Threads in Java
PPTX
Java concurrency
KEY
Java and the machine - Martijn Verburg and Kirk Pepperdine
PPTX
Thread & concurrancy
PDF
Synchronize access to shared mutable data
PDF
Java Concurrency Idioms
PDF
jvm/java - towards lock-free concurrency
ODP
Java concurrency
PPTX
Parallel & Concurrent ...
PPTX
Concurrency
PDF
Lock free programming- pro tips
Java 5 concurrency
Concurrency
Java Concurrency by Example
Java Concurrency by Example
Hs java open_party
Study effective java item 78 synchronize access to mutable data
Concurrency gotchas
Concurrency Learning From Jdk Source
Concurrency on the JVM
Programming with Threads in Java
Java concurrency
Java and the machine - Martijn Verburg and Kirk Pepperdine
Thread & concurrancy
Synchronize access to shared mutable data
Java Concurrency Idioms
jvm/java - towards lock-free concurrency
Java concurrency
Parallel & Concurrent ...
Concurrency
Lock free programming- pro tips

More from Haim Yadid (20)

PDF
On-Call AI Assistant: Streamlining Production Error Investigation with LLM
PDF
Loom me up Scotty! Project Loom - What's in it for Me?
PDF
“Show Me the Garbage!”, Garbage Collection a Friend or a Foe
PDF
Kotlin Backend Development 6 Yrs Recap. The Good, the Bad and the Ugly
PPTX
“Show Me the Garbage!”, Understanding Garbage Collection
PDF
Java Memory Structure
PDF
Basic JVM Troubleshooting With Jmx
PDF
The Freelancer Journey
PDF
Building microservices with Kotlin
PDF
Taking Kotlin to production, Seriously
PDF
Let's talk about Garbage Collection
PDF
JVM Garbage Collection logs, you do not want to ignore them! - Reversim Summi...
PDF
mjprof: Monadic approach for JVM profiling
PDF
Java 8 Launch - MetaSpaces
PDF
The Future of Futures - A Talk About Java 8 CompletableFutures
PDF
Concurrency and Multithreading Demistified - Reversim Summit 2014
PDF
A short Intro. to Java Mission Control
PDF
Java Enterprise Edition Concurrency Misconceptions
PDF
Tales About Scala Performance
PDF
Israeli JUG - IL JUG presentation
On-Call AI Assistant: Streamlining Production Error Investigation with LLM
Loom me up Scotty! Project Loom - What's in it for Me?
“Show Me the Garbage!”, Garbage Collection a Friend or a Foe
Kotlin Backend Development 6 Yrs Recap. The Good, the Bad and the Ugly
“Show Me the Garbage!”, Understanding Garbage Collection
Java Memory Structure
Basic JVM Troubleshooting With Jmx
The Freelancer Journey
Building microservices with Kotlin
Taking Kotlin to production, Seriously
Let's talk about Garbage Collection
JVM Garbage Collection logs, you do not want to ignore them! - Reversim Summi...
mjprof: Monadic approach for JVM profiling
Java 8 Launch - MetaSpaces
The Future of Futures - A Talk About Java 8 CompletableFutures
Concurrency and Multithreading Demistified - Reversim Summit 2014
A short Intro. to Java Mission Control
Java Enterprise Edition Concurrency Misconceptions
Tales About Scala Performance
Israeli JUG - IL JUG presentation

Recently uploaded (20)

PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Modernizing your data center with Dell and AMD
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
KodekX | Application Modernization Development
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Electronic commerce courselecture one. Pdf
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
cuic standard and advanced reporting.pdf
PPTX
MYSQL Presentation for SQL database connectivity
PDF
NewMind AI Monthly Chronicles - July 2025
Understanding_Digital_Forensics_Presentation.pptx
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Modernizing your data center with Dell and AMD
Building Integrated photovoltaic BIPV_UPV.pdf
Mobile App Security Testing_ A Comprehensive Guide.pdf
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Advanced methodologies resolving dimensionality complications for autism neur...
Encapsulation_ Review paper, used for researhc scholars
NewMind AI Weekly Chronicles - August'25 Week I
KodekX | Application Modernization Development
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
The Rise and Fall of 3GPP – Time for a Sabbatical?
Electronic commerce courselecture one. Pdf
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Review of recent advances in non-invasive hemoglobin estimation
Diabetes mellitus diagnosis method based random forest with bat algorithm
Network Security Unit 5.pdf for BCA BBA.
cuic standard and advanced reporting.pdf
MYSQL Presentation for SQL database connectivity
NewMind AI Monthly Chronicles - July 2025

Java 8 - Stamped Lock

  • 1. ilJUG  Java  8  Launch  Event  #2   Stamped  Locks                                     ! Haim Yadid - Performize-IT
  • 2. About  Me:  Haim  Yadid •21 Years of SW development experience •Performance Expert •Consulting R&D Groups •Training: Java Performance Optimization •Organizing : ILJUG
  • 3. IL  JUG •Israeli Java User Group •Reborn at 1/14 •Meetup : http://www.meetup.com/IL-JUG •G+: https://plus.google.com/u/0/communities/110138558454900054301 •Twitter: @il_jug
  • 4. Synchronization Synchronized keyword was introduced to the java language from the beginning Acquire the lock on any java object By default locking object instance on instance methods Locking the class on static methods © Copyright Performize IT LTD. synchronized void foo(){ do something(); } private Object x = new Object(); void bar() { synchronized (x) { do something; } }
  • 5. Volatile keyword Insures access atomicity Visibility and order © Copyright Performize-IT LTD.CPU Profiling: Lock Contention private volatile long counter; public long getCounter() { return counter; } public void increment(long amount){ ++counter; }
  • 6. Contention •Two threads are considered to be contended when they try to access same lock on the same time •Locking mechanism behaves differently under contention • Contention degrades performance dramatically
  • 7. ReentrantLock Introduced in Java5 Part of the java.util.concurrent package Enhanced flexibility In Java 5 had better performance (fixed by now) © Copyright Performize IT LTD. private final ReentrantLock lock = new ReentrantLock(); // ... public void m() { lock.lock(); // block until condition holds try { // ... method body } finally { lock.unlock() } }
  • 8. ReadWriteLock Introduced in Java5 Part of the java.util.concurrent package Two locks work together inside the same lock Any amount of readers can work concurrently Write locks are taken exclusively © Copyright Performize IT LTD. public void increment(long amount) { try { rwlock.writeLock().lock(); counter+=amount; } finally{ rwlock.writeLock().unlock(); } } public long getCounter() { try { rwlock.readLock().lock(); return counter; } finally { rwlock.readLock().unlock(); } }
  • 9. Introduce Fairness Reentrant locks can work in fair and non fair mode. Fair mode means that requests to the lock object are accepted by the order they have been received. Prevents starvation Predictable latency Much slower © Copyright Performize IT LTD. private final ReentrantLock lock = new ReentrantLock(true);
  • 10. Deadlocks A Deadlock is a severe problem in a Java program It is a non recoverable situation requires JVM restart A cycle of locks held by different thread where each one is waiting another thread to release a lock. © Copyright Performize-IT LTD.CPU Profiling: Concurrency problems Thread A Lock X Wait on Y Thread B Lock Y Wait on X
  • 11. tryLock With synchronized keyword you are not able to control how much to wait Reetrantlock introduces tryLock() – If lock already taken return false tryLock(timeout,timeunit) – Waits for a certain amount of time Can be a solution to deadlocks © Copyright Performize-IT LTD.CPU Profiling: Lock Contention
  • 12. CAS Other approaches use low level construct such as compare and swap Faster than synchronized Limited in functionality Can be used to develop complicated mechanism © Copyright Performize-IT LTD.CPU Profiling: Lock Contention private final AtomicLong atomic = new AtomicLong(); public void increment(long amount) { atomic.addAndGet(amount); } public long getCounter() { return atomic.get(); }
  • 13. J8 - LongAdder Added to J8 - should be faster on multi threaded environment compared to AtomicLong Also a version for DoubleAdder © Copyright Performize-IT LTD.CPU Profiling: Lock Contention LongAdder adder = new LongAdder(); public void increment(long amount) { adder.add(amount); } public long getCounter() { return adder.longValue(); }
  • 14. J8 - LongAdder Benchmark Taken from http://minddotout.wordpress.com/2013/05/11/ java-8-concurrency-longadder/ © Copyright Performize-IT LTD.CPU Profiling: Lock Contention
  • 15. Stamped  Locks                                
  • 16. Pessimistic Can work the same as read write lock Assumes contention Get a stamp from © Copyright Performize IT LTD. long stamp = rwlock.writeLock(); try { counter+= amount; } finally { rwlock.unlockWrite(stamp); } long stamp = rwlock.readLock(); try { result = counter; } finally { rwlock.unlockRead(stamp); } return result;
  • 17. Optimistic Approach Optimistic Mechanism Try perform read if disturbed retry © Copyright Performize-IT LTD.CPU Profiling: Lock Contention private StampedLock rwlock = new StampedLock(); ! long stamp = rwlock.tryOptimisticRead(); result = counter; ! if (rwlock.validate(stamp)) { return result; }
  • 18. Retry If failed one can retry © Copyright Performize-IT LTD.CPU Profiling: Lock Contention for (i=0;i<maxRetries;i++) { long stamp = rwlock.tryOptimisticRead(); result = counter; if (rwlock.validate(stamp)) { return result; } }
  • 19. Micro Benchmark Original version developed by Tal Weiss (Takipi) https://github.com/takipi/counters-benchmark.git Modified benchmark here https://github.com/lifey/counters-benchmark.git The two benchmarks are very different and yield different results ( mine is better :) ) © Copyright Performize IT LTD.
  • 20. Disclaimer Beware of micro benchmarks. Benchmarks can be flawed. Including this one Under different conditions they may behave differently They prove nothing for real life application Benchmark your real life applications as well Saying that benchmark contains: Warmup Average on 10 iterations after warmup © Copyright Performize IT LTD.
  • 21. ReaderWriter A class which with configurable probability either increases a counter Reads its value A single iteration performs it for 200M times Number of threads is configurable © Copyright Performize IT LTD.
  • 22. ReaderWriter © Copyright Performize IT LTD. if ((innerCounter % modulo) != 0) { // read
 long count = counter.getCounter();
 ! if (count > Main.TARGET_NUMBER) {
 Main.publish(System.currentTimeMillis());
 break;
 } } else { // write 
 counter.increment(modulo);
 }
 innerCounter++;
  • 23. Different Implementations Volatile - using volatile keyword Atomic - AtomicLong Adder - LongAdder Synchronized Stamped (0,1,3,5 optimistic attempts) RW lock Fair RW lock © Copyright Performize IT LTD.
  • 24. Results 1/2 writes - 1 thread © Copyright Performize IT LTD. 0 1750 3500 5250 7000 Volatile Atomic Adder Sync RWLock Stamped0 Stamped1 Stamped3 Stamped5
  • 25. Results 1/2 writes © Copyright Performize IT LTD. ValueAxis 0 20000 40000 60000 80000 Volatile Atomic Adder Sync RWLock Stamped0 Stamped1 Stamped3 Stamped5 1 2 3 4
  • 26. Results (1/10 writes) - single thread © Copyright Performize IT LTD. 0 2250 4500 6750 9000 Volatile Atomic Adder Sync RWLock Stamped0 Stamped1 Stamped3 Stamped5
  • 27. Results (1/10 writes) © Copyright Performize IT LTD. 0 25000 50000 75000 100000 Volatile Atomic Adder Sync RWLock Stamped0 Stamped1 Stamped3 Stamped5
  • 28. Results 1/100 writes © Copyright Performize IT LTD. 0 10000 20000 30000 40000 Volatile Atomic Adder Sync RWLock Stamped0 Stamped1 Stamped3 Stamped5
  • 29. Results 1/100 writes © Copyright Performize IT LTD. 0 4000 8000 12000 16000 Volatile Atomic Adder Sync Stamped1 Stamped3 Stamped5
  • 30. Insights RWlocks really suck under high contention. StampedLocks require at least one optimistic try. When update probability goes down more than one retry may be beneficial RWLock.tryLock is similar to lock Under low write rate StampedLock with retries can get close to atomic/volatile Fair locks are x100 slower than non fair locks under extreme cases © Copyright Performize IT LTD.
  • 31. Additional Reading - LongAddr http://minddotout.wordpress.com/2013/05/11/ java-8-concurrency-longadder/ http://blog.palominolabs.com/2014/02/10/java-8- performance-improvements-longadder-vs- atomiclong/ http://psy-lob-saw.blogspot.co.il/2013/05/using-jmh- to-benchmark-multi-threaded.html?m=1 http://docs.oracle.com/javase/8/docs/api/java/util/ concurrent/atomic/LongAdder.html © Copyright Performize IT LTD.
  • 32. Additional Reading - StampedLock http://docs.oracle.com/javase/8/docs/api/java/util/ concurrent/locks/StampedLock.html http://www.takipiblog.com/2014/05/30/java-8- stampedlocks-vs-readwritelocks-and-synchronized/ http://www.javaspecialists.eu/archive/Issue215.html © Copyright Performize IT LTD.
  • 34. Thanks + Q&A + Contact Me © Copyright Performize-IT LTD. http://il.linkedin.com/in/haimyadid lifey@performize-it.com www.performize-it.com blog.performize-it.com https://github.com/lifey @lifeyx