Path: csiph.com!x330-a1.tempe.blueboxinc.net!newsfeed.hal-mli.net!feeder1.hal-mli.net!nx02.iad01.newshosting.com!newshosting.com!69.16.185.16.MISMATCH!npeer02.iad.highwinds-media.com!news.highwinds-media.com!feed-me.highwinds-media.com!postnews.google.com!w11g2000vbp.googlegroups.com!not-for-mail From: "vbhavsar@gmail.com" Newsgroups: comp.lang.java.programmer Subject: Singleton Pattern Date: Sat, 13 Aug 2011 13:56:34 -0700 (PDT) Organization: http://groups.google.com Lines: 33 Message-ID: <3be6e6cf-fa32-4503-9457-b0a1caef8f29@w11g2000vbp.googlegroups.com> NNTP-Posting-Host: 67.82.47.84 Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1 X-Trace: posting.google.com 1313269374 10460 127.0.0.1 (13 Aug 2011 21:02:54 GMT) X-Complaints-To: groups-abuse@google.com NNTP-Posting-Date: Sat, 13 Aug 2011 21:02:54 +0000 (UTC) Complaints-To: groups-abuse@google.com Injection-Info: w11g2000vbp.googlegroups.com; posting-host=67.82.47.84; posting-account=owoCbwkAAAApZ2tqH2muWAH9zAFnNJv9 User-Agent: G2/1.0 X-Google-Web-Client: true X-Google-Header-Order: HNKRUAELSC X-HTTP-UserAgent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.112 Safari/535.1,gzip(gfe) Xref: x330-a1.tempe.blueboxinc.net comp.lang.java.programmer:7091 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?