MinhHoang
MinhHoang

Reputation: 711

Partially constructed object

Is this possible if an object is visible to other threads during its initialization (visible while doing initialization but not completed yet)? If yes then could you please give a simple example to backup your justification?

Upvotes: 1

Views: 2335

Answers (2)

Marko Topolnik
Marko Topolnik

Reputation: 200168

The best case in point would be the notoriously broken double-checked locking idiom. I'll extract from it only the part relevant for this argument. Take this code:

public class Holder { public static File f; }

Somewhere in Thread A you do Holder.f = new File("path"); and elsewhere in Thread B you do File xxf = Holder.f; and proceed to use it. There is no guarantee that, even if you read the reference to Holder.f, any field of the File instance will be in any defined state. You may read all nulls, (zeros, falses, depending on type), as well as any combination of non-null and null values.

Upvotes: 3

Peter Lawrey
Peter Lawrey

Reputation: 533530

This can happen in a number of ways.

  • You pass your object to another thread in the constructor, e.g. you start a thread in your constructor.
  • You pass the object to another thread but the other thread sees old, uninitialized values because the fields are not final or volatile or accessed in a locked or synchronized block. Other fields are not guarenteed to be thread safe.

Upvotes: 5

Related Questions