user590444
user590444

Reputation: 4332

Does object state set in object constructor visible from all threads?

For example -

public class Request {
    public String id; //is it visible to other threads after construction?
    public Request(String id){
        this.id= id;
    }   
}

Upvotes: 3

Views: 442

Answers (1)

assylias
assylias

Reputation: 328785

As it is your class is not thread safe and a thread could observe a null value for id even after the constructor has finished.

To make sure id is visible to all threads after construction, you have several possibilities:

  • make the field final
  • make the field volatile
  • safely publish the Request object.

Safe publication idioms include:

  • initialising the instance from a static initialiser
  • marking the reference to the instance as volatile
  • marking the reference to the instance as final
  • synchronizing all accesses

See also this other post which explains the importance of marking fields final to guarantee the thread safety of immutable objects.

Upvotes: 3

Related Questions