2014-09-24 88 views
3

Groovy中的@Singleton注释使单线程安全吗?Groovy单例线程安全

如果不是这样,那么使用Groovy创建线程安全单例最简单的方法是什么?

+1

你的意思是它使你的Thread类的所有方法安全吗? – 2014-09-24 19:10:59

回答

3

用作实例的实际类是而不是线程安全(除非您提供)。有很多的例子在这里(如Are final static variables thread safe in Java?:静态最终HashMap目前使用的是,这是不是线程安全的)

创建使用groovys @Singleton注释线程(你应该依赖于单例 )。

docs显示两个版本,通过变换生成相应的Java代码:

  1. 这里是普通版@Singleton,这会导致static final变量,而这又是线程在java中:

    public class T { 
        public static final T instance = new T(); 
        private T() {} 
    } 
    
  2. 对于lazy版本( @Singleton(lazy=true)Double-checked locking创建:

    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() 
           } 
          } 
         } 
        } 
    } 
    

仅供参考,这里是一个gist with a simple class and the disassembled code