3

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?

hunch_hunch
  • 2,283
  • 1
  • 21
  • 26

1 Answers1

5

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

Community
  • 1
  • 1
cfrick
  • 35,203
  • 6
  • 56
  • 68