Path: csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!aioe.org!eternal-september.org!feeder.eternal-september.org!.POSTED!not-for-mail From: Eric Sosman Newsgroups: comp.lang.java.programmer Subject: Re: Singleton Pattern Date: Sat, 13 Aug 2011 20:56:12 -0400 Organization: A noiseless patient Spider Lines: 58 Message-ID: References: <3be6e6cf-fa32-4503-9457-b0a1caef8f29@w11g2000vbp.googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Injection-Date: Sun, 14 Aug 2011 00:56:49 +0000 (UTC) Injection-Info: mx04.eternal-september.org; posting-host="f8igmItKsWs6nM5YanFxAA"; logging-data="26367"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/v6qizDYsjBWJArXvE+ZVc" User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:5.0) Gecko/20110624 Thunderbird/5.0 In-Reply-To: <3be6e6cf-fa32-4503-9457-b0a1caef8f29@w11g2000vbp.googlegroups.com> Cancel-Lock: sha1:+hZRAHsEAOl/NdongiRKQ+gsTmU= Xref: x330-a1.tempe.blueboxinc.net comp.lang.java.programmer:7096 On 8/13/2011 4:56 PM, vbhavsar@gmail.com wrote: > People have been coming up with creative solutions to lazily implement > the singleton pattern in a thread-safe way. We have seen things like > double-checked locking and creating instance via a single-elemnt enum > type. > > I have thought of yet another way to implement this in a lazy and > thread-safe way. I haven't seen this proposed anywhere and it seems to > work unless I am missing something. Here it goes: > > public class Singleton { > > private static Singleton _instance; > private Singleton(){} > > private synchronized static void createInstance(){ > _instance = new Singleton(); > } > > public static Singleton getInstance(){ > if (_instance == null){ > createInstance(); > } > return _instance; > } > } > > > The synchronized createInstance() method would eliminate the need to > do double-checked locking and the synchronization would happen only > when multiple threads call getInstance() before _instance has been > instantiated. > > Anyone see any issues with this? Yes. T1: if (_instance == null) "Aha! It's null! Let's go make one." ** context switch ** T2: if (_instance == null) "Aha! It's null! Let's go make one." T2: _instance = createInstance(); // instance #1 ** context switch ** T1: _instance = createInstance(); // instance #2 ... and the two threads go merrily on their way with references to two different Singleton instances. With N threads, you could get as many as N distinct instances. -- Eric Sosman esosman@ieee-dot-org.invalid