SlideShare a Scribd company logo
 
Notes on Concurrent, parallel programming with threads Concurrent = work done in several computational processes, only requires one CPU Parallel = work (computations) done simultaneous, requires multiple CPU:s – locally or distributed
GC and Threads and Java CG made easy in Java Person p = null; Concurrent programming made possible (but not easy) Low level support: threads and mutexes volatile boolean stop = false; public void stop() { stop = true; } public void run() { while(!stop) { try { // Do some work Thread.sleep(10); // check stop }catch(InterruptedException ie) { // Ignore } } } // stop = true; thread.interrupt();
Some Hard stuff Data  visibility  between threads Volitile semantics Asynchronous code Race conditions and Deadlocks Congestion/Performance
Data visibility Data not guaranteed to be visable between threads without synchronization long and double not even guaranteed to be ”complete” // In thread 1 at time 1 commonObject.myLong = Long.MAX_VALUE; // In thread 2 at time 2 if(commonObject.myLong > Integer.MAX_VALUE) {
Broken objects The ordering of access to a reference and a constructed object is not guaranteed
If one thread can see an object another thread constructs it might see broken objects (ref available before object constructed)
Double locking // Broken multithreaded version // "Double-Checked Locking" idiom class Foo {  private Helper helper = null; public Helper getHelper() { if (helper == null)  synchronized(this) { if (helper == null)  helper = new Helper(); }  return helper; } // other functions and members... }
Volitile behaviour up until Java 1.4 The Java memory model did not guarantee non reordering on Volatile before 1.5 class VolatileExample { int x = 0; volatile boolean v = false; public void writer() { // Before 1.5 could be done in any order x = 42; v = true; } public void reader() { if (v == true) { //uses x - guaranteed to see 42. } } } // Works with acquire/release semantics for volatile // Broken under current semantics for volatile class Foo { private volatile Helper helper = null; public Helper getHelper() { if (helper == null) { synchronized(this) { if (helper == null) helper = new Helper(); } } return helper; } } Broken up until 1.5 The order of x and v not guaranteed in 1.4
Sending asynchronous messages is complex public void fetchAsync() { Thread t = new Thread(new Runnable() { public void run() {   // Do work in other thread   dataArived("hello"); }   }); t.start(); } public synchronized void dataArived(String s) { // Update data, must be synchronized somehow to be visable }
Reading and writing common data always requires synchronization Sets a limit to scalability
Amdahl's law (simlified):  1/(1 – p)
where P is percentage parallelizable work gives the maximum number of CPU:s that are meaningfull to use when speed is considered.
For example, of 5 percent of the application is serialized because of a common synchronization (such as read on a cache), the maximum number of CPU:s are 20
To fully gain througout by 64 cores about 99 % must be parallelizable
Polopoly on multi core machines
Better data structures from JDK 1.5 – using modern memory management techniques ConcurrentHashMap

More Related Content

PPTX
Java concurrency in practice
KEY
Fork/Join for Fun and Profit!
PDF
Fork Join (BeJUG 2012)
PPTX
Fork and join framework
PDF
Non-blocking Michael-Scott queue algorithm
PPTX
Fork Join
PDF
Concurrency Utilities in Java 8
PDF
Counter Wars (JEEConf 2016)
Java concurrency in practice
Fork/Join for Fun and Profit!
Fork Join (BeJUG 2012)
Fork and join framework
Non-blocking Michael-Scott queue algorithm
Fork Join
Concurrency Utilities in Java 8
Counter Wars (JEEConf 2016)

What's hot (20)

ODP
Concurrent Programming in Java
PDF
NYAN Conference: Debugging asynchronous scenarios in .net
PPTX
Real world functional reactive programming
PPT
Reactive programming with examples
PDF
Quick Introduction to Kotlin Coroutine for Android Dev
ODP
Java Concurrency, Memory Model, and Trends
PDF
PDF
The Future of Futures - A Talk About Java 8 CompletableFutures
PDF
Functional Reactive Programming / Compositional Event Systems
PDF
Building Hermetic Systems (without Docker)
PPTX
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
PDF
Lock free programming - pro tips devoxx uk
PPTX
The Road To Reactive with RxJava JEEConf 2016
PDF
Non Blocking I/O for Everyone with RxJava
PDF
Callbacks and control flow in Node js
PDF
S emb t13-freertos
PDF
The Newest in Session Types
PPTX
Reactive Java (33rd Degree)
PPT
Shared objects and synchronization
PPTX
RxJava Applied
Concurrent Programming in Java
NYAN Conference: Debugging asynchronous scenarios in .net
Real world functional reactive programming
Reactive programming with examples
Quick Introduction to Kotlin Coroutine for Android Dev
Java Concurrency, Memory Model, and Trends
The Future of Futures - A Talk About Java 8 CompletableFutures
Functional Reactive Programming / Compositional Event Systems
Building Hermetic Systems (without Docker)
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
Lock free programming - pro tips devoxx uk
The Road To Reactive with RxJava JEEConf 2016
Non Blocking I/O for Everyone with RxJava
Callbacks and control flow in Node js
S emb t13-freertos
The Newest in Session Types
Reactive Java (33rd Degree)
Shared objects and synchronization
RxJava Applied
Ad

Similar to Threads and concurrency in Java 1.5 (20)

ODP
Java Concurrency
PPT
Java util concurrent
PPT
JAVA MULTITHREDED PROGRAMMING - LECTURES
PPTX
Async java8
PPT
Threaded Programming
PDF
Loom and concurrency latest
PPT
Java Tut1
PPT
Java Tutorial
PPT
Java tut1
PPT
Tutorial java
PPTX
Effective java - concurrency
DOCX
Parallel Programming With Dot Net
PDF
Multithreading in Java
PPT
Server side JavaScript: going all the way
PPTX
Vert.x - Reactive & Distributed [Devoxx version]
PPT
JS everywhere 2011
PDF
Leveraging Completable Futures to handle your query results Asynchrhonously
PDF
Cool JVM Tools to Help You Test
PPTX
.NET Multithreading/Multitasking
PDF
Here comes the Loom - Ya!vaConf.pdf
Java Concurrency
Java util concurrent
JAVA MULTITHREDED PROGRAMMING - LECTURES
Async java8
Threaded Programming
Loom and concurrency latest
Java Tut1
Java Tutorial
Java tut1
Tutorial java
Effective java - concurrency
Parallel Programming With Dot Net
Multithreading in Java
Server side JavaScript: going all the way
Vert.x - Reactive & Distributed [Devoxx version]
JS everywhere 2011
Leveraging Completable Futures to handle your query results Asynchrhonously
Cool JVM Tools to Help You Test
.NET Multithreading/Multitasking
Here comes the Loom - Ya!vaConf.pdf
Ad

More from Peter Antman (20)

PPTX
Core Protocols - A workshop
PDF
Growing up with agile - how the Spotify 'model' has evolved
PDF
Fluent at agile - agile sverige 2014
PDF
Pirateship - growing a great crew: workshop facilitation guide
PPTX
Facilitating the Elephant carpaccio exercise
PPTX
User Story Workshop
PPTX
Lean Canvas - a hypotheses board
PPTX
Strong decisions with consensus, Agila Sverige 2014
PDF
Lean Dot Game
PPTX
Stop the line @spotify
PPTX
Tear Down the Pyramid Again - Agile Management from the trenches
PPTX
Piemonte vin
ODP
The Bespoke Software Product Factory (2007)
ODP
Java 1.5 - whats new and modern patterns (2007)
ODP
Java Server Faces 1.2 presented (2007)
ODP
EJB 3.0 Walkthrough (2006)
ODP
Så funkar det (del 3) - webben
ODP
Så funkar det (del 2) - mail
ODP
Så funkar det (del 1) - word
ODP
eXtreme Programming
Core Protocols - A workshop
Growing up with agile - how the Spotify 'model' has evolved
Fluent at agile - agile sverige 2014
Pirateship - growing a great crew: workshop facilitation guide
Facilitating the Elephant carpaccio exercise
User Story Workshop
Lean Canvas - a hypotheses board
Strong decisions with consensus, Agila Sverige 2014
Lean Dot Game
Stop the line @spotify
Tear Down the Pyramid Again - Agile Management from the trenches
Piemonte vin
The Bespoke Software Product Factory (2007)
Java 1.5 - whats new and modern patterns (2007)
Java Server Faces 1.2 presented (2007)
EJB 3.0 Walkthrough (2006)
Så funkar det (del 3) - webben
Så funkar det (del 2) - mail
Så funkar det (del 1) - word
eXtreme Programming

Recently uploaded (20)

PPTX
Big Data Technologies - Introduction.pptx
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
A Presentation on Artificial Intelligence
PPTX
Machine Learning_overview_presentation.pptx
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PPTX
sap open course for s4hana steps from ECC to s4
PPTX
Spectroscopy.pptx food analysis technology
PDF
Encapsulation theory and applications.pdf
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Spectral efficient network and resource selection model in 5G networks
PPTX
Cloud computing and distributed systems.
Big Data Technologies - Introduction.pptx
MYSQL Presentation for SQL database connectivity
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Diabetes mellitus diagnosis method based random forest with bat algorithm
A Presentation on Artificial Intelligence
Machine Learning_overview_presentation.pptx
Digital-Transformation-Roadmap-for-Companies.pptx
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
NewMind AI Weekly Chronicles - August'25-Week II
Dropbox Q2 2025 Financial Results & Investor Presentation
Programs and apps: productivity, graphics, security and other tools
MIND Revenue Release Quarter 2 2025 Press Release
The Rise and Fall of 3GPP – Time for a Sabbatical?
sap open course for s4hana steps from ECC to s4
Spectroscopy.pptx food analysis technology
Encapsulation theory and applications.pdf
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Encapsulation_ Review paper, used for researhc scholars
Spectral efficient network and resource selection model in 5G networks
Cloud computing and distributed systems.

Threads and concurrency in Java 1.5

  • 1.  
  • 2. Notes on Concurrent, parallel programming with threads Concurrent = work done in several computational processes, only requires one CPU Parallel = work (computations) done simultaneous, requires multiple CPU:s – locally or distributed
  • 3. GC and Threads and Java CG made easy in Java Person p = null; Concurrent programming made possible (but not easy) Low level support: threads and mutexes volatile boolean stop = false; public void stop() { stop = true; } public void run() { while(!stop) { try { // Do some work Thread.sleep(10); // check stop }catch(InterruptedException ie) { // Ignore } } } // stop = true; thread.interrupt();
  • 4. Some Hard stuff Data visibility between threads Volitile semantics Asynchronous code Race conditions and Deadlocks Congestion/Performance
  • 5. Data visibility Data not guaranteed to be visable between threads without synchronization long and double not even guaranteed to be ”complete” // In thread 1 at time 1 commonObject.myLong = Long.MAX_VALUE; // In thread 2 at time 2 if(commonObject.myLong > Integer.MAX_VALUE) {
  • 6. Broken objects The ordering of access to a reference and a constructed object is not guaranteed
  • 7. If one thread can see an object another thread constructs it might see broken objects (ref available before object constructed)
  • 8. Double locking // Broken multithreaded version // "Double-Checked Locking" idiom class Foo { private Helper helper = null; public Helper getHelper() { if (helper == null) synchronized(this) { if (helper == null) helper = new Helper(); } return helper; } // other functions and members... }
  • 9. Volitile behaviour up until Java 1.4 The Java memory model did not guarantee non reordering on Volatile before 1.5 class VolatileExample { int x = 0; volatile boolean v = false; public void writer() { // Before 1.5 could be done in any order x = 42; v = true; } public void reader() { if (v == true) { //uses x - guaranteed to see 42. } } } // Works with acquire/release semantics for volatile // Broken under current semantics for volatile class Foo { private volatile Helper helper = null; public Helper getHelper() { if (helper == null) { synchronized(this) { if (helper == null) helper = new Helper(); } } return helper; } } Broken up until 1.5 The order of x and v not guaranteed in 1.4
  • 10. Sending asynchronous messages is complex public void fetchAsync() { Thread t = new Thread(new Runnable() { public void run() { // Do work in other thread dataArived("hello"); } }); t.start(); } public synchronized void dataArived(String s) { // Update data, must be synchronized somehow to be visable }
  • 11. Reading and writing common data always requires synchronization Sets a limit to scalability
  • 13. where P is percentage parallelizable work gives the maximum number of CPU:s that are meaningfull to use when speed is considered.
  • 14. For example, of 5 percent of the application is serialized because of a common synchronization (such as read on a cache), the maximum number of CPU:s are 20
  • 15. To fully gain througout by 64 cores about 99 % must be parallelizable
  • 16. Polopoly on multi core machines
  • 17. Better data structures from JDK 1.5 – using modern memory management techniques ConcurrentHashMap
  • 19. Optimized for reads: does not block reads even when its updated
  • 20. Does often not block on updates either
  • 22. Atomic check and take action methods V putIfAbsent(K key, V value); boolean remove(Object key, Object value); V replace(K key, V value); boolean replace(K key, V oldValue, V newValue);
  • 25. May track submitted task and get result back
  • 26. Uses Future and Callable Callable<String> worker = new Callable<String>() { int c = 0; public String call() { try {Thread.sleep(2000L);}catch(Exception ignore){} return &quot;jobb no &quot; + c++; } }; ExecutorService exe = Executors.newSingleThreadExecutor(); Future<String> result = exe.submit(worker); while(!result.isDone()) { // Do something other } String s = result.get();
  • 28. volatile but with conditional atomicity
  • 29. Finer granularity of locking (hardware based)
  • 31. Built on optimistic assumptions: do it, check and redo
  • 32. Non blocking counting AtomicLong at = new AtomicLong(); // one thread, no synchronzied long current = at.get(); // another thread increment, no sync at.incrementAndGet();
  • 33. To really solve the parallelity problem you have to look at the world differently Value (immutable)
  • 34. Identity (holder of values over time)
  • 35. State (value of an identity at a point of time)
  • 37. PDS
  • 38. Clojure Clojure Transaction re-ref (coordinated) Asynchronous Atomic and independent
  • 39. Some buzwords to remember Transactional Memory