Re: Threads and synchronization



Peter Duniho wrote:

There's no guarantee to the compiler that "i" isn't accessed outside the constructor before the constructor completes. In fact, this particular

Really? I'm not trying to be argumentative here, just thinking about how Java actually works.

A a = new A();

There's two things that happen here. First the call to the default constructor of class A, then the assignment to the variable "a". There's no way, even in a multi-threaded application, that "a" can be accessed until it's assigned a reference. Even like this:

int i = new A().someField();

first A has to be constructed, fully, then it's field can be accessed. If this code is execute by two threads, you have two objects, not two threads accessing one object. You have the same in the first example, until a is assigned a reference, and even then if a is local then you still have two separate objects.

The only exception is of course publishing a reference to a reference to a partially constructed object, and we all know that's bad. But it's also not "normal" and I'm thinking that Java might optimize what is prescribed, and ignore what is proscribed.
.



Relevant Pages