« When is a Singleton not a Singleton? | Main | Dynamic Extension Using Auto-Generation »


Justin Mclean

Race condidtion can require locking but not allways.

With the above code the race condition isn't actally an issue, as the newly created instance is assigned to application._singleton and as only one instance of that can exist the worse that can happen is that two objects are created but the same instance is returned from both calls.

Steps 7 and 8 would return the exactly the same instance.

Michael Long

Justin: It depends. If process B completed step 6 and then blocked, process A then has a chance to exit with its value on step 7, then B has a chance to do the same on step 8 whenever it unblocks.

That's the problem with multi-threading, you never know if the processes will run simultaneously, concurrently, or in fits and starts as threads block and unblock and the system responds to interupts, garbage collections, and so on.

Best to synchronize things so any potential bugs are zapped before they can grow into more serious problems.

Justin Mclean

Even if the above occurs the instances will still be the same as the code returns a reference to the application instance rather than a copy of it.

But yes it's probably best to put the locking in and avoid this sort of issue from potentially occuring.

The comments to this entry are closed.