SlideShare una empresa de Scribd logo
1 de 16
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?

Más contenido relacionado

La actualidad más candente

Csw2016 gawlik bypassing_differentdefenseschemes
Csw2016 gawlik bypassing_differentdefenseschemesCsw2016 gawlik bypassing_differentdefenseschemes
Csw2016 gawlik bypassing_differentdefenseschemes
CanSecWest
 

La actualidad más candente (20)

The Ring programming language version 1.3 book - Part 84 of 88
The Ring programming language version 1.3 book - Part 84 of 88The Ring programming language version 1.3 book - Part 84 of 88
The Ring programming language version 1.3 book - Part 84 of 88
 
Functional Reactive Programming with RxJS
Functional Reactive Programming with RxJSFunctional Reactive Programming with RxJS
Functional Reactive Programming with RxJS
 
To Swift 2...and Beyond!
To Swift 2...and Beyond!To Swift 2...and Beyond!
To Swift 2...and Beyond!
 
Cascadia.js: Don't Cross the Streams
Cascadia.js: Don't Cross the StreamsCascadia.js: Don't Cross the Streams
Cascadia.js: Don't Cross the Streams
 
Fast Wavelet Tree Construction in Practice
Fast Wavelet Tree Construction in PracticeFast Wavelet Tree Construction in Practice
Fast Wavelet Tree Construction in Practice
 
Cluj.py Meetup: Extending Python in C
Cluj.py Meetup: Extending Python in CCluj.py Meetup: Extending Python in C
Cluj.py Meetup: Extending Python in C
 
Powered by Python - PyCon Germany 2016
Powered by Python - PyCon Germany 2016Powered by Python - PyCon Germany 2016
Powered by Python - PyCon Germany 2016
 
Efficient Two-level Homomorphic Encryption in Prime-order Bilinear Groups and...
Efficient Two-level Homomorphic Encryption in Prime-order Bilinear Groups and...Efficient Two-level Homomorphic Encryption in Prime-order Bilinear Groups and...
Efficient Two-level Homomorphic Encryption in Prime-order Bilinear Groups and...
 
Compose Async with RxJS
Compose Async with RxJSCompose Async with RxJS
Compose Async with RxJS
 
Cluj Big Data Meetup - Big Data in Practice
Cluj Big Data Meetup - Big Data in PracticeCluj Big Data Meetup - Big Data in Practice
Cluj Big Data Meetup - Big Data in Practice
 
Grand centraldispatch
Grand centraldispatchGrand centraldispatch
Grand centraldispatch
 
Java 7 new features
Java 7 new featuresJava 7 new features
Java 7 new features
 
Practical Two-level Homomorphic Encryption in Prime-order Bilinear Groups
Practical Two-level Homomorphic Encryption in Prime-order Bilinear GroupsPractical Two-level Homomorphic Encryption in Prime-order Bilinear Groups
Practical Two-level Homomorphic Encryption in Prime-order Bilinear Groups
 
Modern c++ Memory Management
Modern c++ Memory ManagementModern c++ Memory Management
Modern c++ Memory Management
 
The Ring programming language version 1.5.4 book - Part 59 of 185
The Ring programming language version 1.5.4 book - Part 59 of 185The Ring programming language version 1.5.4 book - Part 59 of 185
The Ring programming language version 1.5.4 book - Part 59 of 185
 
Using Deep Learning (Computer Vision) to Search for Oil and Gas
Using Deep Learning (Computer Vision) to Search for Oil and GasUsing Deep Learning (Computer Vision) to Search for Oil and Gas
Using Deep Learning (Computer Vision) to Search for Oil and Gas
 
Zone.js 2017
Zone.js 2017Zone.js 2017
Zone.js 2017
 
Csw2016 gawlik bypassing_differentdefenseschemes
Csw2016 gawlik bypassing_differentdefenseschemesCsw2016 gawlik bypassing_differentdefenseschemes
Csw2016 gawlik bypassing_differentdefenseschemes
 
Dynamic C++ ACCU 2013
Dynamic C++ ACCU 2013Dynamic C++ ACCU 2013
Dynamic C++ ACCU 2013
 
Counter Wars (JEEConf 2016)
Counter Wars (JEEConf 2016)Counter Wars (JEEConf 2016)
Counter Wars (JEEConf 2016)
 

Similar a Nicety of java 8 multithreading for advanced, Max Voronoy

Codestrong 2012 breakout session hacking titanium
Codestrong 2012 breakout session   hacking titaniumCodestrong 2012 breakout session   hacking titanium
Codestrong 2012 breakout session hacking titanium
Axway Appcelerator
 
Threaded Programming
Threaded ProgrammingThreaded Programming
Threaded Programming
Sri Prasanna
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
Dmitry Buzdin
 
Concurrency on the JVM
Concurrency on the JVMConcurrency on the JVM
Concurrency on the JVM
Vaclav Pech
 
Spark with Elasticsearch - umd version 2014
Spark with Elasticsearch - umd version 2014Spark with Elasticsearch - umd version 2014
Spark with Elasticsearch - umd version 2014
Holden Karau
 
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
Carol McDonald
 

Similar a Nicety of java 8 multithreading for advanced, Max Voronoy (20)

Node.js - As a networking tool
Node.js - As a networking toolNode.js - As a networking tool
Node.js - As a networking tool
 
Clojure And Swing
Clojure And SwingClojure And Swing
Clojure And Swing
 
Codestrong 2012 breakout session hacking titanium
Codestrong 2012 breakout session   hacking titaniumCodestrong 2012 breakout session   hacking titanium
Codestrong 2012 breakout session hacking titanium
 
Threaded Programming
Threaded ProgrammingThreaded Programming
Threaded Programming
 
Java 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from OredevJava 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from Oredev
 
Java
JavaJava
Java
 
MiamiJS - The Future of JavaScript
MiamiJS - The Future of JavaScriptMiamiJS - The Future of JavaScript
MiamiJS - The Future of JavaScript
 
Being functional in PHP (PHPDay Italy 2016)
Being functional in PHP (PHPDay Italy 2016)Being functional in PHP (PHPDay Italy 2016)
Being functional in PHP (PHPDay Italy 2016)
 
node.js - Eventful JavaScript on the Server
node.js - Eventful JavaScript on the Servernode.js - Eventful JavaScript on the Server
node.js - Eventful JavaScript on the Server
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
Nodejs - A quick tour (v6)
Nodejs - A quick tour (v6)Nodejs - A quick tour (v6)
Nodejs - A quick tour (v6)
 
Concurrency on the JVM
Concurrency on the JVMConcurrency on the JVM
Concurrency on the JVM
 
All you need to know about the JavaScript event loop
All you need to know about the JavaScript event loopAll you need to know about the JavaScript event loop
All you need to know about the JavaScript event loop
 
Fast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible JavaFast as C: How to Write Really Terrible Java
Fast as C: How to Write Really Terrible Java
 
Event-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineEvent-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 Engine
 
Spark with Elasticsearch - umd version 2014
Spark with Elasticsearch - umd version 2014Spark with Elasticsearch - umd version 2014
Spark with Elasticsearch - umd version 2014
 
Non-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.jsNon-blocking I/O, Event loops and node.js
Non-blocking I/O, Event loops and node.js
 
H2O Design and Infrastructure with Matt Dowle
H2O Design and Infrastructure with Matt DowleH2O Design and Infrastructure with Matt Dowle
H2O Design and Infrastructure with Matt Dowle
 
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
 
Rust "Hot or Not" at Sioux
Rust "Hot or Not" at SiouxRust "Hot or Not" at Sioux
Rust "Hot or Not" at Sioux
 

Más de Sigma Software

Más de Sigma Software (20)

Fast is Best. Using .NET MinimalAPIs
Fast is Best. Using .NET MinimalAPIsFast is Best. Using .NET MinimalAPIs
Fast is Best. Using .NET MinimalAPIs
 
"Are you developing or declining? Don't become an IT-dinosaur"
"Are you developing or declining? Don't become an IT-dinosaur""Are you developing or declining? Don't become an IT-dinosaur"
"Are you developing or declining? Don't become an IT-dinosaur"
 
Michael Smolin, "Decrypting customer's cultural code"
Michael Smolin, "Decrypting customer's cultural code"Michael Smolin, "Decrypting customer's cultural code"
Michael Smolin, "Decrypting customer's cultural code"
 
Max Kunytsia, “Why is continuous product discovery better than continuous del...
Max Kunytsia, “Why is continuous product discovery better than continuous del...Max Kunytsia, “Why is continuous product discovery better than continuous del...
Max Kunytsia, “Why is continuous product discovery better than continuous del...
 
Marcelino Moreno, "Product Management Mindset"
Marcelino Moreno, "Product Management Mindset"Marcelino Moreno, "Product Management Mindset"
Marcelino Moreno, "Product Management Mindset"
 
Andrii Pastushok, "Product Discovery in Outsourcing - What, When, and How"
Andrii Pastushok, "Product Discovery in Outsourcing - What, When, and How"Andrii Pastushok, "Product Discovery in Outsourcing - What, When, and How"
Andrii Pastushok, "Product Discovery in Outsourcing - What, When, and How"
 
Elena Turkenych “BA vs PM: Who' the right person, for the right job, with the...
Elena Turkenych “BA vs PM: Who' the right person, for the right job, with the...Elena Turkenych “BA vs PM: Who' the right person, for the right job, with the...
Elena Turkenych “BA vs PM: Who' the right person, for the right job, with the...
 
Eleonora Budanova “BA+PM+DEV team: how to build the synergy”
Eleonora Budanova “BA+PM+DEV team: how to build the synergy”Eleonora Budanova “BA+PM+DEV team: how to build the synergy”
Eleonora Budanova “BA+PM+DEV team: how to build the synergy”
 
Stoyan Atanasov “How crucial is the BA role in an IT Project"
Stoyan Atanasov “How crucial is the BA role in an IT Project"Stoyan Atanasov “How crucial is the BA role in an IT Project"
Stoyan Atanasov “How crucial is the BA role in an IT Project"
 
Olexandra Kovalyova, "Equivalence Partitioning, Boundary Values ​​Analysis, C...
Olexandra Kovalyova, "Equivalence Partitioning, Boundary Values ​​Analysis, C...Olexandra Kovalyova, "Equivalence Partitioning, Boundary Values ​​Analysis, C...
Olexandra Kovalyova, "Equivalence Partitioning, Boundary Values ​​Analysis, C...
 
Yana Lysa — "Decision Tables, State-Transition testing, Pairwase Testing"
Yana Lysa — "Decision Tables, State-Transition testing, Pairwase Testing"Yana Lysa — "Decision Tables, State-Transition testing, Pairwase Testing"
Yana Lysa — "Decision Tables, State-Transition testing, Pairwase Testing"
 
VOLVO x HACK SPRINT
VOLVO x HACK SPRINTVOLVO x HACK SPRINT
VOLVO x HACK SPRINT
 
Business digitalization trends and challenges
Business digitalization trends and challengesBusiness digitalization trends and challenges
Business digitalization trends and challenges
 
Дмитро Терещенко, "How to secure your application with Secure SDLC"
Дмитро Терещенко, "How to secure your application with Secure SDLC"Дмитро Терещенко, "How to secure your application with Secure SDLC"
Дмитро Терещенко, "How to secure your application with Secure SDLC"
 
Яна Лиса, “Ефективні методи написання хороших мануальних тестових сценаріїв”
Яна Лиса, “Ефективні методи написання хороших мануальних тестових сценаріїв”Яна Лиса, “Ефективні методи написання хороших мануальних тестових сценаріїв”
Яна Лиса, “Ефективні методи написання хороших мануальних тестових сценаріїв”
 
Тетяна Осетрова, “Модель зрілості розподіленної проектної команди”
Тетяна Осетрова, “Модель зрілості розподіленної проектної команди”Тетяна Осетрова, “Модель зрілості розподіленної проектної команди”
Тетяна Осетрова, “Модель зрілості розподіленної проектної команди”
 
Training solutions and content creation
Training solutions and content creationTraining solutions and content creation
Training solutions and content creation
 
False news - false truth: tips & tricks how to avoid them
False news - false truth: tips & tricks how to avoid themFalse news - false truth: tips & tricks how to avoid them
False news - false truth: tips & tricks how to avoid them
 
Анна Бойко, "Хороший контракт vs очікування клієнтів. Що вбереже вас, якщо вд...
Анна Бойко, "Хороший контракт vs очікування клієнтів. Що вбереже вас, якщо вд...Анна Бойко, "Хороший контракт vs очікування клієнтів. Що вбереже вас, якщо вд...
Анна Бойко, "Хороший контракт vs очікування клієнтів. Що вбереже вас, якщо вд...
 
Дмитрий Лапшин, "The importance of TEX and Internal Quality. How explain and ...
Дмитрий Лапшин, "The importance of TEX and Internal Quality. How explain and ...Дмитрий Лапшин, "The importance of TEX and Internal Quality. How explain and ...
Дмитрий Лапшин, "The importance of TEX and Internal Quality. How explain and ...
 

Último

+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 

Último (20)

%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
ManageIQ - Sprint 236 Review - Slide Deck
ManageIQ - Sprint 236 Review - Slide DeckManageIQ - Sprint 236 Review - Slide Deck
ManageIQ - Sprint 236 Review - Slide Deck
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
 
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxBUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 

Nicety of java 8 multithreading for advanced, Max Voronoy

  • 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