关于实例变量初始化的线程安全性 [英] On the thread safety of instance variable initialization

查看:101
本文介绍了关于实例变量初始化的线程安全性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到这个初始化实例变量的习惯很多

I see this idiom of initializing instance variables quite a bit

public class Test{
    private Long l = 1l;
    private MyClass mc = new MyClass();

    public Test(){}
    ...
 }

但我更喜欢

public class Test{
    private Long l;
    private MyClass mc;

    public Test(){
        l = 1l;
        mc = new MyClass();
    }
    ...
}

考虑到这些是非最终变量,2个方法是等价的还是在线程安全方面比另一个更正确?

Considering that these are non-final variables, are the 2 approaches equivalent or is one "more" correct than the other in terms of thread safety?

推荐答案

线程安全不是问题,因为这在构造阶段发生,并且两个线程不能构造相同的对象。好吧,如果你让这个从构造函数中转义,那么另一个线程可能在构造期间访问该对象,但你真的不应该这样做。功能方面,两个选项是相同的,所以即使存在线程安全问题,它们也会以相同的方式影响。

Thread safety isn't an issue because this happens at construction phase, and two threads cannot be constructing the same object. Well, if you let this escape from the constructor, it might be possible for another thread to access the object during construction, but you really shouldn't do that. Functionality-wise, the two options are the same, so even if there were thread-safety issues, they would affect both the same way.

初始化的第一个选项如果您需要进行一些无法在初始化程序中完成的计算,那么声明中的字段并不总是可行的(尽管如此,如果您在初始化程序块中执行此操作,则可以将初始化保留在构造函数之外)。但是,如果任何一种方式都可行,那么它纯粹是一种风格问题,而且我认为Java程序员并不存在明显的偏好,所以请选择适合自己的方式。

The first option, of initializing the fields at their declaration, is not always possible if you need to do some computation that cannot be done in an initializer (even then, you can keep the initialization out of the constructor if you do it in an initializer block, though). But if either way is possible, then it's purely a style issue, and I don't think there is a clear preference among Java programmers, so go with whichever seems better to you.

这篇关于关于实例变量初始化的线程安全性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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