SlideShare ist ein Scribd-Unternehmen logo
1 von 17
 
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 ,[object Object]
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 ,[object Object],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 ,[object Object]
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 ,[object Object]

Weitere ähnliche Inhalte

Was ist angesagt?

Functional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event SystemsFunctional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event Systems
Leonardo Borges
 
Shared objects and synchronization
Shared objects and synchronization Shared objects and synchronization
Shared objects and synchronization
Dr. C.V. Suresh Babu
 

Was ist angesagt? (20)

Concurrent Programming in Java
Concurrent Programming in JavaConcurrent Programming in Java
Concurrent Programming in Java
 
NYAN Conference: Debugging asynchronous scenarios in .net
NYAN Conference: Debugging asynchronous scenarios in .netNYAN Conference: Debugging asynchronous scenarios in .net
NYAN Conference: Debugging asynchronous scenarios in .net
 
Real world functional reactive programming
Real world functional reactive programmingReal world functional reactive programming
Real world functional reactive programming
 
Reactive programming with examples
Reactive programming with examplesReactive programming with examples
Reactive programming with examples
 
Quick Introduction to Kotlin Coroutine for Android Dev
Quick Introduction to Kotlin Coroutine for Android DevQuick Introduction to Kotlin Coroutine for Android Dev
Quick Introduction to Kotlin Coroutine for Android Dev
 
Java Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and TrendsJava Concurrency, Memory Model, and Trends
Java Concurrency, Memory Model, and Trends
 
JavaCro'15 - Spring @Async - Dragan Juričić
JavaCro'15 - Spring @Async - Dragan JuričićJavaCro'15 - Spring @Async - Dragan Juričić
JavaCro'15 - Spring @Async - Dragan Juričić
 
The Future of Futures - A Talk About Java 8 CompletableFutures
The Future of Futures - A Talk About Java 8 CompletableFuturesThe Future of Futures - A Talk About Java 8 CompletableFutures
The Future of Futures - A Talk About Java 8 CompletableFutures
 
Functional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event SystemsFunctional Reactive Programming / Compositional Event Systems
Functional Reactive Programming / Compositional Event Systems
 
Building Hermetic Systems (without Docker)
Building Hermetic Systems (without Docker)Building Hermetic Systems (without Docker)
Building Hermetic Systems (without Docker)
 
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
4Developers 2015: Programowanie synchroniczne i asynchroniczne - dwa światy k...
 
Lock free programming - pro tips devoxx uk
Lock free programming - pro tips devoxx ukLock free programming - pro tips devoxx uk
Lock free programming - pro tips devoxx uk
 
The Road To Reactive with RxJava JEEConf 2016
The Road To Reactive with RxJava JEEConf 2016The Road To Reactive with RxJava JEEConf 2016
The Road To Reactive with RxJava JEEConf 2016
 
Non Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJavaNon Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJava
 
Callbacks and control flow in Node js
Callbacks and control flow in Node jsCallbacks and control flow in Node js
Callbacks and control flow in Node js
 
S emb t13-freertos
S emb t13-freertosS emb t13-freertos
S emb t13-freertos
 
The Newest in Session Types
The Newest in Session TypesThe Newest in Session Types
The Newest in Session Types
 
Reactive Java (33rd Degree)
Reactive Java (33rd Degree)Reactive Java (33rd Degree)
Reactive Java (33rd Degree)
 
Shared objects and synchronization
Shared objects and synchronization Shared objects and synchronization
Shared objects and synchronization
 
RxJava Applied
RxJava AppliedRxJava Applied
RxJava Applied
 

Ähnlich wie Threads and concurrency in Java 1.5

Threaded Programming
Threaded ProgrammingThreaded Programming
Threaded Programming
Sri Prasanna
 

Ähnlich wie Threads and concurrency in Java 1.5 (20)

Java Concurrency
Java ConcurrencyJava Concurrency
Java Concurrency
 
Java util concurrent
Java util concurrentJava util concurrent
Java util concurrent
 
Async java8
Async java8Async java8
Async java8
 
Threaded Programming
Threaded ProgrammingThreaded Programming
Threaded Programming
 
Loom and concurrency latest
Loom and concurrency latestLoom and concurrency latest
Loom and concurrency latest
 
Java tut1
Java tut1Java tut1
Java tut1
 
Tutorial java
Tutorial javaTutorial java
Tutorial java
 
Java Tut1
Java Tut1Java Tut1
Java Tut1
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
Effective java - concurrency
Effective java - concurrencyEffective java - concurrency
Effective java - concurrency
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in Java
 
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
 
Vert.x - Reactive & Distributed [Devoxx version]
Vert.x - Reactive & Distributed [Devoxx version]Vert.x - Reactive & Distributed [Devoxx version]
Vert.x - Reactive & Distributed [Devoxx version]
 
JS everywhere 2011
JS everywhere 2011JS everywhere 2011
JS everywhere 2011
 
Leveraging Completable Futures to handle your query results Asynchrhonously
Leveraging Completable Futures to handle your query results AsynchrhonouslyLeveraging Completable Futures to handle your query results Asynchrhonously
Leveraging Completable Futures to handle your query results Asynchrhonously
 
Cool JVM Tools to Help You Test
Cool JVM Tools to Help You TestCool JVM Tools to Help You Test
Cool JVM Tools to Help You Test
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/Multitasking
 
Here comes the Loom - Ya!vaConf.pdf
Here comes the Loom - Ya!vaConf.pdfHere comes the Loom - Ya!vaConf.pdf
Here comes the Loom - Ya!vaConf.pdf
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM Mechanics
 

Mehr von Peter Antman

Mehr von Peter Antman (20)

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

Kürzlich hochgeladen

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Kürzlich hochgeladen (20)

Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 

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.
  • 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.
  • 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.
  • 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.
  • 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);
  • 23.
  • 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();
  • 27.
  • 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.
  • 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.