This lecture reviewed the built-in Java concurrency primitives and introduced some patterns that can help with using them: immutability, synchronization wrappers, and control abstractions like producer/consumer. More high-level currency abstractions, such as those in the
java.util.concurrent package, support programming that is not only thread-safe but takes explicit advantage of concurrency to increase performance and responsiveness.
There are still pitfalls around, though: I explained about race conditions and in particular data races that may cause problems in concurrent code. The abstractions described earlier can help manage these challenges, but sometimes at a performance cost. At the end I briefly walked through some intentionally racy code from the Java
String library. This is an example of a “benign” data race which improves performance and, the creators believe, does not introduce surprise behaviour.
1. Do This
Find out what the
addAndGet method on a Java
AtomicLong object does. Why is that useful?
Java 8 introduced a
LongAdder class. Find out what it does, and how it can make code faster.
2. Read this
Work on the remaining sections of the Java Concurrency Tutorial.
This is not required homework: it’s a coding exercise for those who want to try their hand at programming with Java concurrency.
Lecture 8 presented some code for one method of a
Pigeonhole class. The exercise is to take that class and fill out other methods it needs: to
check whether a pigeonhole is full or empty, and to
release the contents of a pigeonhole. You might think of others.
Then write some code that exercises concurrent pigeonholes. For example, a
PigeonFancier program that:
Has a fixed number of pigeonholes which are emptied by some dedicated pigeon-handler threads releasing pigeons after random delays;
Has a single thread which regularly puts new pigeons into empty holes;
Makes sure the pigeon stuffer doesn’t wait too long for any hole to become empty.
Reports on how heavily-loaded the pigeonholes are, or how long threads are having to wait.
You might also be able to think of other ways that explore or stress the concurrency in this.
These two books are core references for Java concurrency, with clear explanations of the facilities offered by the language and libraries, as well as discussions of when and why to use them.
Brian Goetz, Time Peierls, Joshua Block, Joseph Bowbeer, David Holmes and Doug Lea. Java Concurrency In Practice. Addison-Wesley, 2006.
The current standard reference for concurrent Java programming.
Doug Lea. Concurrent Programming in Java: Design Principles and Patterns. Second Edition. Addison-Wesley, 1999.
The original text describing many of the patterns now implemented inside