Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
    }   
}
like image 496
user590444 Avatar asked Jun 17 '26 16:06

user590444


1 Answers

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.

like image 128
assylias Avatar answered Jun 19 '26 05:06

assylias



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!