Singletons was: Eliminate silent dependencies

Jaroslav Tulach jaroslav.tulach at oracle.com
Wed Feb 22 08:00:09 PST 2012


>## 22. 2. 2012 12:34:31 ##<
> On 20/02/2012 09:49, Jaroslav Tulach wrote:
> > Services often act like singletons. Properly used singletons need to be
> > "inherently initialized" (discussed at [2] and [3]).
> 
> I think singletons is a good topic to bring up. An interesting question
> is whether this should be something that the module system or
> ServiceLoader knows about or whether it's the user of SeviceLoader that
> enforces it (possible as a side effect of caching).

The typical implementation of (injectable) singleton via ServiceLoader is 
shown at http://wiki.apidesign.org/wiki/Injectable_Singleton#Initialize
If this pattern is followed, the only thing that the module system is supposed 
to do is to enable providers of such service. E.g. using

requires (optional) service DialogDisplayer

and 

provides service DialogDisplayer

in module-info files of appropriate modules would be enough.

Of course the module system can make it even easier. One could annotate the 
field with

@InjectService(fallback=Impl.class)
private static DialogDisplayer DEFAULT;

Having annotation like this or reusing for example 
http://docs.oracle.com/javase/6/docs/api/javax/annotation/Resource.html
would be more convenient. Whether usage of (injectable) singletons is typical 
and should be simplified with annotation is something I don't dare to decide.

Btw. usage of @InjectService could imply generating "requires service <type of 
the field>" into module-info.java. Usage of @InjectService with fallback would 
be equivalent to "requires optional service".
-jt



More information about the jigsaw-dev mailing list