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.
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

What's hot

Java concurrency - Thread pools
Java concurrency - Thread poolsJava concurrency - Thread pools
Java concurrency - Thread pools
maksym220889
 
Inter threadcommunication.38
Inter threadcommunication.38Inter threadcommunication.38
Inter threadcommunication.38myrajendra
 
Multi threading
Multi threadingMulti threading
Multi threading
Mavoori Soshmitha
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency Gotchas
Alex Miller
 
Java Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsJava Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and Trends
Carol McDonald
 
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
Sachintha Gunasena
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronization
priyabogra1
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
Raja Sekhar
 
Java Multithreading Using Executors Framework
Java Multithreading Using Executors FrameworkJava Multithreading Using Executors Framework
Java Multithreading Using Executors Framework
Arun Mehra
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and Concurrency
Sunil OS
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/Multitasking
Sasha Kravchuk
 
Java Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyJava Course 10: Threads and Concurrency
Java Course 10: Threads and Concurrency
Anton Keks
 
Inter thread communication &amp; runnable interface
Inter thread communication &amp; runnable interfaceInter thread communication &amp; runnable interface
Inter thread communication &amp; runnable interface
keval_thummar
 
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningJava 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningCarol McDonald
 
Multithreading 101
Multithreading 101Multithreading 101
Multithreading 101
Tim Penhey
 
Multi-Threading
Multi-ThreadingMulti-Threading
Multi-Threading
Robert MacLean
 
Synchronization.37
Synchronization.37Synchronization.37
Synchronization.37myrajendra
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in Practice
Alina Dolgikh
 
Python multithreading session 9 - shanmugam
Python multithreading session 9 - shanmugamPython multithreading session 9 - shanmugam
Python multithreading session 9 - shanmugamNavaneethan Naveen
 

What's hot (20)

Java concurrency - Thread pools
Java concurrency - Thread poolsJava concurrency - Thread pools
Java concurrency - Thread pools
 
Inter threadcommunication.38
Inter threadcommunication.38Inter threadcommunication.38
Inter threadcommunication.38
 
Multi threading
Multi threadingMulti threading
Multi threading
 
Introduction+To+Java+Concurrency
Introduction+To+Java+ConcurrencyIntroduction+To+Java+Concurrency
Introduction+To+Java+Concurrency
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency Gotchas
 
Java Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsJava Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and Trends
 
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
Concurrency Programming in Java - 07 - High-level Concurrency objects, Lock O...
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronization
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
 
Java Multithreading Using Executors Framework
Java Multithreading Using Executors FrameworkJava Multithreading Using Executors Framework
Java Multithreading Using Executors Framework
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and Concurrency
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/Multitasking
 
Java Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyJava Course 10: Threads and Concurrency
Java Course 10: Threads and Concurrency
 
Inter thread communication &amp; runnable interface
Inter thread communication &amp; runnable interfaceInter thread communication &amp; runnable interface
Inter thread communication &amp; runnable interface
 
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningJava 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
 
Multithreading 101
Multithreading 101Multithreading 101
Multithreading 101
 
Multi-Threading
Multi-ThreadingMulti-Threading
Multi-Threading
 
Synchronization.37
Synchronization.37Synchronization.37
Synchronization.37
 
Java Concurrency in Practice
Java Concurrency in PracticeJava Concurrency in Practice
Java Concurrency in Practice
 
Python multithreading session 9 - shanmugam
Python multithreading session 9 - shanmugamPython multithreading session 9 - shanmugam
Python multithreading session 9 - shanmugam
 

Viewers also liked

Demistifying OSGi - Colombo Java Meetup 2013
Demistifying OSGi - Colombo Java Meetup 2013Demistifying OSGi - Colombo Java Meetup 2013
Demistifying OSGi - Colombo Java Meetup 2013
Sameera Jayasoma
 
Why roommates matter
Why roommates matterWhy roommates matter
Why roommates matter
drmstucker
 
Kettlebell esercizio military press
Kettlebell esercizio military pressKettlebell esercizio military press
Kettlebell esercizio military press
Calzetti & Mariucci Editori
 
Testimonial for the High Performance Organisation (HPO) Workshop for Generali...
Testimonial for the High Performance Organisation (HPO) Workshop for Generali...Testimonial for the High Performance Organisation (HPO) Workshop for Generali...
Testimonial for the High Performance Organisation (HPO) Workshop for Generali...
Centre for Executive Education
 
ADAPTATION OF MANGROVES
ADAPTATION OF MANGROVESADAPTATION OF MANGROVES
ADAPTATION OF MANGROVES
Abhijit Mitra
 
Talentdotgo
TalentdotgoTalentdotgo
Talentdotgo
DotGoSolutions
 
paesi e nazionalità by elenab
paesi e nazionalità by elenabpaesi e nazionalità by elenab
paesi e nazionalità by elenab
elenab76
 
TrinityP3 Webinar Series: Transforming Production for the 21st Century
TrinityP3 Webinar Series: Transforming Production for the 21st CenturyTrinityP3 Webinar Series: Transforming Production for the 21st Century
TrinityP3 Webinar Series: Transforming Production for the 21st Century
TrinityP3 Marketing Management Consultants
 
通信プロトコルから見る艦隊これくしょん on 第十回 カーネル/VM探検隊
通信プロトコルから見る艦隊これくしょん on 第十回 カーネル/VM探検隊通信プロトコルから見る艦隊これくしょん on 第十回 カーネル/VM探検隊
通信プロトコルから見る艦隊これくしょん on 第十回 カーネル/VM探検隊Kazuhiro Fujieda
 
2016 GAP Report® Presentation
2016 GAP Report® Presentation2016 GAP Report® Presentation
2016 GAP Report® Presentation
Global Harvest Initiative
 
Relatório Anual De Atividade Não Letiva
Relatório Anual De Atividade Não LetivaRelatório Anual De Atividade Não Letiva
Relatório Anual De Atividade Não Letiva
Fátima Brás
 
Building cities with women in mind
Building cities with women in mindBuilding cities with women in mind
Building cities with women in mind
Shiftbalance
 
Problem set 2 4b3
Problem set 2 4b3Problem set 2 4b3
Problem set 2 4b3
4ChEAB08
 
A Guide to CIO Advisory Services
A Guide to CIO Advisory ServicesA Guide to CIO Advisory Services
A Guide to CIO Advisory Services
Wipfli LLP/Brittenford Systems Inc.
 

Viewers also liked (15)

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

Similar to Java 8 - Stamped Lock

Native Java with GraalVM
Native Java with GraalVMNative Java with GraalVM
Native Java with GraalVM
Sylvain Wallez
 
Towards a Scalable Non-Blocking Coding Style
Towards a Scalable Non-Blocking Coding StyleTowards a Scalable Non-Blocking Coding Style
Towards a Scalable Non-Blocking Coding Style
Azul Systems Inc.
 
Java 5 concurrency
Java 5 concurrencyJava 5 concurrency
Java 5 concurrencypriyank09
 
Tornado Web Server Internals
Tornado Web Server InternalsTornado Web Server Internals
Tornado Web Server InternalsPraveen Gollakota
 
Concurrency Learning From Jdk Source
Concurrency Learning From Jdk SourceConcurrency Learning From Jdk Source
Concurrency Learning From Jdk SourceKaniska Mandal
 
Batch Applications for the Java Platform
Batch Applications for the Java PlatformBatch Applications for the Java Platform
Batch Applications for the Java Platform
Sivakumar Thyagarajan
 
Java util concurrent
Java util concurrentJava util concurrent
Java util concurrent
Roger Xia
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM Mechanics
Azul Systems, Inc.
 
Hs java open_party
Hs java open_partyHs java open_party
Hs java open_party
Open Party
 
Virtualizing Java in Java (jug.ru)
Virtualizing Java in Java (jug.ru)Virtualizing Java in Java (jug.ru)
Virtualizing Java in Java (jug.ru)
aragozin
 
The State of the Veil Framework
The State of the Veil FrameworkThe State of the Veil Framework
The State of the Veil Framework
VeilFramework
 
Nodejs Intro Part One
Nodejs Intro Part OneNodejs Intro Part One
Nodejs Intro Part One
Budh Ram Gurung
 
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
WebStackAcademy
 
Python twisted
Python twistedPython twisted
Python twisted
Mahendra M
 
Java and Serverless - A Match Made In Heaven, Part 2
Java and Serverless - A Match Made In Heaven, Part 2Java and Serverless - A Match Made In Heaven, Part 2
Java and Serverless - A Match Made In Heaven, Part 2
Curity
 
Java Performance Tuning
Java Performance TuningJava Performance Tuning
Java Performance Tuning
Minh Hoang
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?
Doug Hawkins
 
Testing in android
Testing in androidTesting in android
Testing in android
jtrindade
 
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...Paul King
 

Similar to Java 8 - Stamped Lock (20)

Native Java with GraalVM
Native Java with GraalVMNative Java with GraalVM
Native Java with GraalVM
 
Towards a Scalable Non-Blocking Coding Style
Towards a Scalable Non-Blocking Coding StyleTowards a Scalable Non-Blocking Coding Style
Towards a Scalable Non-Blocking Coding Style
 
Java 5 concurrency
Java 5 concurrencyJava 5 concurrency
Java 5 concurrency
 
Tornado Web Server Internals
Tornado Web Server InternalsTornado Web Server Internals
Tornado Web Server Internals
 
Concurrency Learning From Jdk Source
Concurrency Learning From Jdk SourceConcurrency Learning From Jdk Source
Concurrency Learning From Jdk Source
 
Batch Applications for the Java Platform
Batch Applications for the Java PlatformBatch Applications for the Java Platform
Batch Applications for the Java Platform
 
Java adv
Java advJava adv
Java adv
 
Java util concurrent
Java util concurrentJava util concurrent
Java util concurrent
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM Mechanics
 
Hs java open_party
Hs java open_partyHs java open_party
Hs java open_party
 
Virtualizing Java in Java (jug.ru)
Virtualizing Java in Java (jug.ru)Virtualizing Java in Java (jug.ru)
Virtualizing Java in Java (jug.ru)
 
The State of the Veil Framework
The State of the Veil FrameworkThe State of the Veil Framework
The State of the Veil Framework
 
Nodejs Intro Part One
Nodejs Intro Part OneNodejs Intro Part One
Nodejs Intro Part One
 
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
 
Python twisted
Python twistedPython twisted
Python twisted
 
Java and Serverless - A Match Made In Heaven, Part 2
Java and Serverless - A Match Made In Heaven, Part 2Java and Serverless - A Match Made In Heaven, Part 2
Java and Serverless - A Match Made In Heaven, Part 2
 
Java Performance Tuning
Java Performance TuningJava Performance Tuning
Java Performance Tuning
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?
 
Testing in android
Testing in androidTesting in android
Testing in android
 
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
 

More from Haim Yadid

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

More from Haim Yadid (19)

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

Recently uploaded

Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 

Recently uploaded (20)

Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 

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.
  • 33.
  • 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