Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.java.programmer > #37898
| From | Patrick Roemer <sangamon@netcologne.de> |
|---|---|
| Newsgroups | comp.lang.java.programmer |
| Subject | Re: Guice vs plain singleton |
| Date | 2017-12-20 17:53 +0100 |
| Organization | news.netcologne.de |
| Message-ID | <p1e4i8$3rc$1@newsreader4.netcologne.de> (permalink) |
| References | <p1e2jv$1jmk$1@gioia.aioe.org> |
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
Back to comp.lang.java.programmer | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
Guice vs plain singleton Victor Porton <porton@narod.ru> - 2017-12-20 18:19 +0200
Re: Guice vs plain singleton Patrick Roemer <sangamon@netcologne.de> - 2017-12-20 17:53 +0100
Re: Guice vs plain singleton Daniele Futtorovic <da.futt.news@laposte.net> - 2017-12-21 13:59 +0100
Re: Guice vs plain singleton lewbloch@gmail.com - 2017-12-21 11:36 -0800
Re: Guice vs plain singleton Arne Vajhøj <arne@vajhoej.dk> - 2017-12-22 20:11 -0500
Re: Guice vs plain singleton Sebastian <nowhere@nirvana.org> - 2017-12-23 16:15 +0100
Re: Guice vs plain singleton lewbloch@gmail.com - 2017-12-23 09:54 -0800
Re: Guice vs plain singleton Arne Vajhøj <arne@vajhoej.dk> - 2017-12-23 19:27 -0500
csiph-web