SlideShare ist ein Scribd-Unternehmen logo
1 von 45
Downloaden Sie, um offline zu lesen
Advanced
Java Concurrency
arno.haase@haase-consulting.com
Premature Optimization is
the root of all evil.
Donald Knuth
We should forget about small
efficiencies, say about 97% of
the time:
Yet we should not pass up our
opportunities in that critical 3%.
JDK: Atomic*, Streams, synchronized,
Locks, Fork/Join, ConcHashMap, ...
Libraries: JEE / Spring,
Akka, LMAX, Servlet 3, ...
Java Memory Model
Architecture
Algorithms
Concepts
Ideas
1. Java Memory Model
2. Concepts and Paradigms
3. Performance
Threads (naive)
● Threads take turns doing work.
● Each Thread does what the source code says.
● When a thread is interrupted, other threads see
the intermediate state.
● Synchronization serves only to make several
changes atomic.
Threads (a little less naive)
● There are several CPUs / cores executing
threads really at the same time.
● Each thread does what the source code says.
● Data access goes to RAM.
● When different threads access the same data,
they do that one after the other.
Threads: the truth
● Within a single thread, the JVM makes it look
as if the thread does what the source code
says.
● There is a defined ordering between things
happening in different threads if
synchronization prescribes that („happens-
before“).
● And that is all!
Does your computer do
what you programmed?
yes no
Compiler: Instruction Reordering,
expression caching, …
Hotspot: Register Allocation, Instruction
Reordering, Escape Analysis, …
Prozessor: Branch Prediction, Speculative
Evaluation, Prefetch, …
Caches: Store Buffers, Private Shared
Caches, …
Transformations
Visible effects are the same at all levels.
Example: Loop termination
boolean shutdown = false;
…
void doIt() {
while (!shutdown) {
…
}
}
boolean shutdown = false;
…
void doIt() {
boolean b = shutdown;
while (!b) {
…
}
}
Correct Synchronization
● No Race Conditions:
● If several threads access the same variable,
● and at least one of them writes,
● then access must be ordered by „happens-before“.
● If that is true for a program, then it will run as if
● all memory access was sequential
● and really went to RAM
● in the order defined by „happens-before“.
Example: volatile
● If
● Thread T1 writes a volatile Variable v, and
● Thread T2 then reads v,
● then
● all changes T1 made up to writing v are 'before' all
code in T2 after the read from v.
Memory Barriers
● Tools used to implement JMM
● Assembler instructions
● „synchronizing“ CPUs and Caches
● Constrain Reordering
● Potentially expensive
● Direct Cost: Cache Dirtying
● Limit Optimizations
● Especially between processors
● Where does Java use them?
● synchronized, Locks
● volatile
● after constructors (for final fields), …
Concurrency
is
complex!
A simple Logger
public class Logger {
public void log (String msg, Object... params) {
String s = doFormat (msg, params);
doLog (s);
}
private String doFormat (String msg, Object... params) {…}
private void doLog (String msg) {…}
}
thread safe?
public class Logger {
public synchronized void log (String msg, Object... params) {
String s = doFormat (msg, params);
doLog (s);
}
private String doFormat (String msg, Object... params) {…}
private void doLog (String msg) {…}
}
Hidden Deadlocks
public class X {
public synchronized void doIt () {
log.log ("doing it");
…
}
public synchronized String toString () { … }
…
}
x.doIt(); log.log ("%s", x);
lock (x)
log.log("...") → lock (log)
lock (log)
x.toString() → lock (x)
Asynchronous Logging
final ExecutorService exec =
Executors.newSingleThreadExecutor();
public void log (String msg, Object... args) {
exec.execute (() -> {
String formatted = doFormat (msg, args);
doLog (formatted);
});
}
Parallel Execution?
● Formatting can be expensive
● toString(): Callbacks to application code!
● Thread Pool for Logging?
● Message ordering is lost!
● … and doLog() ist not thread safe
Future<String>
final ExecutorService exec =
Executors.newSingleThreadExecutor();
public void log (String msg, Object... args) {
final Future<String> formatted =
CompletableFuture.supplyAsync(() -> doFormat(msg, args));
exec.execute (() -> {
try {
doLog (formatted.get());
}
catch (Exception exc) {
exc.printStackTrace();
}
});
}
Concurrency:
Shared Mutable State
● Locks: Blocking
● Read/Write and other optimizations
● Single Worker-Thread with a Message-Queue:
Non-Blocking
● Actors as a variant
● „Lock Free“ has share mutable state
● Every approach has its specific cost!
Worker Threads
● Queues
● Bounded / Unbounded
● Blocking / Non-Blocking
● Single / Multi Producers / Consumers
● Optimized for reading or writing (or a mix)
● Special features: Priority, remove(), Batch, …
● Future for results
● .thenAccept(...) / .thenAcceptAsync(...)
Which Thread Pool to use?
● Code with side effects
● (usually) ordering is important → Executors.newSingleThreadPool()
● non-blocking without Seiteneffekte
● ForkJoinPool.commonPool()
● blocking
● Specific ExecutorService per context
● Tuning, Monitoring, …
● Divide and conquer big proglems
● Measure to verify assumptions!
● Never ad hoc!
Amdahl's Law
Sharing is the root
of all contention
● more precisely: sharing mutable Ressources
● Locks, I/O, …
● Hidden Sharing
● ReadLock: Counter
● UUID.randomUUID()
● volatile: Shared main memory
● Cache Lines (Locality, Poisoning)
● Disk, DVDs, Network
● …
● Solutions: Isolation or Immutability
Lock-free Programming
● Shared Mutable State
● Lock Free
● Callers need never wait
● Processing may be delayed however
● e.g. asynchronous decoupling
● Responsive, saves ressources
● Wait Free
● Processing without a delay
● Special algorithms and data structures
● Highly complex; Ongoing research, work in progress
● ConcurrentHashMap, ConcurrentLinkedQueue
CAS loop
final AtomicInteger n = new AtomicInteger (0);
int max (int i) {
int prev, next;
do {
prev = n.get();
next = Math.max (prev, i);
} while (! n.compareAndSet (prev, next));
return next;
}
Functional Programming
● No Seiteneffekte
● All Objects are immutable, changes create new objects
● not just using Lambdas: JDK collections, Guice, …
● Scala, Clojure; a-foundation
● different style of programming
● efficient copying: partial reuse of objects
● functional algorithms
● State is stable automatically, even concurrently
Performance-Tuning
for Concurrency
public class StockExchange {
private final Map<Currency, Double> rates = new HashMap<>();
private final Map<String, Double> pricesInEuro = new HashMap<>();
public void updateRate (Currency currency, double fromEuro) {
rates.put (currency, fromEuro);
}
public void updatePrice (String wkz, double euros) {
pricesInEuro.put (wkz, euros);
}
public double currentPrice (String wkz, Currency currency) {
return pricesInEuro.get (wkz) * rates.get (currency);
}
}
Wait-Free:
ConcurrentHashMap
public class StockExchange {
private final Map<Currency, Double> rates =
new ConcurrentHashMap<>();
private final Map<String, Double> pricesInEuro =
new ConcurrentHashMap<>();
…
}
Fine-grained Locks:
Collections.synchronizedMap
public class StockExchange {
private final Map<Currency, Double> rates =
Collections.synchronizedMap (new HashMap<>());
private final Map<String, Double> pricesInEuro =
Collections.synchronizedMap (new HashMap<>());
…
}
Coarse Locks
public class StockExchange {
…
public synchronized void updateRate (…) {
…
}
public synchronized void updatePrice (…) {
…
}
public synchronized double currentPrice (…) {
…
}
}
Functional: Immutable Maps
public class StockExchange {
private final AtomicReference<AMap<Currency, Double>> rates =
new AtomicReference<> (AHashMap.empty ());
…
public void updateRate (Currency currency, double fromEuro) {
AMap<Currency, Double> prev, next;
do {
prev = rates.get ();
next = prev.updated (currency, fromEuro);
}
while (! rates.compareAndSet (prev, next));
}
…
}
Variant:
reduced update guarantees
public class StockExchange {
private volatile AMap<Currency, Double> rates =
AHashMap.empty ();
…
public void updateRate (Currency currency, double fromEuro) {
rates = rates.updated (currency, fromEuro);
}
…
}
Queue with a Worker-Thread
public class StockExchange {
private final Map<Currency, Double> rates = new HashMap<>();
…
private final BlockingQueue<Runnable> queue = …;
public StockExchange() {
new Thread(() -> {
while (true) queue.take().run();
}).start();
}
public void updateRate (Currency currency, double fromEuro) {
queue.put (() -> rates.put (currency, fromEuro));
}
…
}
Tests for comparison
for (int i=0; i<1_000_000; i++) {
stockExchange.updatePrice ("abc", 1.23);
}
volatile int v=0;
…
for (int i=0; i<1_000_000; i++) {
v=v;
stockExchange.updatePrice ("abc", 1.23);
}
volatile int v=0;
final LinkedList<String> l = new LinkedList<>();
…
for (int i=0; i<1_000_000; i++) {
l.add ("abc");
v=v;
stockExchange.updatePrice (l.remove(), 1.23);
}
Mixed Load
Mixed Load
Mostly Updates
And the Winner is...
● ConcurrentHashMap
● No consistency requirements, mostly reads, algorithmic access
● Queue with Worker Thread
● Transactionaler access, centralized Event-Queue
●
Data locality in multi-processor systems
● Immutable Map
●
Stable data during read operations
● long running reads
● „lossy“ → fast udate
● Locks
● never particularly fast → prescribed threading and data model
● Granularity: Lock per operation
Testing (1): Correctness
● „it wors“ is not enough
● JMM vs. JVM, Hardware, …
● Reviews
● controlled interruptions
● Shotgun
Testen (2): Performance
● Reserve time for testing!
● realistic Hardware
● big Hardware
● Multi-Core vs. Multi-Prozessor → HW optimizations for cache exchange
● Scaling effects
● realistic load scenarios (→ Know your load!!! Document assumptions!!!)
● Virtualized hardware
● Ask specific questions – there are many variables
● Pool sizes, cut-off for serial processing
● Hardware sizes: RAM, #Cores, …
● Series of measurements to evaluate alternatives
Practice: Local Parallelization
● e.g. searching in a large collection
● Fork/Join examples
●
Streams-API
● Verify improvements
● APIs are simple and invite „ad hoc“ use
● apparent improvements – at least without background load
●
overall CPU load is increased – use only if CPUs would
otherwise be idling!
● Measure, measure, measure: real hardware, real load
scenarios
Wrap-Up
● Concurrency is difficult
● Really understand your problems
● Measure, measure, measure!
● OS and hardware influence behavior
● Correctness before performance
● Korrektheit vor Performance
● Möglichst grobe Concurrency
● Share Nothing
The End
● Links:
● http://channel9.msdn.com/Shows/Going+Deep/Cpp
-and-Beyond-2012-Herb-Sutter-atomic-Weapons-1-
of-2
● http://github.com/arnohaase/a-foundation

Weitere ähnliche Inhalte

Was ist angesagt?

Java concurrency
Java concurrencyJava concurrency
Java concurrencyducquoc_vn
 
Java New Evolution
Java New EvolutionJava New Evolution
Java New EvolutionAllan Huang
 
Java Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyJava Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyAnton Keks
 
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
 
[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronization[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronizationxuehan zhu
 
Java multi threading
Java multi threadingJava multi threading
Java multi threadingRaja Sekhar
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with javaHoang Nguyen
 
Java concurrency in practice
Java concurrency in practiceJava concurrency in practice
Java concurrency in practiceMikalai Alimenkou
 
Java concurrency - Thread pools
Java concurrency - Thread poolsJava concurrency - Thread pools
Java concurrency - Thread poolsmaksym220889
 
Working With Concurrency In Java 8
Working With Concurrency In Java 8Working With Concurrency In Java 8
Working With Concurrency In Java 8Heartin Jacob
 
Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)choksheak
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and ConcurrencyRajesh Ananda Kumar
 
Java Multithreading Using Executors Framework
Java Multithreading Using Executors FrameworkJava Multithreading Using Executors Framework
Java Multithreading Using Executors FrameworkArun Mehra
 
iOS Multithreading
iOS MultithreadingiOS Multithreading
iOS MultithreadingRicha Jain
 
Inter threadcommunication.38
Inter threadcommunication.38Inter threadcommunication.38
Inter threadcommunication.38myrajendra
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronizationpriyabogra1
 
Programming with Threads in Java
Programming with Threads in JavaProgramming with Threads in Java
Programming with Threads in Javakoji lin
 

Was ist angesagt? (20)

Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Java New Evolution
Java New EvolutionJava New Evolution
Java New Evolution
 
Java Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyJava Course 10: Threads and Concurrency
Java Course 10: Threads and Concurrency
 
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...
 
[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronization[Java concurrency]02.basic thread synchronization
[Java concurrency]02.basic thread synchronization
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Java concurrency in practice
Java concurrency in practiceJava concurrency in practice
Java concurrency in practice
 
Java concurrency - Thread pools
Java concurrency - Thread poolsJava concurrency - Thread pools
Java concurrency - Thread pools
 
Working With Concurrency In Java 8
Working With Concurrency In Java 8Working With Concurrency In Java 8
Working With Concurrency In Java 8
 
Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
 
Java Multithreading Using Executors Framework
Java Multithreading Using Executors FrameworkJava Multithreading Using Executors Framework
Java Multithreading Using Executors Framework
 
iOS Multithreading
iOS MultithreadingiOS Multithreading
iOS Multithreading
 
Threading in java - a pragmatic primer
Threading in java - a pragmatic primerThreading in java - a pragmatic primer
Threading in java - a pragmatic primer
 
Tech talk
Tech talkTech talk
Tech talk
 
Inter threadcommunication.38
Inter threadcommunication.38Inter threadcommunication.38
Inter threadcommunication.38
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronization
 
Java memory model
Java memory modelJava memory model
Java memory model
 
Programming with Threads in Java
Programming with Threads in JavaProgramming with Threads in Java
Programming with Threads in Java
 

Andere mochten auch

Scala for the doubters. Максим Клыга
Scala for the doubters. Максим КлыгаScala for the doubters. Максим Клыга
Scala for the doubters. Максим КлыгаAlina Dolgikh
 
Appium + selenide comaqa.by. Антон Семенченко
Appium + selenide comaqa.by. Антон СеменченкоAppium + selenide comaqa.by. Антон Семенченко
Appium + selenide comaqa.by. Антон СеменченкоAlina Dolgikh
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Javaparag
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaRaghu nath
 
Java Concurrency Idioms
Java Concurrency IdiomsJava Concurrency Idioms
Java Concurrency IdiomsAlex Miller
 
Reactive streams. Slava Schmidt
Reactive streams. Slava SchmidtReactive streams. Slava Schmidt
Reactive streams. Slava SchmidtAlina Dolgikh
 
Programmazione concorrente in Java (vecchio modello)
Programmazione concorrente in Java (vecchio modello)Programmazione concorrente in Java (vecchio modello)
Programmazione concorrente in Java (vecchio modello)Davide Carboni
 
Modern Java Concurrency
Modern Java ConcurrencyModern Java Concurrency
Modern Java ConcurrencyBen Evans
 
Cracking android app. Мокиенко Сергей
Cracking android app. Мокиенко СергейCracking android app. Мокиенко Сергей
Cracking android app. Мокиенко СергейAlina Dolgikh
 
Dzone core java concurrency -_
Dzone core java concurrency -_Dzone core java concurrency -_
Dzone core java concurrency -_Surendra Sirvi
 
Architecting well-structured Java applications
Architecting well-structured Java applicationsArchitecting well-structured Java applications
Architecting well-structured Java applicationsEduards Sizovs
 
No sql unsuccessful_story. Владимир Зеленкевич
No sql unsuccessful_story. Владимир ЗеленкевичNo sql unsuccessful_story. Владимир Зеленкевич
No sql unsuccessful_story. Владимир ЗеленкевичAlina Dolgikh
 
Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Martin Toshev
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency GotchasAlex Miller
 
Lecture on Java Concurrency Day 4 on Feb 18, 2009.
Lecture on Java Concurrency Day 4 on Feb 18, 2009.Lecture on Java Concurrency Day 4 on Feb 18, 2009.
Lecture on Java Concurrency Day 4 on Feb 18, 2009.Kyung Koo Yoon
 
GPars: Groovy Parallelism for Java
GPars: Groovy Parallelism for JavaGPars: Groovy Parallelism for Java
GPars: Groovy Parallelism for JavaRussel Winder
 

Andere mochten auch (18)

Scala for the doubters. Максим Клыга
Scala for the doubters. Максим КлыгаScala for the doubters. Максим Клыга
Scala for the doubters. Максим Клыга
 
Appium + selenide comaqa.by. Антон Семенченко
Appium + selenide comaqa.by. Антон СеменченкоAppium + selenide comaqa.by. Антон Семенченко
Appium + selenide comaqa.by. Антон Семенченко
 
Multithreading In Java
Multithreading In JavaMultithreading In Java
Multithreading In Java
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Java Concurrency Idioms
Java Concurrency IdiomsJava Concurrency Idioms
Java Concurrency Idioms
 
Reactive streams. Slava Schmidt
Reactive streams. Slava SchmidtReactive streams. Slava Schmidt
Reactive streams. Slava Schmidt
 
Programmazione concorrente in Java (vecchio modello)
Programmazione concorrente in Java (vecchio modello)Programmazione concorrente in Java (vecchio modello)
Programmazione concorrente in Java (vecchio modello)
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Modern Java Concurrency
Modern Java ConcurrencyModern Java Concurrency
Modern Java Concurrency
 
Cracking android app. Мокиенко Сергей
Cracking android app. Мокиенко СергейCracking android app. Мокиенко Сергей
Cracking android app. Мокиенко Сергей
 
Concurrency
ConcurrencyConcurrency
Concurrency
 
Dzone core java concurrency -_
Dzone core java concurrency -_Dzone core java concurrency -_
Dzone core java concurrency -_
 
Architecting well-structured Java applications
Architecting well-structured Java applicationsArchitecting well-structured Java applications
Architecting well-structured Java applications
 
No sql unsuccessful_story. Владимир Зеленкевич
No sql unsuccessful_story. Владимир ЗеленкевичNo sql unsuccessful_story. Владимир Зеленкевич
No sql unsuccessful_story. Владимир Зеленкевич
 
Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Concurrency Utilities in Java 8
Concurrency Utilities in Java 8
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency Gotchas
 
Lecture on Java Concurrency Day 4 on Feb 18, 2009.
Lecture on Java Concurrency Day 4 on Feb 18, 2009.Lecture on Java Concurrency Day 4 on Feb 18, 2009.
Lecture on Java Concurrency Day 4 on Feb 18, 2009.
 
GPars: Groovy Parallelism for Java
GPars: Groovy Parallelism for JavaGPars: Groovy Parallelism for Java
GPars: Groovy Parallelism for Java
 

Ähnlich wie Java Concurrency in Practice

Dragoncraft Architectural Overview
Dragoncraft Architectural OverviewDragoncraft Architectural Overview
Dragoncraft Architectural Overviewjessesanford
 
Clojure concurrency
Clojure concurrencyClojure concurrency
Clojure concurrencyAlex Navis
 
Robust C++ Task Systems Through Compile-time Checks
Robust C++ Task Systems Through Compile-time ChecksRobust C++ Task Systems Through Compile-time Checks
Robust C++ Task Systems Through Compile-time ChecksStoyan Nikolov
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/MultitaskingSasha Kravchuk
 
Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in JavaRuben Inoto Soto
 
Server side JavaScript: going all the way
Server side JavaScript: going all the wayServer side JavaScript: going all the way
Server side JavaScript: going all the wayOleg Podsechin
 
Os Reindersfinal
Os ReindersfinalOs Reindersfinal
Os Reindersfinaloscon2007
 
Os Reindersfinal
Os ReindersfinalOs Reindersfinal
Os Reindersfinaloscon2007
 
Clojure concurrency overview
Clojure concurrency overviewClojure concurrency overview
Clojure concurrency overviewSergey Stupin
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot NetNeeraj Kaushik
 
Node.js Course 1 of 2 - Introduction and first steps
Node.js Course 1 of 2 - Introduction and first stepsNode.js Course 1 of 2 - Introduction and first steps
Node.js Course 1 of 2 - Introduction and first stepsManuel Eusebio de Paz Carmona
 
Concurrency Constructs Overview
Concurrency Constructs OverviewConcurrency Constructs Overview
Concurrency Constructs Overviewstasimus
 
Deuce STM - CMP'09
Deuce STM - CMP'09Deuce STM - CMP'09
Deuce STM - CMP'09Guy Korland
 
Medical Image Processing Strategies for multi-core CPUs
Medical Image Processing Strategies for multi-core CPUsMedical Image Processing Strategies for multi-core CPUs
Medical Image Processing Strategies for multi-core CPUsDaniel Blezek
 

Ähnlich wie Java Concurrency in Practice (20)

Dragoncraft Architectural Overview
Dragoncraft Architectural OverviewDragoncraft Architectural Overview
Dragoncraft Architectural Overview
 
Clojure concurrency
Clojure concurrencyClojure concurrency
Clojure concurrency
 
Robust C++ Task Systems Through Compile-time Checks
Robust C++ Task Systems Through Compile-time ChecksRobust C++ Task Systems Through Compile-time Checks
Robust C++ Task Systems Through Compile-time Checks
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/Multitasking
 
Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in Java
 
Async fun
Async funAsync fun
Async fun
 
Server side JavaScript: going all the way
Server side JavaScript: going all the wayServer side JavaScript: going all the way
Server side JavaScript: going all the way
 
Node js lecture
Node js lectureNode js lecture
Node js lecture
 
JavaScript for real men
JavaScript for real menJavaScript for real men
JavaScript for real men
 
Introduction to OpenMP
Introduction to OpenMPIntroduction to OpenMP
Introduction to OpenMP
 
Os Reindersfinal
Os ReindersfinalOs Reindersfinal
Os Reindersfinal
 
Os Reindersfinal
Os ReindersfinalOs Reindersfinal
Os Reindersfinal
 
Clojure concurrency overview
Clojure concurrency overviewClojure concurrency overview
Clojure concurrency overview
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
 
Node.js Course 1 of 2 - Introduction and first steps
Node.js Course 1 of 2 - Introduction and first stepsNode.js Course 1 of 2 - Introduction and first steps
Node.js Course 1 of 2 - Introduction and first steps
 
Threads and Node.js
Threads and Node.jsThreads and Node.js
Threads and Node.js
 
Concurrency Constructs Overview
Concurrency Constructs OverviewConcurrency Constructs Overview
Concurrency Constructs Overview
 
Deuce STM - CMP'09
Deuce STM - CMP'09Deuce STM - CMP'09
Deuce STM - CMP'09
 
G pars
G parsG pars
G pars
 
Medical Image Processing Strategies for multi-core CPUs
Medical Image Processing Strategies for multi-core CPUsMedical Image Processing Strategies for multi-core CPUs
Medical Image Processing Strategies for multi-core CPUs
 

Mehr von Alina Dolgikh

Orm на no sql через jpa. Павел Вейник
Orm на no sql через jpa. Павел ВейникOrm на no sql через jpa. Павел Вейник
Orm на no sql через jpa. Павел ВейникAlina Dolgikh
 
David Mertz. Type Annotations. PyCon Belarus 2015
David Mertz. Type Annotations. PyCon Belarus 2015David Mertz. Type Annotations. PyCon Belarus 2015
David Mertz. Type Annotations. PyCon Belarus 2015Alina Dolgikh
 
Владимир Еремин. Extending Openstack. PyCon Belarus 2015
Владимир Еремин. Extending Openstack. PyCon Belarus 2015Владимир Еремин. Extending Openstack. PyCon Belarus 2015
Владимир Еремин. Extending Openstack. PyCon Belarus 2015Alina Dolgikh
 
Кирилл Борисов. Code style_checking_v2. PyCon Belarus 2015
Кирилл Борисов. Code style_checking_v2. PyCon Belarus 2015Кирилл Борисов. Code style_checking_v2. PyCon Belarus 2015
Кирилл Борисов. Code style_checking_v2. PyCon Belarus 2015Alina Dolgikh
 
Володимир Гоцик. Getting maximum of python, django with postgres 9.4. PyCon B...
Володимир Гоцик. Getting maximum of python, django with postgres 9.4. PyCon B...Володимир Гоцик. Getting maximum of python, django with postgres 9.4. PyCon B...
Володимир Гоцик. Getting maximum of python, django with postgres 9.4. PyCon B...Alina Dolgikh
 
Андрей Солдатенко. Разработка высокопроизводительныx функциональных тестов д...
Андрей Солдатенко. Разработка высокопроизводительныx функциональных тестов д...Андрей Солдатенко. Разработка высокопроизводительныx функциональных тестов д...
Андрей Солдатенко. Разработка высокопроизводительныx функциональных тестов д...Alina Dolgikh
 
Austin Bingham. Transducers in Python. PyCon Belarus
Austin Bingham. Transducers in Python. PyCon BelarusAustin Bingham. Transducers in Python. PyCon Belarus
Austin Bingham. Transducers in Python. PyCon BelarusAlina Dolgikh
 
Austin Bingham. Python Refactoring. PyCon Belarus
Austin Bingham. Python Refactoring. PyCon BelarusAustin Bingham. Python Refactoring. PyCon Belarus
Austin Bingham. Python Refactoring. PyCon BelarusAlina Dolgikh
 
Denis Lebedev. Non functional swift.
Denis Lebedev. Non functional swift.Denis Lebedev. Non functional swift.
Denis Lebedev. Non functional swift.Alina Dolgikh
 
Максим Лапшин. Erlang production
Максим Лапшин. Erlang productionМаксим Лапшин. Erlang production
Максим Лапшин. Erlang productionAlina Dolgikh
 
Максим Харченко. Erlang lincx
Максим Харченко. Erlang lincxМаксим Харченко. Erlang lincx
Максим Харченко. Erlang lincxAlina Dolgikh
 
Пиар в стартапе: извлекаем максимум пользы. Алексей Лартей
Пиар в стартапе: извлекаем максимум пользы. Алексей ЛартейПиар в стартапе: извлекаем максимум пользы. Алексей Лартей
Пиар в стартапе: извлекаем максимум пользы. Алексей ЛартейAlina Dolgikh
 
Подготовка проекта к первому раунду инвестиций. Дмитрий Поляков
Подготовка проекта к первому раунду инвестиций. Дмитрий ПоляковПодготовка проекта к первому раунду инвестиций. Дмитрий Поляков
Подготовка проекта к первому раунду инвестиций. Дмитрий ПоляковAlina Dolgikh
 
Как составлять правильный тизер для инвесторов? Никита Рогозин
Как составлять правильный тизер для инвесторов? Никита РогозинКак составлять правильный тизер для инвесторов? Никита Рогозин
Как составлять правильный тизер для инвесторов? Никита РогозинAlina Dolgikh
 
Startup belarus pres_khamiankova
Startup belarus pres_khamiankovaStartup belarus pres_khamiankova
Startup belarus pres_khamiankovaAlina Dolgikh
 

Mehr von Alina Dolgikh (16)

Orm на no sql через jpa. Павел Вейник
Orm на no sql через jpa. Павел ВейникOrm на no sql через jpa. Павел Вейник
Orm на no sql через jpa. Павел Вейник
 
David Mertz. Type Annotations. PyCon Belarus 2015
David Mertz. Type Annotations. PyCon Belarus 2015David Mertz. Type Annotations. PyCon Belarus 2015
David Mertz. Type Annotations. PyCon Belarus 2015
 
Владимир Еремин. Extending Openstack. PyCon Belarus 2015
Владимир Еремин. Extending Openstack. PyCon Belarus 2015Владимир Еремин. Extending Openstack. PyCon Belarus 2015
Владимир Еремин. Extending Openstack. PyCon Belarus 2015
 
Кирилл Борисов. Code style_checking_v2. PyCon Belarus 2015
Кирилл Борисов. Code style_checking_v2. PyCon Belarus 2015Кирилл Борисов. Code style_checking_v2. PyCon Belarus 2015
Кирилл Борисов. Code style_checking_v2. PyCon Belarus 2015
 
Володимир Гоцик. Getting maximum of python, django with postgres 9.4. PyCon B...
Володимир Гоцик. Getting maximum of python, django with postgres 9.4. PyCon B...Володимир Гоцик. Getting maximum of python, django with postgres 9.4. PyCon B...
Володимир Гоцик. Getting maximum of python, django with postgres 9.4. PyCon B...
 
Андрей Солдатенко. Разработка высокопроизводительныx функциональных тестов д...
Андрей Солдатенко. Разработка высокопроизводительныx функциональных тестов д...Андрей Солдатенко. Разработка высокопроизводительныx функциональных тестов д...
Андрей Солдатенко. Разработка высокопроизводительныx функциональных тестов д...
 
Austin Bingham. Transducers in Python. PyCon Belarus
Austin Bingham. Transducers in Python. PyCon BelarusAustin Bingham. Transducers in Python. PyCon Belarus
Austin Bingham. Transducers in Python. PyCon Belarus
 
Austin Bingham. Python Refactoring. PyCon Belarus
Austin Bingham. Python Refactoring. PyCon BelarusAustin Bingham. Python Refactoring. PyCon Belarus
Austin Bingham. Python Refactoring. PyCon Belarus
 
Denis Lebedev. Non functional swift.
Denis Lebedev. Non functional swift.Denis Lebedev. Non functional swift.
Denis Lebedev. Non functional swift.
 
Максим Лапшин. Erlang production
Максим Лапшин. Erlang productionМаксим Лапшин. Erlang production
Максим Лапшин. Erlang production
 
Максим Харченко. Erlang lincx
Максим Харченко. Erlang lincxМаксим Харченко. Erlang lincx
Максим Харченко. Erlang lincx
 
Пиар в стартапе: извлекаем максимум пользы. Алексей Лартей
Пиар в стартапе: извлекаем максимум пользы. Алексей ЛартейПиар в стартапе: извлекаем максимум пользы. Алексей Лартей
Пиар в стартапе: извлекаем максимум пользы. Алексей Лартей
 
Подготовка проекта к первому раунду инвестиций. Дмитрий Поляков
Подготовка проекта к первому раунду инвестиций. Дмитрий ПоляковПодготовка проекта к первому раунду инвестиций. Дмитрий Поляков
Подготовка проекта к первому раунду инвестиций. Дмитрий Поляков
 
Как составлять правильный тизер для инвесторов? Никита Рогозин
Как составлять правильный тизер для инвесторов? Никита РогозинКак составлять правильный тизер для инвесторов? Никита Рогозин
Как составлять правильный тизер для инвесторов? Никита Рогозин
 
Startup belarus pres_khamiankova
Startup belarus pres_khamiankovaStartup belarus pres_khamiankova
Startup belarus pres_khamiankova
 
Pr talk lartey
Pr talk larteyPr talk lartey
Pr talk lartey
 

Kürzlich hochgeladen

Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
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.docxComplianceQuest1
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
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.pdfkalichargn70th171
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
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 ApplicationsAlberto González Trastoy
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
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.comFatema Valibhai
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
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-...Steffen Staab
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
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 CCTVshikhaohhpro
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
+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
 

Kürzlich hochgeladen (20)

Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
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
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
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
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
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
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
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
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
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-...
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
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
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
+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...
 

Java Concurrency in Practice

  • 2. Premature Optimization is the root of all evil. Donald Knuth We should forget about small efficiencies, say about 97% of the time: Yet we should not pass up our opportunities in that critical 3%.
  • 3. JDK: Atomic*, Streams, synchronized, Locks, Fork/Join, ConcHashMap, ... Libraries: JEE / Spring, Akka, LMAX, Servlet 3, ... Java Memory Model Architecture Algorithms Concepts Ideas
  • 4. 1. Java Memory Model 2. Concepts and Paradigms 3. Performance
  • 5. Threads (naive) ● Threads take turns doing work. ● Each Thread does what the source code says. ● When a thread is interrupted, other threads see the intermediate state. ● Synchronization serves only to make several changes atomic.
  • 6. Threads (a little less naive) ● There are several CPUs / cores executing threads really at the same time. ● Each thread does what the source code says. ● Data access goes to RAM. ● When different threads access the same data, they do that one after the other.
  • 7. Threads: the truth ● Within a single thread, the JVM makes it look as if the thread does what the source code says. ● There is a defined ordering between things happening in different threads if synchronization prescribes that („happens- before“). ● And that is all!
  • 8. Does your computer do what you programmed? yes no
  • 9. Compiler: Instruction Reordering, expression caching, … Hotspot: Register Allocation, Instruction Reordering, Escape Analysis, … Prozessor: Branch Prediction, Speculative Evaluation, Prefetch, … Caches: Store Buffers, Private Shared Caches, … Transformations Visible effects are the same at all levels.
  • 10. Example: Loop termination boolean shutdown = false; … void doIt() { while (!shutdown) { … } } boolean shutdown = false; … void doIt() { boolean b = shutdown; while (!b) { … } }
  • 11. Correct Synchronization ● No Race Conditions: ● If several threads access the same variable, ● and at least one of them writes, ● then access must be ordered by „happens-before“. ● If that is true for a program, then it will run as if ● all memory access was sequential ● and really went to RAM ● in the order defined by „happens-before“.
  • 12. Example: volatile ● If ● Thread T1 writes a volatile Variable v, and ● Thread T2 then reads v, ● then ● all changes T1 made up to writing v are 'before' all code in T2 after the read from v.
  • 13. Memory Barriers ● Tools used to implement JMM ● Assembler instructions ● „synchronizing“ CPUs and Caches ● Constrain Reordering ● Potentially expensive ● Direct Cost: Cache Dirtying ● Limit Optimizations ● Especially between processors ● Where does Java use them? ● synchronized, Locks ● volatile ● after constructors (for final fields), …
  • 15. A simple Logger public class Logger { public void log (String msg, Object... params) { String s = doFormat (msg, params); doLog (s); } private String doFormat (String msg, Object... params) {…} private void doLog (String msg) {…} }
  • 16. thread safe? public class Logger { public synchronized void log (String msg, Object... params) { String s = doFormat (msg, params); doLog (s); } private String doFormat (String msg, Object... params) {…} private void doLog (String msg) {…} }
  • 17. Hidden Deadlocks public class X { public synchronized void doIt () { log.log ("doing it"); … } public synchronized String toString () { … } … } x.doIt(); log.log ("%s", x); lock (x) log.log("...") → lock (log) lock (log) x.toString() → lock (x)
  • 18. Asynchronous Logging final ExecutorService exec = Executors.newSingleThreadExecutor(); public void log (String msg, Object... args) { exec.execute (() -> { String formatted = doFormat (msg, args); doLog (formatted); }); }
  • 19. Parallel Execution? ● Formatting can be expensive ● toString(): Callbacks to application code! ● Thread Pool for Logging? ● Message ordering is lost! ● … and doLog() ist not thread safe
  • 20. Future<String> final ExecutorService exec = Executors.newSingleThreadExecutor(); public void log (String msg, Object... args) { final Future<String> formatted = CompletableFuture.supplyAsync(() -> doFormat(msg, args)); exec.execute (() -> { try { doLog (formatted.get()); } catch (Exception exc) { exc.printStackTrace(); } }); }
  • 21. Concurrency: Shared Mutable State ● Locks: Blocking ● Read/Write and other optimizations ● Single Worker-Thread with a Message-Queue: Non-Blocking ● Actors as a variant ● „Lock Free“ has share mutable state ● Every approach has its specific cost!
  • 22. Worker Threads ● Queues ● Bounded / Unbounded ● Blocking / Non-Blocking ● Single / Multi Producers / Consumers ● Optimized for reading or writing (or a mix) ● Special features: Priority, remove(), Batch, … ● Future for results ● .thenAccept(...) / .thenAcceptAsync(...)
  • 23. Which Thread Pool to use? ● Code with side effects ● (usually) ordering is important → Executors.newSingleThreadPool() ● non-blocking without Seiteneffekte ● ForkJoinPool.commonPool() ● blocking ● Specific ExecutorService per context ● Tuning, Monitoring, … ● Divide and conquer big proglems ● Measure to verify assumptions! ● Never ad hoc!
  • 25. Sharing is the root of all contention ● more precisely: sharing mutable Ressources ● Locks, I/O, … ● Hidden Sharing ● ReadLock: Counter ● UUID.randomUUID() ● volatile: Shared main memory ● Cache Lines (Locality, Poisoning) ● Disk, DVDs, Network ● … ● Solutions: Isolation or Immutability
  • 26. Lock-free Programming ● Shared Mutable State ● Lock Free ● Callers need never wait ● Processing may be delayed however ● e.g. asynchronous decoupling ● Responsive, saves ressources ● Wait Free ● Processing without a delay ● Special algorithms and data structures ● Highly complex; Ongoing research, work in progress ● ConcurrentHashMap, ConcurrentLinkedQueue
  • 27. CAS loop final AtomicInteger n = new AtomicInteger (0); int max (int i) { int prev, next; do { prev = n.get(); next = Math.max (prev, i); } while (! n.compareAndSet (prev, next)); return next; }
  • 28. Functional Programming ● No Seiteneffekte ● All Objects are immutable, changes create new objects ● not just using Lambdas: JDK collections, Guice, … ● Scala, Clojure; a-foundation ● different style of programming ● efficient copying: partial reuse of objects ● functional algorithms ● State is stable automatically, even concurrently
  • 29. Performance-Tuning for Concurrency public class StockExchange { private final Map<Currency, Double> rates = new HashMap<>(); private final Map<String, Double> pricesInEuro = new HashMap<>(); public void updateRate (Currency currency, double fromEuro) { rates.put (currency, fromEuro); } public void updatePrice (String wkz, double euros) { pricesInEuro.put (wkz, euros); } public double currentPrice (String wkz, Currency currency) { return pricesInEuro.get (wkz) * rates.get (currency); } }
  • 30. Wait-Free: ConcurrentHashMap public class StockExchange { private final Map<Currency, Double> rates = new ConcurrentHashMap<>(); private final Map<String, Double> pricesInEuro = new ConcurrentHashMap<>(); … }
  • 31. Fine-grained Locks: Collections.synchronizedMap public class StockExchange { private final Map<Currency, Double> rates = Collections.synchronizedMap (new HashMap<>()); private final Map<String, Double> pricesInEuro = Collections.synchronizedMap (new HashMap<>()); … }
  • 32. Coarse Locks public class StockExchange { … public synchronized void updateRate (…) { … } public synchronized void updatePrice (…) { … } public synchronized double currentPrice (…) { … } }
  • 33. Functional: Immutable Maps public class StockExchange { private final AtomicReference<AMap<Currency, Double>> rates = new AtomicReference<> (AHashMap.empty ()); … public void updateRate (Currency currency, double fromEuro) { AMap<Currency, Double> prev, next; do { prev = rates.get (); next = prev.updated (currency, fromEuro); } while (! rates.compareAndSet (prev, next)); } … }
  • 34. Variant: reduced update guarantees public class StockExchange { private volatile AMap<Currency, Double> rates = AHashMap.empty (); … public void updateRate (Currency currency, double fromEuro) { rates = rates.updated (currency, fromEuro); } … }
  • 35. Queue with a Worker-Thread public class StockExchange { private final Map<Currency, Double> rates = new HashMap<>(); … private final BlockingQueue<Runnable> queue = …; public StockExchange() { new Thread(() -> { while (true) queue.take().run(); }).start(); } public void updateRate (Currency currency, double fromEuro) { queue.put (() -> rates.put (currency, fromEuro)); } … }
  • 36. Tests for comparison for (int i=0; i<1_000_000; i++) { stockExchange.updatePrice ("abc", 1.23); } volatile int v=0; … for (int i=0; i<1_000_000; i++) { v=v; stockExchange.updatePrice ("abc", 1.23); } volatile int v=0; final LinkedList<String> l = new LinkedList<>(); … for (int i=0; i<1_000_000; i++) { l.add ("abc"); v=v; stockExchange.updatePrice (l.remove(), 1.23); }
  • 40. And the Winner is... ● ConcurrentHashMap ● No consistency requirements, mostly reads, algorithmic access ● Queue with Worker Thread ● Transactionaler access, centralized Event-Queue ● Data locality in multi-processor systems ● Immutable Map ● Stable data during read operations ● long running reads ● „lossy“ → fast udate ● Locks ● never particularly fast → prescribed threading and data model ● Granularity: Lock per operation
  • 41. Testing (1): Correctness ● „it wors“ is not enough ● JMM vs. JVM, Hardware, … ● Reviews ● controlled interruptions ● Shotgun
  • 42. Testen (2): Performance ● Reserve time for testing! ● realistic Hardware ● big Hardware ● Multi-Core vs. Multi-Prozessor → HW optimizations for cache exchange ● Scaling effects ● realistic load scenarios (→ Know your load!!! Document assumptions!!!) ● Virtualized hardware ● Ask specific questions – there are many variables ● Pool sizes, cut-off for serial processing ● Hardware sizes: RAM, #Cores, … ● Series of measurements to evaluate alternatives
  • 43. Practice: Local Parallelization ● e.g. searching in a large collection ● Fork/Join examples ● Streams-API ● Verify improvements ● APIs are simple and invite „ad hoc“ use ● apparent improvements – at least without background load ● overall CPU load is increased – use only if CPUs would otherwise be idling! ● Measure, measure, measure: real hardware, real load scenarios
  • 44. Wrap-Up ● Concurrency is difficult ● Really understand your problems ● Measure, measure, measure! ● OS and hardware influence behavior ● Correctness before performance ● Korrektheit vor Performance ● Möglichst grobe Concurrency ● Share Nothing
  • 45. The End ● Links: ● http://channel9.msdn.com/Shows/Going+Deep/Cpp -and-Beyond-2012-Herb-Sutter-atomic-Weapons-1- of-2 ● http://github.com/arnohaase/a-foundation