When playing around with multithreading, I could observe some unexpected but serious performance issues related to AtomicLong (and classes using it, such as java.util.Random), for which I currently have no explanation. However, I created a minimalistic example, which basically consists of two classes: a class "Container", which keeps a reference to a volatile variable, and a class "DemoThread", which operates on an instance of "Container" during thread execution. Note that the references to "Container" and the volatile long are private, and never shared between threads (I know that there's no need to use volatile here, it's just for demonstration purposes) - thus, multiple instances of "DemoThread" should run perfectly parallel on a multiprocessor machine, but for some reason, they do not (Complete example is at the bottom of this post).
private static class Container {
private volatile long value;
public long getValue() {
return value;
}
public final void set(long newValue) {
value = newValue;
}
}
private static class DemoThread extends Thread {
private Container variable;
public void prepare() {
this.variable = new Container();
}
public void run() {
for(int j = 0; j < 10000000; j++) {
variable.set(variable.getValue() + System.nanoTime());
}
}
}
During my test, I repeatedly create 4 DemoThreads, which are then started and joined. The only difference in each loop is the time when "prepare()" gets called (which is obviously required for the thread to run, as it otherwise would result in a NullPointerException):
DemoThread[] threads = new DemoThread[numberOfThreads];
for(int j = 0; j < 100; j++) {
boolean prepareAfterConstructor = j % 2 == 0;
for(int i = 0; i < threads.length; i++) {
threads[i] = new DemoThread();
if(prepareAfterConstructor) threads[i].prepare();