SlideShare a Scribd company logo
1
Nicety of java 8 multithreading for advanced
Maksym Voroniy
Software Architect of GlobalLogic
2
Common points01
3
History
Text
The Dream Time sharing
Stone Age Intel 80386
Multiple
data
multiple
handlers
Multiple
processo
rs
Multiple
data
single
handler
Hyper threading
IBM 360
CUDA
Multicore
Today
4
Point #1
Maurice Herlihy & Nir Shavit “The Art of Multiprocessor Programming”
5
Atomicity vs Consistence
static int a = 5;
a *= 3;
int b = 22;
b += a;
mov EAX, 5
mov ds:[a], EAX
mul 3
mov ds:[a], EAX
mov EBX, 22
add EBX, EAX;vs add EBX,ds:[a]
atomicity
consistence
6
Java 8 FAA vs CAS02
7
Nicety #1 - Java 8 Atomics
http://ashkrit.blogspot.com/2014/02/atomicinteger-java-7-vs-java-8.html
fetch-and-add vs compare-and-swap (CAS)
JDK 8 - AtomicInteger
public final int getAndIncrement() {
return unsafe.getAndAddInt(
this, valueOffset, 1);
}
JDK7 - AtomicInteger
public final int getAndIncrement() {
for (;;) {
int current = get();
int next = current + 1;
if (compareAndSet(current, next))
return current;
}
}
8
Why Atomic important?
Text
ConcurrentHashMap<>
Collections.synchronizedMap(new HashMap<>())
• ConcurrentLinkedDeque/Queue
• ConcurrentSkipListSet/Map
• ConcurrentHashMap
• wait-free, if every concurrent operation is guaranteed to be
finished in a finite number of steps
• lock-free, if some concurrent operations are guaranteed to
be finished in a finite number of steps.
DARE
develop concurrent hash-map
TODAY tomorrow
9
ConcurrentHashMap
StampedLock goes to stage
Text
Simple cache implementation (value by key):
(T key, Map<T, V> map) -> {
return map.get(i);
}
synchronizedMap(new HashMap<>())
(T key, Map<T, V> map) -> {
synchronized (map){
return map.get(i);
}
}
HashMap + ReadWriteLock
(T key, Map<T, V> map) -> {
Lock l = rwLock.readLock();
l.lock();
try {
return map.get(i);
} finally {
l.unlock();
}}
10
StampedLock goes to stage (II)
Text
HashMap + StampedLock
(T key, Map<T, V> map) -> {
long l = stampedLock.readLock();
try {
return map.get(i);
} finally {
stampedLock.unlockRead(l);
}}
HashMap + StampedLock+Optimistic
(T key, Map<T, V> map) -> {
long stamp = optimisticLock.tryOptimisticRead();
Integer r = map.get(i);
if (!optimisticLock.validate(stamp)) {
stamp = optimisticLock.readLock();
try {
return map.get(i);
} finally {
optimisticLock.unlockRead(stamp);
}
}
return r;
}
200`000 op for 10
Threads
Nanoseconds
ConcurrentHashMap 72645.057
Optimistic 359819.982
StampedLock 1303853.525
ReadWriteLock 1326939.766
Locked 1922399.053
11
Java 8 Parallelism03
12
.parallelStream()
Text
//from Oracle tutorial:
double average = roster
.parallelStream()
.filter(p -> p.getGender() == Person.Sex.MALE)
.mapToInt(Person::getAge)
.average()
.getAsDouble()
• Java runtime partitions the stream into
multiple substreams. Aggregate operations
iterate over and process these substreams in
parallel and then combine the results
static ExecutorService newWorkStealingPool()
static ExecutorService newFixedThreadPool(int nThreads)
static ScheduledExecutorService newScheduledThreadPool(int corePoolSize)
static ExecutorService newCachedThreadPool(ThreadFactory threadFactory)
• Work Stealing (An idle thread steals work from a thread having tasks queued up more than it
can process currently)
• Ability to recursively decompose the tasks and collect the results. (Apparently, this requirement
must have popped up along with the conception of the notion of parallel processing... but lacked
a solid implementation framework in Java till Java 7)
ForkJoinPool
13
The trap!
List<SomeClass> list = // A list of objects
list.parallelStream()
.map(this::veryLongProcessing)
.collect(toList());
partition
Stream-1
Stream-2
Stream-3
Core -1 Core -2
ForkJoinPool forkJoinPool = new ForkJoinPool(2);
forkJoinPool.submit(() ->
list.parallel()
.map(this::veryLongProcessing)
.collect(toList())
).get();
"Arranges to asynchronously execute this task in the pool the
current task is running in, if applicable, or using the
ForkJoinPool.commonPool() if not in
ForkJoinPool()"
14
The Future
Text
Time sharing
Stone Age Intel 80386
Hyper threading
IBM 360
CUDA
Multicore
HTMSTM
15
Future direction
• How Databases works (SQL& NoSQL)
• Quantum computing
• Advanced data structures (R-Tree, B-Tree, Trie, Skip-lists, Heaps…)
http://goo.gl/forms/9LauaeJBlO
N
16
Thank you!
Any Questions?

More Related Content

PPTX
RealmDB for Android
PDF
The Ring programming language version 1.3 book - Part 84 of 88
PPTX
Why learn Internals?
PDF
Memory management
PPT
JVM performance options. How it works
PPT
20100712-OTcl Command -- Getting Started
PDF
Engineering fast indexes (Deepdive)
PDF
Collections forceawakens
RealmDB for Android
The Ring programming language version 1.3 book - Part 84 of 88
Why learn Internals?
Memory management
JVM performance options. How it works
20100712-OTcl Command -- Getting Started
Engineering fast indexes (Deepdive)
Collections forceawakens

What's hot (20)

PDF
Handling 20 billion requests a month
PDF
Tweaking performance on high-load projects
PDF
sizeof(Object): how much memory objects take on JVMs and when this may matter
PDF
Wprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
PDF
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
PDF
ConFess Vienna 2015 - Metaprogramming with Groovy
PPT
NS2: Binding C++ and OTcl variables
PPT
NS2 Object Construction
PPTX
Functional Reactive Programming with RxJS
PDF
PyCon KR 2019 sprint - RustPython by example
PDF
The Ring programming language version 1.10 book - Part 22 of 212
PDF
Hw09 Hadoop + Clojure
PDF
Full Stack Clojure
PDF
ooc - OSDC 2010 - Amos Wenger
KEY
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
PDF
DConf 2016: Keynote by Walter Bright
PDF
Out ofmemoryerror what is the cost of java objects
PDF
Dynamic C++ ACCU 2013
PDF
Hadoop + Clojure
PPT
Java 7
Handling 20 billion requests a month
Tweaking performance on high-load projects
sizeof(Object): how much memory objects take on JVMs and when this may matter
Wprowadzenie do technologii Big Data / Intro to Big Data Ecosystem
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
ConFess Vienna 2015 - Metaprogramming with Groovy
NS2: Binding C++ and OTcl variables
NS2 Object Construction
Functional Reactive Programming with RxJS
PyCon KR 2019 sprint - RustPython by example
The Ring programming language version 1.10 book - Part 22 of 212
Hw09 Hadoop + Clojure
Full Stack Clojure
ooc - OSDC 2010 - Amos Wenger
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
DConf 2016: Keynote by Walter Bright
Out ofmemoryerror what is the cost of java objects
Dynamic C++ ACCU 2013
Hadoop + Clojure
Java 7
Ad

Viewers also liked (12)

PPTX
Java Performance Boost
PDF
How to Learn a Programming Language in 25 Minutes
PPTX
Java 8 Intro - Core Features
PDF
Take a Look at Akka-Java
PPTX
Object-Relational Mapping for Dummies
PPTX
Spring vs EJB
PPTX
Commercial Development from the Inside
PDF
Big Audience at Scale — Spark and Big Data
PPTX
Battle for Code Quality - A Story of One Java Project
PPTX
Advanced Introduction to Java Multi-Threading - Full (chok)
PPTX
Антон Зотов - "Від інженера до AVP. Мій досвід побудови кар’єри в ІТ" Kharkiv...
PDF
Ingesting Drone Data into Big Data Platforms
Java Performance Boost
How to Learn a Programming Language in 25 Minutes
Java 8 Intro - Core Features
Take a Look at Akka-Java
Object-Relational Mapping for Dummies
Spring vs EJB
Commercial Development from the Inside
Big Audience at Scale — Spark and Big Data
Battle for Code Quality - A Story of One Java Project
Advanced Introduction to Java Multi-Threading - Full (chok)
Антон Зотов - "Від інженера до AVP. Мій досвід побудови кар’єри в ІТ" Kharkiv...
Ingesting Drone Data into Big Data Platforms
Ad

Similar to Nicety of Java 8 Multithreading (20)

KEY
Node.js - As a networking tool
PPTX
Clojure And Swing
PPTX
Codestrong 2012 breakout session hacking titanium
PPT
Threaded Programming
PPTX
Java 7 Whats New(), Whats Next() from Oredev
PPTX
PPTX
MiamiJS - The Future of JavaScript
PDF
Being functional in PHP (PHPDay Italy 2016)
PDF
Counter Wars (JEEConf 2016)
PDF
node.js - Eventful JavaScript on the Server
PDF
Refactoring to Macros with Clojure
PDF
Nodejs - A quick tour (v6)
ODP
Concurrency on the JVM
PPTX
All you need to know about the JavaScript event loop
PDF
Fast as C: How to Write Really Terrible Java
PPTX
Event-driven IO server-side JavaScript environment based on V8 Engine
PDF
Spark with Elasticsearch - umd version 2014
PDF
Non-blocking I/O, Event loops and node.js
PDF
H2O Design and Infrastructure with Matt Dowle
ODP
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Node.js - As a networking tool
Clojure And Swing
Codestrong 2012 breakout session hacking titanium
Threaded Programming
Java 7 Whats New(), Whats Next() from Oredev
MiamiJS - The Future of JavaScript
Being functional in PHP (PHPDay Italy 2016)
Counter Wars (JEEConf 2016)
node.js - Eventful JavaScript on the Server
Refactoring to Macros with Clojure
Nodejs - A quick tour (v6)
Concurrency on the JVM
All you need to know about the JavaScript event loop
Fast as C: How to Write Really Terrible Java
Event-driven IO server-side JavaScript environment based on V8 Engine
Spark with Elasticsearch - umd version 2014
Non-blocking I/O, Event loops and node.js
H2O Design and Infrastructure with Matt Dowle
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning

More from GlobalLogic Ukraine (20)

PDF
GlobalLogic JavaScript Community Webinar #21 “Інтерв’ю без заспокійливих”
PPTX
Deadlocks in SQL - Turning Fear Into Understanding (by Sergii Stets)
PDF
GlobalLogic Java Community Webinar #18 “How to Improve Web Application Perfor...
PDF
GlobalLogic Embedded Community x ROS Ukraine Webinar "Surgical Robots"
PDF
GlobalLogic Java Community Webinar #17 “SpringJDBC vs JDBC. Is Spring a Hero?”
PDF
GlobalLogic JavaScript Community Webinar #18 “Long Story Short: OSI Model”
PPTX
Штучний інтелект як допомога в навчанні, а не замінник.pptx
PPTX
Задачі AI-розробника як застосовується штучний інтелект.pptx
PPTX
Що треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptx
PDF
GlobalLogic Java Community Webinar #16 “Zaloni’s Architecture for Data-Driven...
PDF
JavaScript Community Webinar #14 "Why Is Git Rebase?"
PDF
GlobalLogic .NET Community Webinar #3 "Exploring Serverless with Azure Functi...
PPTX
Страх і сила помилок - IT Inside від GlobalLogic Education
PDF
GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”
PDF
GlobalLogic QA Webinar “What does it take to become a Test Engineer”
PDF
“How to Secure Your Applications With a Keycloak?
PDF
GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
PPTX
GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...
PDF
GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”
PDF
Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"
GlobalLogic JavaScript Community Webinar #21 “Інтерв’ю без заспокійливих”
Deadlocks in SQL - Turning Fear Into Understanding (by Sergii Stets)
GlobalLogic Java Community Webinar #18 “How to Improve Web Application Perfor...
GlobalLogic Embedded Community x ROS Ukraine Webinar "Surgical Robots"
GlobalLogic Java Community Webinar #17 “SpringJDBC vs JDBC. Is Spring a Hero?”
GlobalLogic JavaScript Community Webinar #18 “Long Story Short: OSI Model”
Штучний інтелект як допомога в навчанні, а не замінник.pptx
Задачі AI-розробника як застосовується штучний інтелект.pptx
Що треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptx
GlobalLogic Java Community Webinar #16 “Zaloni’s Architecture for Data-Driven...
JavaScript Community Webinar #14 "Why Is Git Rebase?"
GlobalLogic .NET Community Webinar #3 "Exploring Serverless with Azure Functi...
Страх і сила помилок - IT Inside від GlobalLogic Education
GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”
GlobalLogic QA Webinar “What does it take to become a Test Engineer”
“How to Secure Your Applications With a Keycloak?
GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...
GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”
Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"

Recently uploaded (20)

PDF
Odoo Companies in India – Driving Business Transformation.pdf
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PDF
top salesforce developer skills in 2025.pdf
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PDF
Digital Strategies for Manufacturing Companies
PDF
wealthsignaloriginal-com-DS-text-... (1).pdf
PPTX
assetexplorer- product-overview - presentation
PPTX
Introduction to Artificial Intelligence
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PDF
System and Network Administraation Chapter 3
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PDF
medical staffing services at VALiNTRY
PDF
Nekopoi APK 2025 free lastest update
PPTX
L1 - Introduction to python Backend.pptx
PPTX
Computer Software and OS of computer science of grade 11.pptx
PDF
Design an Analysis of Algorithms I-SECS-1021-03
Odoo Companies in India – Driving Business Transformation.pdf
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
How to Choose the Right IT Partner for Your Business in Malaysia
VVF-Customer-Presentation2025-Ver1.9.pptx
top salesforce developer skills in 2025.pdf
Design an Analysis of Algorithms II-SECS-1021-03
Digital Strategies for Manufacturing Companies
wealthsignaloriginal-com-DS-text-... (1).pdf
assetexplorer- product-overview - presentation
Introduction to Artificial Intelligence
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
System and Network Administraation Chapter 3
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
How to Migrate SBCGlobal Email to Yahoo Easily
medical staffing services at VALiNTRY
Nekopoi APK 2025 free lastest update
L1 - Introduction to python Backend.pptx
Computer Software and OS of computer science of grade 11.pptx
Design an Analysis of Algorithms I-SECS-1021-03

Nicety of Java 8 Multithreading

  • 1. 1 Nicety of java 8 multithreading for advanced Maksym Voroniy Software Architect of GlobalLogic
  • 3. 3 History Text The Dream Time sharing Stone Age Intel 80386 Multiple data multiple handlers Multiple processo rs Multiple data single handler Hyper threading IBM 360 CUDA Multicore Today
  • 4. 4 Point #1 Maurice Herlihy & Nir Shavit “The Art of Multiprocessor Programming”
  • 5. 5 Atomicity vs Consistence static int a = 5; a *= 3; int b = 22; b += a; mov EAX, 5 mov ds:[a], EAX mul 3 mov ds:[a], EAX mov EBX, 22 add EBX, EAX;vs add EBX,ds:[a] atomicity consistence
  • 6. 6 Java 8 FAA vs CAS02
  • 7. 7 Nicety #1 - Java 8 Atomics http://ashkrit.blogspot.com/2014/02/atomicinteger-java-7-vs-java-8.html fetch-and-add vs compare-and-swap (CAS) JDK 8 - AtomicInteger public final int getAndIncrement() { return unsafe.getAndAddInt( this, valueOffset, 1); } JDK7 - AtomicInteger public final int getAndIncrement() { for (;;) { int current = get(); int next = current + 1; if (compareAndSet(current, next)) return current; } }
  • 8. 8 Why Atomic important? Text ConcurrentHashMap<> Collections.synchronizedMap(new HashMap<>()) • ConcurrentLinkedDeque/Queue • ConcurrentSkipListSet/Map • ConcurrentHashMap • wait-free, if every concurrent operation is guaranteed to be finished in a finite number of steps • lock-free, if some concurrent operations are guaranteed to be finished in a finite number of steps. DARE develop concurrent hash-map TODAY tomorrow
  • 9. 9 ConcurrentHashMap StampedLock goes to stage Text Simple cache implementation (value by key): (T key, Map<T, V> map) -> { return map.get(i); } synchronizedMap(new HashMap<>()) (T key, Map<T, V> map) -> { synchronized (map){ return map.get(i); } } HashMap + ReadWriteLock (T key, Map<T, V> map) -> { Lock l = rwLock.readLock(); l.lock(); try { return map.get(i); } finally { l.unlock(); }}
  • 10. 10 StampedLock goes to stage (II) Text HashMap + StampedLock (T key, Map<T, V> map) -> { long l = stampedLock.readLock(); try { return map.get(i); } finally { stampedLock.unlockRead(l); }} HashMap + StampedLock+Optimistic (T key, Map<T, V> map) -> { long stamp = optimisticLock.tryOptimisticRead(); Integer r = map.get(i); if (!optimisticLock.validate(stamp)) { stamp = optimisticLock.readLock(); try { return map.get(i); } finally { optimisticLock.unlockRead(stamp); } } return r; } 200`000 op for 10 Threads Nanoseconds ConcurrentHashMap 72645.057 Optimistic 359819.982 StampedLock 1303853.525 ReadWriteLock 1326939.766 Locked 1922399.053
  • 12. 12 .parallelStream() Text //from Oracle tutorial: double average = roster .parallelStream() .filter(p -> p.getGender() == Person.Sex.MALE) .mapToInt(Person::getAge) .average() .getAsDouble() • Java runtime partitions the stream into multiple substreams. Aggregate operations iterate over and process these substreams in parallel and then combine the results static ExecutorService newWorkStealingPool() static ExecutorService newFixedThreadPool(int nThreads) static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) • Work Stealing (An idle thread steals work from a thread having tasks queued up more than it can process currently) • Ability to recursively decompose the tasks and collect the results. (Apparently, this requirement must have popped up along with the conception of the notion of parallel processing... but lacked a solid implementation framework in Java till Java 7) ForkJoinPool
  • 13. 13 The trap! List<SomeClass> list = // A list of objects list.parallelStream() .map(this::veryLongProcessing) .collect(toList()); partition Stream-1 Stream-2 Stream-3 Core -1 Core -2 ForkJoinPool forkJoinPool = new ForkJoinPool(2); forkJoinPool.submit(() -> list.parallel() .map(this::veryLongProcessing) .collect(toList()) ).get(); "Arranges to asynchronously execute this task in the pool the current task is running in, if applicable, or using the ForkJoinPool.commonPool() if not in ForkJoinPool()"
  • 14. 14 The Future Text Time sharing Stone Age Intel 80386 Hyper threading IBM 360 CUDA Multicore HTMSTM
  • 15. 15 Future direction • How Databases works (SQL& NoSQL) • Quantum computing • Advanced data structures (R-Tree, B-Tree, Trie, Skip-lists, Heaps…) http://goo.gl/forms/9LauaeJBlO N