java - why is Immutable Objects safe in Double-Checked Locking? -
java - why is Immutable Objects safe in Double-Checked Locking? -
at bottom of http://www.cs.umd.edu/~pugh/java/memorymodel/doublecheckedlocking.html, says:
double-checked locking immutable objects
if helper immutable object, such of fields of helper final, double-checked locking work without having utilize volatile fields. thought reference immutable object (such string or integer) should behave in much same way int or float; reading , writing references immutable objects atomic.
the sample , explanation of mutable 1 follows:
// broken multithreaded version // "double-checked locking" idiom class foo { private helper helper = null; public helper gethelper() { if (helper == null) synchronized(this) { if (helper == null) helper = new helper(); } homecoming helper; } // other functions , members... }
the first reason doesn't work
the obvious reason doesn't work writes initialize helper object , write helper field can done or perceived out of order. thus, thread invokes gethelper() see non-null reference helper object, see default values fields of helper object, rather values set in constructor.
if compiler inlines phone call constructor, writes initialize object , write helper field can freely reordered if compiler can prove constructor cannot throw exception or perform synchronization.
even if compiler not reorder writes, on multiprocessor processor or memory scheme may reorder writes, perceived thread running on processor.
my question is: why immutable class does't have problem? cannot see relation of reorder whether class mutable.
thanks
the reason why code "broken" usual objects helper
non null point object has not been completely initialised yet explained in quote.
however if helper class immutable, meaning fields final, the java memory model guarantees safely published if object made available through info race (which case in example):
final
fields allow programmers implement thread-safe immutable objects without synchronization. a thread-safe immutable object seen immutable threads, if info race used pass references immutable object between threads. can provide safety guarantees against misuse of immutable class wrong or malicious code. final
fields must used correctly provide guarantee of immutability.
java thread-safety immutability double-checked-locking
Comments
Post a Comment