Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 935
Nicolás Arkhipenko Avatar asked Aug 26 '26 04:08

Nicolás Arkhipenko


1 Answers

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

like image 146
cfrick Avatar answered Aug 29 '26 00:08

cfrick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!