By alarmnummer
via pveentjer.wordpress.com
Published: Mar 19 2007 / 01:44
Immutability is a great way to reduce concurrency control related complexity. But making properly constructed immutable classes, it not without problems. This blogpost explains what can go wrong with not properly constructed immutable classes.
Comments
daniel replied ago:
Ok, in a highly theoretical situation you could indeed have a thread trying to access data within an instance of MyInt before it was in fact fully constructed. But consider for a moment the requirements for something like that to happen:
public class ThreadTest {
static MyInt var;
class Thread1 extends Thread {
public void run() {
var = new MyInt(3);
}
}
public static void main(String[] args) {
Thread thread1 = new Thread1();
thread1.start();
System.out.println(var.getValue()); // theoretical failure here
}
}
Think for a moment about exactly what would have to happen for the invocation to fail in the way described. The VM would have to reorder the thread spawn and the run() invocation ahead of everything else. Then (without losing its preeminence) it would have to reorder the object creation (and assignment) before the internal variable assignment. That's quite a trick.
On top of that, there's a much bigger problem with the code I gave. Basically, there's no guaranty that the thread initialization code will run completely before we try to access the variable on the next line. In fact, we'd probably get a NullPointerException fairly often with this code.
In fact, having sat down and given this some thought now, I can't think of a single way in which you could trigger the reordering problem described without triggering a null pointer exception far more often.
bloid replied ago:
I may be completely wrong here, but isn't that what java.util.concurrent.FutureTask is for?
Lowell Heddings replied ago:
Isn't there an implementation of a lock() function or something?
Voters For This Link (12)
Voters Against This Link (0)