java - Does object state set in object constructor visible from all threads? -
for example -
public class request { public string id; //is visible other threads after construction? public request(string id){ this.id= id; } }
as class not thread safe , thread observe null value id after constructor has finished.
to make sure id visible threads after construction, have several possibilities:
- make field
final - make field
volatile - safely publish
requestobject.
safe publication idioms include:
- initialising instance static initialiser
- marking reference instance volatile
- marking reference instance final
- synchronizing accesses
see this other post explains importance of marking fields final guarantee thread safety of immutable objects.
Comments
Post a Comment