Discover the Elegant Simplicity of JSR 166
By Nathan Tippy, OCI Senior Software Engineer
September 2006
Introduction
Concurrent or multi-threaded software is not a new technology but its importance has been accelerating. This is primarily due to the low cost of multi-core CPUs that are becoming common in even the most basic machines. This trend is expected to continue as hardware manufacturers, following Moore's law, cram greater numbers of cores onto a single die at ever lower costs.
In the past older applications have taken advantage of faster hardware for improved performance, thus extending their functional life. In the future this will be less common because CPUs are not expected to be significantly faster; instead they will be doing more in parallel.
There is no better feeling for a developer than knowing that his/her software has withstood the test of time. This is rare, of course, because technology and methodologies don't remain static but continue to progress with the relentless march of time.
It is not advisable to rewrite everything to make use of concurrent algorithms. However, finding places where it makes sense to add multi-threading and "use the right tool for the job" may greatly increase application longevity.
It would require a short course to do justice to the topic of concurrent Java development so the remainder of this brief will focus on demonstrating a few of the features with the hope that the reader will continue further study on his/her own.
Simple Demonstration of New Concurrency Package
The new concurrency package is not intended to replace the traditional use of synchronize, wait and notify etc. but it does give the developer a whole new set of design choices. Most of the new classes rely on CAS (Compare and Swap) operations, instead of the traditional synchronized block, for their excellent performance and ease of use.
CAS works just as it sounds; First it checks to ensure that the existing value is what it expects it to be and then replaces it with the new value unless it has already been changed by another thread. This sounds rather simple but it can only be done as an operation by the CPU because it must be atomic. Modern CPUs support this mechanism which has now been exposed in the JVM and used heavily in the java.util.concurrent
package.
Example 1 Part 1
Using the AtomicLong
class it's very easy to put together a simple thread safe sequence number generator. Note that no synchronization is needed because CAS is relied upon to ensure thread safety.
- package com.ociweb.concurrency.atomic.example1;
- import java.util.concurrent.atomic.*;
-
- public class SequenceNumberGenerator {
- private AtomicLong number = new AtomicLong(0);
-
- public long nextSequenceNumber() {
- return number.getAndIncrement();
- }
- }
To see CAS at work, take a look at the source code for the getAndIncrement()
method within the AtomicLong
class. You will find a loop very similar to the one below. Any thread attempting to set a new value for the AtomicLong
is required to pass in what they perceive to be the current value. If this snapshot value matches what the real current value is then the update is done but if they do not match then a new snapshot value is retrieved and the update is attempted again. When there are threads modifying the value simultaneously many attempts may be required before the value is changed successfully. This characteristic of CAS makes is less desirable under conditions where there are large numbers of threads contending on relatively few resources but in most applications this is not the case so CAS works well.
- while (true) {
- long current = get();
- long next = current + 1;
- if (compareAndSet(current, next))
- return current;
- }
Notice that when using CAS there will be less predictability as more threads attempt to modify the same object. This is because each thread grabs the value, increments it and then attempts to set the new value. Any given thread is only allowed to set the new value if its current value still matches the original value. If other threads are doing the same thing at the same time this becomes less likely. For most cases this does not cause any performance issues unless a large number of threads is used.
Example 1 Part 2
A simple Runnable
that asks for the next number until it reaches a predefined limit will be used to demonstrate the number generator. It's never a good practice to kill a thread. InsteadRunnable
s should be designed to exit on their own after receiving some sort of predefined message or flag. Each thread is responsible for shutting down on there own when the work is complete. This is made possible by passing in the sequenceLimit
to each Runnable
so each thread can compare it with the current sequence number to determine when all the numbers have been generated.
- package com.ociweb.concurrency.atomic.example1;
-
- public class SequenceRunnable implements Runnable {
- private final int id;
- private final SequenceNumberGenerator generator;
- private final long sequenceLimit;
-
- protected SequenceRunnable(int id,
- SequenceNumberGenerator generator,
- long sequenceLimit) {
- this.id = id;
- this.generator = generator;
- this.sequenceLimit = sequenceLimit;
- }
-
- public void run(){
-
- boolean workToDo = true;
-
- while (workToDo) {
- long sequenceNumber =
- generator.nextSequenceNumber();
-
- workToDo = (sequenceNumber<sequenceLimit);
-
- System.out.println("Thread:"+id+
- "SequenceNumber:"+sequenceNumber);
-
- }
- }
- }
Example 1 Part 3
For this example the newFixedThreadPool
builder method on the Executor
class is used to create an Executor
instance which will maintain a fixed number of threads. The Executor
class supports many thread creation strategies and can greatly simplify the management of threads. Note that the example also makes use of the availableProcessors()
method which returns how many processors are available for use by the JVM at that moment. This method may return 1 if the example is run on a single processor machine. If this is the case the threadCount
is changed to 2 in order to perform a more meaningful demonstration.
- package com.ociweb.concurrency.atomic.example1;
-
- import java.util.concurrent.Executor;
- import java.util.concurrent.Executors;
-
- public class SequenceNumberDemo {
-
- private static final int SEQUENCE_LIMIT = 30;
- private final SequenceNumberGenerator numberGenerator;
- private final int threadCount;
- private final long sequenceLimit;
- private final Executor executor;
-
- public SequenceNumberDemo(int threads,
- long sequenceLimit) {
-
- this.threadCount = threads;
- this.sequenceLimit = sequenceLimit;
- this.numberGenerator = new SequenceNumberGenerator();
- this.executor = Executors.newFixedThreadPool(threads);
- };
-
- public static void main(String [] args) {
- int threadCount=
- Runtime.getRuntime().availableProcessors();
-
- if (threadCount<2) {
- System.out.println("get a real machine");
- threadCount=2;
- }
-
- SequenceNumberDemo app =
- new SequenceNumberDemo(threadCount,
- SEQUENCE_LIMIT);
- app.generateSequences();
- }
-
- private void generateSequences() {
-
- for (int id=0; id<threadCount; id++) {
- Runnable runMeSoon = new SequenceRunnable(id,
- numberGenerator,
- sequenceLimit);
- executor.execute(runMeSoon);
- }
- }
- }
How to verify the results of our SequenceNumberGenerator
After implementing a sequence number generator example how can one go about verifying that it is really doing what is expected? Each sequence number must be verified to ensure it is only used once and if an error is detected there must be a clean way to exit quickly.
Example 2 Part 1
Adding a simple jumpTo
method will let the application exit quickly by passing in the sequenceLimit
. The example will be simpler because no extra logic will be needed to handle the early exit condition. When an error is detected by a thread it will use this new method to set the sequenceNumber
to the last number it expects to generate. Once this is done it will be detected by all the other threads and they will end on their own because it will appear to them that all the numbers have been generated.
- package com.ociweb.concurrency.atomic.example2;
- import java.util.concurrent.atomic.*;
-
- public class SequenceNumberGenerator {
- private AtomicLong number = new AtomicLong(0);
-
- public long nextSequenceNumber() {
- return number.getAndIncrement();
- }
-
- public void jumpToSequenceNumber(long newValue) {
- number.set(newValue);
- }
- }
Example 2 Part 2
In order to put the number generator to a more strenuous test a countDownLatch
was added. The countDownLatch
will force every thread to wait until the count goes down to zero. Once all of the threads have been initialized they will all be released to retrieve sequence numbers at the same time.
Using a List
of the same length as the sequenceLimit
provides an easy way to ensure no number is used twice. The List
's set method will return the previous value for the index in question. If the value returned by the set call is not null then the sequence number has already been used which indicates that something has gone wrong.
If any errors are detected the generators position will be set to the sequenceLimit
with the new jumpToSequenceNumber
method. In production applications it may be inappropriate to change the sequence number in this way so one may consider adding a separate isDone
boolean in that case. Regardless of how this gets implemented it's important that the threads exit on their own. Never call stop()
on a running thread and don't interrupt one unless it's interrupt policy is well understood.
- package com.ociweb.concurrency.atomic.example2;
-
- import java.util.List;
- import java.util.concurrent.CountDownLatch;
-
- public class SequenceRunnable implements Runnable {
- private final int id;
- private final SequenceNumberGenerator generator;
- private final long sequenceLimit;
- private final CountDownLatch latch;
- private final List<Integer> sequenceArray;
-
- protected SequenceRunnable(int id,
- SequenceNumberGenerator generator,
- long sequenceLimit,
- CountDownLatch latch,
- List<Integer> sequenceArray) {
- this.id = id;
- this.generator = generator;
- this.sequenceLimit = sequenceLimit;
- this.latch = latch;
- this.sequenceArray = sequenceArray;
- }
-
- public void run(){
-
- try {
- latch.countDown();
- latch.await();
- } catch (InterruptedException e) {
- e.printStackTrace();
-
- //be sure to stop the other threads
- generator.jumpToSequenceNumber(sequenceLimit);
-
- return;
- }
-
- long sequenceNumber = generator.nextSequenceNumber();
- for(;sequenceNumber<sequenceLimit;
- sequenceNumber = generator.nextSequenceNumber()) {
-
- //check if number is valid
- if (null!=sequenceArray.set((int)sequenceNumber,id)) {
- System.out.println("Thread:"+id+
- " found sequenceNumber "+sequenceNumber+
- " was already used.");
-
- //be sure to stop all the other threads
- generator.jumpToSequenceNumber(sequenceLimit);
- }
-
- //do work here
- System.out.println("Thread:"+id+
- " SequenceNumber:"+sequenceNumber);
-
- //uncomment this 'train wreck' to test that the threads exit cleanly
-
- //if ((id==sequenceArray.get(0))&&(sequenceNumber>5))
- //generator.jumpToSequenceNumber(5);
-
- }
- }
- }
Example 2 Part 3
Added latch
and sequenceArray
to support the new functionality of the SequenceRunnable
class.
- package com.ociweb.concurrency.atomic.example2;
-
- import java.util.Arrays;
- import java.util.List;
- import java.util.concurrent.CountDownLatch;
- import java.util.concurrent.Executor;
- import java.util.concurrent.Executors;
-
- public class SequenceNumberDemo {
-
- private static final int SEQUENCE_LIMIT = 30;
-
- private final SequenceNumberGenerator numberGenerator;
- private final int threadCount;
- private final long sequenceLimit;
- private final Executor executor;
-
- private final CountDownLatch latch;
- private final List<Integer> sequenceArray;
-
-
- public SequenceNumberDemo(int threads, long sequenceLimit) {
-
- this.threadCount = threads;
- this.sequenceLimit = sequenceLimit;
- this.numberGenerator = new SequenceNumberGenerator();
- this.executor = Executors.newFixedThreadPool(threads);
-
- this.latch = new CountDownLatch(threads);
- this.sequenceArray = Arrays.asList(new Integer[(int)sequenceLimit]);
-
- };
-
- public static void main(String [] args) {
- int threadCount=Runtime.getRuntime().availableProcessors();
- if (threadCount<2) {
- System.out.println("get a real machine");
- threadCount=2;
- }
-
- SequenceNumberDemo app =
- new SequenceNumberDemo(threadCount,SEQUENCE_LIMIT);
- app.generateSequences();
- }
-
- private void generateSequences() {
-
- for (int id=0; id<threadCount; id++) {
- Runnable runMeSoon = new SequenceRunnable(id,
- numberGenerator,
- sequenceLimit,
- latch,
- sequenceArray);
- executor.execute(runMeSoon);
- }
-
- }
- }
How to monitor our SequenceNumberGenerator
Some better monitoring of the sequence numbers and threads can be done now that all the number/thread pairs are being recorded. Using the sequenceList
data the text output is enhanced to show which sequence numbers were retrieved by each thread.
Example 3 Part 1
Running the previous examples it may become apparent that one thread will often monopolize all the time and it gets the majority of the sequence numbers. To help limit this problem the CountDownLatch
has been removed and replaced with a CyclicBarrier
. The CyclicBarrier
does the same thing as a CountDownLatch
but it can be used multiple times. This can come in very handy when threads need to be controlled more tightly such as in particle or life simulations.
Notice that this class gets an iterator from the sequenceArray
and walks down it without synchronization while other threads may be modifying the list. This is not a safe assumption for List
s but it will work in this example because the CopyOnWriteArrayList
class is used in the SequenceNumberDemo
class. It is left to the reader to put this to the test by passing in other List
implementations.
- package com.ociweb.concurrency.atomic.example3;
-
- import java.util.Iterator;
- import java.util.List;
- import java.util.concurrent.BrokenBarrierException;
- import java.util.concurrent.CountDownLatch;
- import java.util.concurrent.CyclicBarrier;
-
- public class SequenceRunnable implements Runnable {
- private static final int WAIT_ON_OTHERS_COUNT = 10;
- private final int id;
- private final SequenceNumberGenerator generator;
- private final long sequenceLimit;
- private final CyclicBarrier latch;
- private final List<Integer> sequenceArray;
-
- protected SequenceRunnable(int id,
- SequenceNumberGenerator generator,
- long sequenceLimit,
- CyclicBarrier latch,
- List<Integer> sequenceArray) {
- this.id = id;
- this.generator = generator;
- this.sequenceLimit = sequenceLimit;
- this.latch = latch;
- this.sequenceArray = sequenceArray;
- }
-
- public void run(){
-
- try {
- latch.await();
- } catch (Exception e) {
-
- e.printStackTrace();
- //be sure to stop the other threads
- generator.jumpToSequenceNumber(sequenceLimit);
- return;
- }
-
- int count=0;
- long sequenceNumber = generator.nextSequenceNumber();
- for(;sequenceNumber<sequenceLimit;
- sequenceNumber = generator.nextSequenceNumber()) {
-
- //check if number is valid
- if (null!=sequenceArray.set((int)sequenceNumber,id)) {
- System.out.println("Thread:"+id+
- " found sequenceNumber "+sequenceNumber+
- " was already used.");
-
- //be sure to stop all the other threads
- generator.jumpToSequenceNumber(sequenceLimit);
- }
-
- //System.out.println("Thread:"+id+
- // " SequenceNumber:"+sequenceNumber);
-
- //print sequence list without sync!
- Iterator<Integer> verificationIterator =
- sequenceArray.iterator();
-
- StringBuffer output = new StringBuffer();
- output.append("id:").append(id).append(' ');
- int pos=0;
- while (verificationIterator.hasNext()) {
- Integer currentId = verificationIterator.next();
-
- //only add the sequence numbers that belong to me.
- if ((null != currentId) && (id == currentId)){
- output.append(pos).append(' ');
- }
-
- pos++;
- }
- System.out.println(output);
-
- //wait if you are getting ahead of the others
- if (++count%WAIT_ON_OTHERS_COUNT==0){
- try {
- latch.await();
-
- } catch (Exception e) {
-
- e.printStackTrace();
- //be sure to stop the other threads
- generator.jumpToSequenceNumber(sequenceLimit);
- return;
-
- }
- }
- }
- }
- }
Example 3 Part 2
The latch has been changed to a CyclicBarrier
and the sequenceArray
is now a CopyOnWriteArrayList
. The CyclicBarrier
has already been discussed so no need to repeat it here. The CopyOnWriteArrayList
does what the name implies. Every write or update causes a new copy of the internal array to be created. This enables any array that backs up an iterator to remain unchanged until the iterator completes. The consequence of this is that an iterator could have old data but this is not a problem for this particular example.
A THREAD_COUNT_MULTIPLIER
constant has also been added so the thread count can be modified for better demos.
- package com.ociweb.concurrency.atomic.example3;
-
- import java.util.List;
- import java.util.concurrent.BrokenBarrierException;
- import java.util.concurrent.ConcurrentHashMap;
- import java.util.concurrent.CopyOnWriteArrayList;
- import java.util.concurrent.CountDownLatch;
- import java.util.concurrent.CyclicBarrier;
- import java.util.concurrent.Executor;
- import java.util.concurrent.Executors;
-
- public class SequenceNumberDemo {
-
- private static final int THREAD_COUNT_MULTIPLIER = 2;
- private static final int SEQUENCE_LIMIT = 30;
-
- private final SequenceNumberGenerator numberGenerator;
- private final int threadCount;
- private final long sequenceLimit;
- private final Executor executor;
-
- private final CyclicBarrier latch;
- private final List<Integer> sequenceArray;
-
-
- public SequenceNumberDemo(int threads, long sequenceLimit) {
-
- this.threadCount = threads;
- this.sequenceLimit = sequenceLimit;
- this.numberGenerator = new SequenceNumberGenerator();
- this.executor = Executors.newFixedThreadPool(threads);
-
- this.latch = new CyclicBarrier(threads);
-
- this.sequenceArray =
- new CopyOnWriteArrayList<Integer>(
- new Integer[(int)sequenceLimit]);
- };
-
- public static void main(String [] args) {
- int threadCount=Runtime.getRuntime().availableProcessors();
- if (threadCount<2) {
- System.out.println("get a real machine");
- threadCount=2;
- }
-
- SequenceNumberDemo app =
- new SequenceNumberDemo(threadCount*
- THREAD_COUNT_MULTIPLIER,SEQUENCE_LIMIT);
-
- app.generateSequences();
- }
-
- private void generateSequences() {
-
- for (int id=0; id<threadCount; id++) {
- Runnable runMeSoon = new SequenceRunnable(id,
- numberGenerator,
- sequenceLimit,
- latch,
- sequenceArray);
- executor.execute(runMeSoon);
- }
- }
- }
Conclusion
As a further exercise it is left to the reader to add a BlockingQueue
to accept the rapidly generated messages before they are sent to the output stream. This is great pattern to follow whenever there is a source producing more work than one consumer can handle.
There are many more features of the concurrency package that are worth investigation. They are very powerful and can often prevent one from reinventing the wheel.
References
- [1] Book
Java Concurrency in Practice, Brian Goetz - [2] Going atomic
http://www-128.ibm.com/developerworks/java/library/j-jtp11234/ - [3] Introduction to nonblocking algorithms
http://www-128.ibm.com/developerworks/java/library/j-jtp04186/ - [4] The Free Lunch Is Over
http://www.gotw.ca/publications/concurrency-ddj.htm - [5] A First Look at JSR 166
http://today.java.net/pub/a/today/2004/03/01/jsr166.html - [6] Concurrency JSR-166 Interest Site
http://g.oswego.edu/dl/concurrency-interest/index.html