Groovy single threaded stream safe
The actual class used as an instance is not thread safe (unless you do this). There are many examples here (e.g. Are final static variables thread safe in Java?: It uses static final HashMap
, which is not thread safe)
creating a singleton using groovys @Singleton
annotation is thread safe (and you have to rely on it).
The docs show two versions of the corresponding Java code generated by the transformation:
-
Here is the regular version
@Singleton
that results in a variablestatic final
which is again thread safe in java:public class T { public static final T instance = new T(); private T() {} }
-
For version
lazy
(@Singleton(lazy=true)
) Double lock created :class T { private static volatile T instance private T() {} static T getInstance () { if (instance) { instance } else { synchronized(T) { if (instance) { instance } else { instance = new T () } } } } }
For reference: gist with simple class and disassembled code
source to share