构造函数中的同步块 [英] Synchronized blocks in constructors

查看:73
本文介绍了构造函数中的同步块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的静态变量的类

I have a class with a static var like so

private static Object sMyStaticVar;

如果我想在构造函数中为这个var赋值,我有这样的代码

if i want to assign a value to this var in the constructor I have code like

if(sMyStaticVar == null) sMyStaticVar = new CustomObject(someRuntimeObject);

其中 someRuntimeObject 是一个在我的类加载时不可用的对象,因此阻止我像下面这样声明我的静态变量

where someRuntimeObject is an object that is not available at the time my class is loaded and therefore prevents me from declaring my static var like the below

private static Object sMyStaticVar = new CustomObject(someRuntimeObject);

我的问题是,在构造函数线程中初始化静态 var 对象是否安全?我的直觉告诉我它不是,我应该使用非运行时类类型作为锁进行同步,如下所示

my question is, is the initialization of the static var object in the constructor thread safe? My instincts tell me its not and i should synchronise using the non-runtime class type as the lock, like the below

synchronized(MyClass.class)
{
    if(sMyStaticVar == null) sMyStaticVar = new CustomObject(someRuntimeObject);
}

(相对于从 getClass() 获得的 runTime 类型)

(as opposed to the runTime type obtained from getClass())

但由于我的直觉通常是错误的,如果有人能为我阐明这一点,我将不胜感激!

but as my instincts are usually wrong I would be grateful if anyone could shed some light on this for me!

推荐答案

如果它是静态的,则不应在构造函数中分配它.制作一个静态初始化方法来执行public static synchronized void initialize(someRuntimeObject).

If it is static, you should not assign it in the constructor. Make a static initializer method that does that public static synchronized void initialize(someRuntimeObject).

注意 synchronized 关键字:它与 MyClass.class

Note the synchronized keyword: it is is the same as synchronizing on MyClass.class

这篇关于构造函数中的同步块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆