Groovy singleton thread safe

Does @Singleton annotation in Groovy make a singleton thread-safe?

If it's not, which is the easiest way to create a thread-safe singleton using Groovy?

Upvotes: 3

Views: 1723

Answers (1)

cfrick
cfrick

Reputation: 37043

The actual class used as the instance is not threadsafe (unless you make it). There are lots of examples around here (e.g. Are final static variables thread safe in Java?: a static final HashMap is used there, which is not threadsafe)

The creation of the singleton using groovys @Singleton annotation is thread-safe (and you should rely on that).

The docs show two versions, of the corresponding Java code generated by the transformation:

  1. Here is the regular version @Singleton, which results in a static final variable, which again is threadsafe in java:

    public class T {
        public static final T instance = new T();
        private T() {}
    }
    
  2. For the lazy version (@Singleton(lazy=true)) Double-checked locking is 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, here is a gist with a simple class and the disassembled code

Upvotes: 5

Related Questions