On Thu, 2002-03-21 at 20:10, Alexey A. Efimov wrote:
> I'm answer. Even if in case of condition "if (instance == null)" - about
> this condition says article, even is instance already not null but
> memmory not allocated this no fatal happends, becose reference
> controlled by JVM, and if JVM say "The instance is not NULL" then it's
> true, and referense did not come sudenly to other value. Exactly it
> WORKS PROPERTLY - return already innitialized instance, but not tryed
> reinitilise it. I guess.
If I remember correctly, this is what could happen:
(1) Thread 1 sees that instance==null.
(2) Thread 1 synchronizes on the synchronizer.
(3) Thread 1 allocates X bytes of memory for a FileCache.
(4) Thread 1 sets instance=(pointer to the allocated memory).
(5) Thread 1 calls FileCache() constructor to initialize
the memory area that instance points to -- AFTER it has
already set the instance pointer!
(6) Thread 1 unlocks the synchronizer.
And if we have another thread, the following could happen.
(1) Thread 1 sees that instance==null.
(2) Thread 1 synchronizes on the synchronizer.
(3) Thread 1 allocates X bytes of memory for a FileCache.
(4) Thread 1 sets instance=(pointer to the allocated memory).
(4b) Thread 2 enters getInstance().
(4c) Thread 2 sees that instance!=null.
(4d) Thread 2 returns instance, a pointer to an
uninitialized memory area.
(4e) Thread 2 uses the uninitialized FileCache object and
crashes with a NullPointerException or a virtual machine
error or whatever.
(5) Thread 1 calls FileCache() constructor to initialize
the memory area that instance points to -- AFTER it has
already set the instance pointer!
(6) Thread 1 unlocks the synchronizer.
Of course this only refers to what is *guaranteed* by the Java memory
model. It could still be the case that (for example) HotSpot always
calls the constructor first and *then* sets the instance field to point
to a valid, complete FileCache instance, so that double-checked locking
is always safe in HotSpot. But this is still not guaranteed to work in
*all* virtual machines *all* the time, if I have understood the article
correctly.
_______________________________________________
Eap-list mailing list
[EMAIL PROTECTED]
http://www.intellij.com/mailman/listinfo/eap-list