Notes on Concurrent, parallel programming with threads Concurrent = work done in several computational processes, only req...
GC and Threads and Java CG made easy in Java Person p = null; Concurrent programming made possible (but not easy) Low leve...
Some Hard stuff Data  visibility  between threads Volitile semantics Asynchronous code Race conditions and Deadlocks Conge...
Data visibility Data not guaranteed to be visable between threads without synchronization long and double not even guarant...
Broken objects <ul><li>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 constru...
Double locking </li></ul>// Broken multithreaded version // &quot;Double-Checked Locking&quot; idiom class Foo {  private ...
Volitile behaviour up until Java 1.4 <ul><li>The Java memory model did not guarantee non reordering on Volatile before 1.5...
Sending asynchronous messages is complex public void fetchAsync() { Thread t = new Thread(new Runnable() { public void run...
Reading and writing common data always requires synchronization <ul><li>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 cons...
For example, of 5 percent of the application is serialized because of a common synchronization (such as read on a cache), ...
To fully gain througout by 64 cores about 99 % must be parallelizable </li></ul>
Polopoly on multi core machines
Better data structures from JDK 1.5 – using modern memory management techniques <ul><li>ConcurrentHashMap
Upcoming SlideShare
Loading in …5
×

Threads and concurrency in Java 1.5

1,983 views
1,838 views

Published on

A lightning talk from a geeknight at Polopoly in 2009 about concurrent programming in Java.

Published in: Technology, News & Politics
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
1,983
On SlideShare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
0
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

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
  2. 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();
  3. 4. Some Hard stuff Data visibility between threads Volitile semantics Asynchronous code Race conditions and Deadlocks Congestion/Performance
  4. 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) {
  5. 6. Broken objects <ul><li>The ordering of access to a reference and a constructed object is not guaranteed
  6. 7. If one thread can see an object another thread constructs it might see broken objects (ref available before object constructed)
  7. 8. Double locking </li></ul>// Broken multithreaded version // &quot;Double-Checked Locking&quot; 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... }
  8. 9. Volitile behaviour up until Java 1.4 <ul><li>The Java memory model did not guarantee non reordering on Volatile before 1.5 </li></ul>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
  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(&quot;hello&quot;); } }); t.start(); } public synchronized void dataArived(String s) { // Update data, must be synchronized somehow to be visable }
  10. 11. Reading and writing common data always requires synchronization <ul><li>Sets a limit to scalability
  11. 12. Amdahl's law (simlified): 1/(1 – p)
  12. 13. where P is percentage parallelizable work gives the maximum number of CPU:s that are meaningfull to use when speed is considered.
  13. 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
  14. 15. To fully gain througout by 64 cores about 99 % must be parallelizable </li></ul>
  15. 16. Polopoly on multi core machines
  16. 17. Better data structures from JDK 1.5 – using modern memory management techniques <ul><li>ConcurrentHashMap
  17. 18. Lock striping
  18. 19. Optimized for reads: does not block reads even when its updated
  19. 20. Does often not block on updates either
  20. 21. Weakly consistent iterators
  21. 22. Atomic check and take action methods </li></ul>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);
  22. 23. ExecutorService <ul><li>Extension to Executor
  23. 24. Provides management methods
  24. 25. May track submitted task and get result back
  25. 26. Uses Future and Callable </li></ul>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();
  26. 27. Atomic Objects <ul><li>java.util.concurrent.atomic
  27. 28. volatile but with conditional atomicity
  28. 29. Finer granularity of locking (hardware based)
  29. 30. Non blocking
  30. 31. Built on optimistic assumptions: do it, check and redo
  31. 32. Non blocking counting </li></ul>AtomicLong at = new AtomicLong(); // one thread, no synchronzied long current = at.get(); // another thread increment, no sync at.incrementAndGet();
  32. 33. To really solve the parallelity problem you have to look at the world differently <ul><li>Value (immutable)
  33. 34. Identity (holder of values over time)
  34. 35. State (value of an identity at a point of time)
  35. 36. Time (ordering) </li></ul>
  36. 37. PDS
  37. 38. Clojure Clojure Transaction re-ref (coordinated) Asynchronous Atomic and independent
  38. 39. Some buzwords to remember <ul><li>Transactional Memory
  39. 40. Memory Conflict Detection
  40. 41. Eventually Consistent
  41. 42. Imutable </li></ul>

×