Advanced Introduction To Java Multi-Threading (Recovered)
Advanced Introduction To Java Multi-Threading (Recovered)
Java Multi-Threading
LAU Chok Sheak, June 2012
Abbreviations Used
CPU Caching
(General background info on how CPU caches work)
http://en.wikipedia.org/wiki/CPU_cache
References - Unofficial JSR-133
FAQ to JSR 133 - The Java Memory Model
(Human-readable introduction to JSR-133)
http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html
Answer:
If you only write single-threaded programs => No.
If you write multi-threaded programs => Yes.
What is the Java Memory Model (JMM)?
Any more details would be beyond the scope of this presentation, but
you may feel free to read up further on your own.
Part I. Java Memory Model
int n = 0; n = 1; if (v == true)
boolean v = false; v = true; System.out.println("n=" + n);
int n = 0; n = 1; if (v == true)
boolean v = false; v = true; System.out.println("n=" + n);
Answer: Yes!
Why? v=true might come before n=1 in compiler
reorderings. Also n=1 might not become visible in Thread
2, so Thread 2 will load n=0.
Fix: If you make v as volatile, then Thread 2 can only print
“n=1”. n does not need to be volatile. n cannot be
reordered to come after v=true when v is volatile.
JMM – Sample Code 2: Synchronized
block
Initialization Thread 1 Thread 2
Answer: No!
Why? The values of both x and y gets synchronized
between Threads 1 and 2 by implicit memory barriers
across the synchronized block boundaries. All values will
be synchronized even if they are not volatile. The
synchronization object does not have to be the owning
class instance object "this". It can be any object.
JMM – Sample Code 3:
Double-checked locking
public class MyClass { Question: Is it possible to
private MyClass() {} create two or more
private static MyClass instance; instances of MyClass
public static MyClass getInstance() { using getInstance() when
if (instance == null) this code is run in
synchronized (MyClass.class) { multi-threaded mode?
if (instance == null)
instance = new MyClass();
Hint: Does "instance"
}
need to be volatile in
return instance;
order for this to work
}
correctly?
}
JMM – Sample Code 3:
Double-checked locking (2)
Answer: No, but the code is buggy.
Why? "instance" must be volatile, otherwise
the invocation of the constructor could be
reordered out of the synchronized block and a
different thread might get "instance" in an
uninitialized state even though it is not
possible to create two instances here.
JMM – Sample Code 3:
Double-checked locking (3)
Some people claim that this code:
instance = new MyClass();
Can be compiled into this code (which is correct):
A. instance = create new uninitialized object
B. invoke constructor on instance
Which means that between points A and B, instance is in
an uninitialized state, and another thread may obtain a
reference to it. Therefore this code is only correct in a
single-threaded context, but not in a multithreaded
context. This is possible when instance is not volatile and
thus can be reordered!
JMM and Double-Checked Locking
There are two cases to consider to see whether you should
use double-checked locking or not:
● Lock objects
● Executors
● Concurrent collections
● Atomic variables
● Other stuff
Concurrent Utilities
1. Lock Objects
Package: java.util.concurrent.locks
ReentrantLock
● Almost the same as the synchronized keyword with wait(), notify() and notifyAll(),
but gives more flexibility.
● "Reentrant" means that when you have already acquired the lock, you can acquire
the same lock again without deadlocking yourself.
● "Reentrant" also means that if two or more threads execute the same piece of
code at the same time, there won’t be any conflicts (this definition does not apply
here).
● The synchronized keyword and the ReentrantLock uses two completely different
sets of code and has nothing in common.
● The synchronized keyword seems to perform better with uncontended locks, but
the ReentrantLock seems to perform better with contended locks. (no guarantees
here)
● Main use of ReentrantLock – can try locking with timeout.
Concurrent Utilities
1. Lock Objects (2)
ReentrantReadWriteLock
● Encapsulates two different types of locks
within one lock – a read lock and a write
lock.
● Usually only useful when you have a large
number of readers and small number of
writers, and user operations outweigh
synchronization overhead.
● Usually only useful when you have multiple
CPUs.
Concurrent Utilities
2. Executors
● Abstraction of the execution of a large
number of tasks immediately or in the
future.
● I have not found the executors to be very
useful.
● Basically only three types of Executors in
the JDK:
○ ThreadPoolExecutor
○ ScheduledThreadPoolExecutor
○ ForkJoinPool (new in Java 7)
Concurrent Utilities
2. Executors (2)
● You might find that ThreadPoolExecutor is
the only executor you will ever need to use.
● Option of either fixed or variable sized
thread pools.
● I have never found variable-sized thread
pools useful, so I only need fixed-sized
thread pools (thread creation is a bit
expensive).
● Make sure never to use an unbounded thread
pool (unlimited number of threads).
Concurrent Utilities
3. Concurrent Collections
ConcurrentHashMap
● Perhaps the most commonly-used concurrent
collection that exists.
● Similar to a synchronized map, but allows more
concurrency by splitting the table into lock sections.
● Performance is comparable to Cliff Click’s
NonBlockingHashMap, which is a lock-free hashmap
that outperforms ConcurrentHashMap only when you
have a large number of processors.
Concurrent Utilities
3. Concurrent Collections (2)
ArrayBlockingQueue
● Fixed-length array-backed blocking queue.
LinkedBlockingQueue
● Variable-length linked-list-backed blocking
queue.
● Allows option to specify max possible queue
size so that it does not get filled up
indefinitely.
Concurrent Utilities
3. Concurrent Collections (3)
ArrayBlockingQueue vs LinkedBlockingQueue
● Both use very basic wait/notifyAll implementation with
no spin retries.
● Advantage of using linked list: 1) saves memory when
queue is empty.
● Advantage of using array: 1) less memory allocation
and GC, 2) less pointer dereferencing (faster), 3) uses
less memory when queue is full.
● Hence most of the time I will choose to use an
ArrayBlockingQueue, not a LinkedBlockingQueue.
Concurrent Utilities
3. More Concurrent Collections
● Some more concurrent collections that I have never
used before.
● Provided here only as an overview.
● Source code and javadoc readily available online.
ConcurrentLinkedDeque DelayQueue
ConcurrentLinkedQueue ForkJoinPool (new in Java 7)
ConcurrentSkipListMap LinkedBlockingDeque
ConcurrentSkipListSet LinkedTransferQueue
CopyOnWriteArrayList PriorityBlockingQueue
CopyOnWriteArraySet SynchronousQueue
Concurrent Utilities
The LMAX Disruptor Blocking Queue
● The LMAX Disruptor is perhaps the fastest blocking queue implementation
in the planet.
● Boasts a speed of 100K events per second (10 nanoseconds per event)
● Main difference from ArrayBlockingQueue is that the Disruptor uses spin
retries. Spin retries prevent the threads from doing lock, park, and
release immediately when there is no work to do, hence saving CPU
cycles.
● Spin retries are slower when your input is slow (does more work).
● Disruptor is faster than the ArrayBlockingQueue only at super high
throughputs (100K per second). At slower throughputs, the Disruptor is
the same speed or slower than the ArrayBlockingQueue.
● I implemented an AtomicBlockingQueue that does something similar, and
is slightly faster than the Disruptor, but difference is hardly noticeable.
● Conclusion: Your application can hardly catch up with these speeds, so
using the ArrayBlockingQueue and LinkedBlockingQueue should be your
best options!
Concurrent Utilities
4. Atomic Variables
Package: Those that I have never used:
java.util.concurrent.atomic AtomicIntegerArray
AtomicLongArray
Utilities to provide atomic AtomicMarkableReference
updates to variables without the AtomicReference
overhead of synchronization.
AtomicReferenceArray
AtomicStampedReference
Most commonly used:
AtomicBoolean
AtomicInteger
AtomicLong
Concurrent Utilities
What is CAS?
● Atomic variables work using a principle/algorithm
called Compare-And-Set (CAS).
● CAS is supported at the machine instruction level.
Hence it is very fast.
The basic idea is like this:
1. Get the expected value (usually current value)
2. Get the update value (usually expected value + delta)
3. Check that the variable currently has the expected
value
4. Set the variable to the update value
5. Check that the variable now has the update value
6. If true, return success. Else retry from 1.
Concurrent Utilities
CAS Algorithm
The getAndIncrement() method in AtomicInteger gives the algorithm for this:
The native instruction to perform CAS guarantees that the operation is atomic
(all or nothing).
Concurrent Utilities
5. Other Stuff
There are a few other small utilities that I think are quite useful:
CountDownLatch
● Allows one or more threads to wait at a certain point until countdown is
completed.
● Any thread that does the countdown will not wait at the point of
countdown. This is the difference between the CountDownLatch and the
CyclicBarrier.
CyclicBarrier
● Allows two or more threads to wait at a certain point until all threads
have arrived at the wait point. Then all threads will resume execution at
the same time.
● Useful when you want to sync up all threads to arrive at a certain point
in the code before proceeding further.
Concurrent Utilities
5. Other Stuff (2)
Phaser (new in Java 7)
● Combines the functionality of both the
CountDownLatch and the CyclicBarrier.
● With the new Phaser, you will not need to use any of
the CountDownLatch and the CyclicBarrier anymore.
TimeUnit
● Time unit conversions utility
Concurrent Utilities
5. Other Stuff - ThreadLocal
java.lang.ThreadLocal
● Not part of the concurrent package, but
closely-related to concurrency.
● Implementation is super-fast using a rehash lookup
hashtable (not linked list of entries).
● Saves programmers from needing to extend
java.lang.Thread to add additional attributes to each
thread.
● Entries for dead threads will be cleaned up by GC
automatically.
Concurrent Utilities
5. Other Stuff - ThreadLocal Sample
● Don't add "synchronized" on method "initialValue")
● @Override is optional
SimpleBarrierExample.java:
import java.util.concurrent.Phaser;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
}
End of Part II. Concurrent Utilities
We are done with a brief overview of what is
available out of the box from the
java.util.concurrent package.