Link Details

Link 16346 thumbnail
User 160967 avatar

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.
  • 12
  • 0
  • 1052
  • 333

Comments

Add your comment
User 107114 avatar

daniel replied ago:

1 votes Vote down Vote up Reply

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.

User 111696 avatar

bloid replied ago:

0 votes Vote down Vote up Reply

I may be completely wrong here, but isn't that what java.util.concurrent.FutureTask is for?

User 205047 avatar

Lowell Heddings replied ago:

0 votes Vote down Vote up Reply

Isn't there an implementation of a lock() function or something?

Add your comment


Html tags not supported. Reply is editable for 5 minutes. Use [code lang="java|ruby|sql|css|xml"][/code] to post code snippets.

Voters For This Link (12)



Voters Against This Link (0)