Groovy single threaded stream safe

Is the @Singleton annotation in Groovy justified as being single-threaded, thread-safe?

If it isn't, is this the easiest way to create a thread-safe singleton using Groovy?

+3


source to share


1 answer


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 variable static 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

+3


source







All Articles