Solving Lazy Initialization and double checked locking problem

D

David

I know this thread is getting old but I had an interview with someone who
claims to have solved the DCL paradox. When I look at this I cannot help
but think that if it were that simple many people would have solved it by
now.

Here's the code. Sorry, I don't know how that last postnig got munged.
 
M

Mark Thornton

David said:
Here's the code. Sorry, I don't know how that last postnig got munged.

That is also broken. A thread that obtains a reference to the singleton
without synchronization may see an incompletely intialised instance. (At
least it would if there was anything in an instance of Singleton to
initialise).

Mark Thornton
 
D

David

That is also broken. A thread that obtains a reference to the singleton
without synchronization may see an incompletely intialised instance. (At
least it would if there was anything in an instance of Singleton to
initialise).

Mark Thornton

Thanks. I pronounced it broken too during the interview. However, I don't
have enough knowledge of the JMM to define exactly why.
 
X

xarax

David said:
Thanks. I pronounced it broken too during the interview. However, I don't
have enough knowledge of the JMM to define exactly why.

The reason is that the Java memory model allows the target
field "_instance" to receive the reference to the newly
created instance *before* the instance has been fully
constructed. All threads that look at the field "_instance"
must be synchronized *before* peeking at the field. The
issue can be ameliorated somewhat by declaring the field
as "volatile", but that still violates the memory model
specification, even though it may work on most modern
hardware platforms.

For now, just bite the bullet and synchronize the access.
If the field is truly a singleton, then each thread can
save a copy of the value elsewhere for quicker local
access.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,778
Messages
2,569,605
Members
45,238
Latest member
Top CryptoPodcasts

Latest Threads

Top