3

For example -

public class Request {
    public String id; //is it visible to other threads after construction?
    public Request(String id){
        this.id= id;
    }   
}
user590444
  • 4,252
  • 8
  • 36
  • 43
  • possible duplicate of [Java Concurrency in Practice - Sample 14.12](http://stackoverflow.com/questions/10528572/java-concurrency-in-practice-sample-14-12) – assylias Jul 18 '13 at 11:47
  • Due to JVM optimization, you can never assume that operations are executed in the order they are written, unless it matters for the same thread. So when you call the constructor and then pass a reference to the resulting object to another thread, the JVM might not actually write the value of foo.bar before it is needed within the same thread. That means that in a multithreaded environment, the getBar method could be called before the value in the constructor was written to it. – user590444 Jul 23 '13 at 09:38

1 Answers1

3

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.

Community
  • 1
  • 1
assylias
  • 321,522
  • 82
  • 660
  • 783