groovy-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Jochen Theodorou <blackd...@gmx.org>
Subject Re: Hierarchy of singletons howto?
Date Sat, 02 Apr 2016 17:19:16 GMT
On 01.04.2016 21:38, OC wrote:
[...]
> ===
> class Foo {
>    static instance=newInstance()
> }
> class Bar extends Foo {
>    static instance=newInstance()
> }
> ===
>
> it works like a charm, only -- unlike @Singleton -- it is not lazy (and if turned to
lazy, it would not be threadsafe).

there is an easy Java trick for lazy:

class Foo {
   static getInstance() {
     return Inner.instance
   }
   private Foo(){}
   private static class Inner {
      final static instance = new Foo()
   }
}

The trick is that the inner class is only loaded if getInstance is 
called, thus you get lazy behaviour, that is even thread safe.

bye Jochen


Mime
View raw message