java - why is Immutable Objects safe in Double-Checked Locking? -


Below this, it says:

Double-checked Locking irreversible objects

If the helper is an irreversible thing, then all the fields in Helper are final, then double check-locking will work without using unstable areas. The idea is that the context of an immutable object (such as string or integer) should behave like a similar or float; Reading and writing contexts of temporary objects are atoms.

The sample and explanation of volatility is as follows:

  // broken multithread version // "double-check locking" idiom class Foo {Private Helper Assistant = Zero; Public Helper getHelper () (if synchronized (helper == zero) {if (helpful == zero) helper = new helper ();} return assistant;} // other work and member ...}  

The first reason why it does not work

The most obvious reason for this is that 'it works that writes helper object starting and helper Writing in the field can be done out of order or is considered. Thus, a thread that meets Helper () assistant You can see a non-blank reference for the object, but instead of the values ​​set in the constructor, see the default value for the fields of the helper object.

If the compiler writes the constructor to the caller, then writes That the initialization of the object and writing the supporting fields can be freely reordered if the compiler can prove that the constructor can not throw exceptions. Can not synchronize or synchronize.

Even if the compiler does not reorder it, the processor or memory system can rearrange those instruments on a multiprocessor, just like those running on another processor Thread is considered by.

My question is why is not the problem of temporary class? I can not see any relation of rearrangement, whether the class is unstable.

Thanks

Why is the code "broken" for normal objects that it is < Code> assistant can be untrue, but that object can be pointing to the not completely started as yet your speech is explained.

However, if the helper class is immutable, which means that all its fields are final, guarantee that they are published safely, even if the object data race (which is in your case example): < / P>

The Last field also allows the programmer to apply thread-safe non-convertible objects without synchronization. Thread-safe immovable objects can be seen as unchanging by all threads, even if a data race is used to refer to an unrelated object between threads < / Strong> This can provide a guarantee of security or guarantee against misuse of an irreversible class by incorrect or malicious code. The final field must be used correctly to guarantee the accuracy.


Comments

Popular posts from this blog

java - Can't add JTree to JPanel of a JInternalFrame -

javascript - data.match(var) not working it seems -

javascript - How can I pause a jQuery .each() loop, while waiting for user input? -