Path: csiph.com!weretis.net!feeder4.news.weretis.net!newsreader4.netcologne.de!news.netcologne.de!.POSTED.xdsl-87-78-157-110.netcologne.de!not-for-mail From: Patrick Roemer Newsgroups: comp.lang.java.programmer Subject: Re: Guice vs plain singleton Date: Wed, 20 Dec 2017 17:53:28 +0100 Organization: news.netcologne.de Distribution: world Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: 7bit Injection-Date: Wed, 20 Dec 2017 16:53:28 +0000 (UTC) Injection-Info: newsreader4.netcologne.de; posting-host="xdsl-87-78-157-110.netcologne.de:87.78.157.110"; logging-data="3948"; mail-complaints-to="abuse@netcologne.de" User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.24) Gecko/20100411 Thunderbird/2.0.0.24 Mnenhy/0.7.6.0 In-Reply-To: Content-Language: en-US Xref: csiph.com comp.lang.java.programmer:37898 Responding to Victor Porton: > What should I prefer for creating a singleton object with "heavy" (requiring > much CPU time or like this) constructor: > > - Guice @Singleton injector > > or > > - plain hand-made singleton like > > static Type instance; ... if(instance==null) ... > > ? public class Singleton { public final static Singleton INSTANCE = new Singleton(); private Singleton() { // expensive setup } public Foo service(Bar bar) { // ... } } The instance will only be created when the class is initialized, and that's only if a client accesses the field or calls the method on this class (which requires having access to the instance first). So as long as you don't provide any unrelated functionality on this class that might unadvertently trigger class initialization, you'll get lazy on demand initialization for free with this pattern, without having to worry about synchronization issues or involving 3rd party code. I'd be reluctant to use a singleton at all in the first place, though. Best regards, Patrick