Pages 91 - 111 of “The Well-Grounded Java Developer” by Evans and Verburg.
We have provided for you a non thread-safe producer-consumer implementation:
This implementation is not thread-safe because the bounded buffer could be put in an inconsistent state. This inconsistent state will occur if either
get are interrupted in the middle of execution. In particular, if either method is interrupted between adding/removing the new value to array and updating
mNext then the buffer will lose or repeat values.
Use one of the techniques you have learned about in the above readings to make this producer-consumer thread-safe without locking it up.
Note, it is quite hard to get the bounded buffer in in inconsistent state - bragging rights go to anyone that can make a program that always and demonstrably gets into an inconsistent state.
Imagine you want to add motion blur to an image. Such an algorithm would replace any pixel value with some combination of the pixel values “to the right” of that pixel. So you can experiment with the speed you can get for this type of algorithm so we have provided a
Main.java that performs just such a computation.
The code will time itself and report how long it took to run. Your job is to make a multi-threaded version of this code that is faster than the reference implementation above.
Use one of the modern concurrency techniques described in “The Well-Grounded Java Developer” to achieve this as simply as possible.
There are a number of possible solutions. You can consider a countdown latch or you might try an executor service.