Java中的构造方法同步 [英] Constructor synchronization in Java

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

问题描述

有人在某处告诉我,Java构造函数是同步的,所以它不能在构建过程中同时访问,我想知道:如果我有一个构造函数存储在地图中的对象,另一个线程从该地图检索它

Someone somewhere told me that Java constructors are synchronized so that it can't be accessed concurrently during construction, and I was wondering: if I have a constructor that stores the object in a map, and another thread retrieves it from that map before its construction is finished, will that thread block until the constructor completes?

让我用一些代码演示:

public class Test {
    private static final Map<Integer, Test> testsById =
            Collections.synchronizedMap(new HashMap<>());
    private static final AtomicInteger atomicIdGenerator = new AtomicInteger();
    private final int id;

    public Test() {
        this.id = atomicIdGenerator.getAndIncrement();
        testsById.put(this.id, this);
        // Some lengthy operation to fully initialize this object
    }

    public static Test getTestById(int id) {
        return testsById.get(id);
    }
}

假设put / get是map,所以我不会通过类似迭代的东西来获取CME,并尝试忽略其他明显的缺陷。

Assume that put/get are the only operations on the map, so I won't get CME's via something like iteration, and try to ignore other obvious flaws here.

我想知道的是,如果另一个线程构造对象,显然)试图访问该对象使用 getTestById 并调用的东西,它会阻止吗?换句话说:

What I want to know is if another thread (that's not the one constructing the object, obviously) tries to access the object using getTestById and calling something on it, will it block? In other words:

Test test = getTestById(someId);
test.doSomething(); // Does this line block until the constructor is done?

我只是想澄清构造函数同步在Java中有多远,如果这样的代码有问题。我最近看过这样的代码,而不是使用一个静态工厂方法,我想知道这是多危险(或安全)这是在多线程系统。

I'm just trying to clarify how far the constructor synchronization goes in Java and if code like this would be problematic. I've seen code like this recently that did this instead of using a static factory method, and I was wondering just how dangerous (or safe) this is in a multi-threaded system.

推荐答案


有人在某处告诉我,Java构造函数是同步的,因此无法在构建过程中同时访问

Someone somewhere told me that Java constructors are synchronized so that it can't be accessed concurrently during construction

这当然不是这样。没有暗示与构造函数的同步。多个构造函数不仅可以同时发生,而且可以通过例如在构造函数中分配一个线程,引用构建的 this 来获取并发性问题。

This is certainly not the case. There is no implied synchronization with constructors. Not only can multiple constructors happen at the same time but you can get concurrency issues by, for example, forking a thread inside of a constructor with a reference to the this being constructed.


如果我有一个构造函数将对象存储在映射中,另一个线程在构建完成之前从该映射中检索它,该线程阻塞直到构造函数完成?

if I have a constructor that stores the object in a map, and another thread retrieves it from that map before its construction is finished, will that thread block until the constructor completes?

不会。

在线程应用程序中构造函数的最大问题是,编译器在Java内存模型下具有重新排序构造函数内部的操作的权限,所以它们在(所有事情)之后发生对象引用被创建,并且构造函数完成。 final volatile 字段将被保证在构造函数完成时完全初始化,而不是其他正常字段。

The big problem with constructors in threaded applications is that the compiler has the permission, under the Java memory model, to reorder the operations inside of the constructor so they take place after (of all things) the object reference is created and the constructor finishes. final and volatile fields will be guaranteed to be fully initialized by the time the constructor finishes but not other "normal" fields.

在你的情况下,由于你把 Test 放到同步映射中, / em>继续做初始化,正如@Tim所提到的,这将允许其他线程在可能半初始化的状态下获得对象的保持。一个解决方案是使用 static 方法来创建您的对象:

In your case, since you are putting your Test into the synchronized-map and then continuing to do initialization, as @Tim mentioned, this will allow other threads to get ahold of the object in a possibly semi-initialized state. One solution would be to use a static method to create your object:

private Test() {
    this.id = atomicIdGenerator.getAndIncrement();
    // Some lengthy operation to fully initialize this object
}

public static Test createTest() {
    Test test = new Test();
    // this put to a synchronized map will force the happens-before of the Test constructor
    testsById.put(test.id, test);
    return test;
}

我的示例代码工作,因为你正在处理一个synchronized-调用 synchronized ,它确保 Test 构造函数已完成并已进行内存同步。

My example code works since you are dealing with a synchronized-map, which makes a call to synchronized which ensures that the Test constructor has completed and has been memory synchronized.

您的示例中的大问题是发生在之前保证(构造函数可能不会完成测试被放入地图)和内存同步(构造线程和获取线程可能会看到 Test 实例的不同内存)。如果你移动 put 在构造函数之外,那么都由synchronized-map处理。无论什么对象是 synchronized ,以保证构造函数在放入映射之前已经完成,并且内存已经同步。

The big problems in your example is both the "happens before" guarantee (the constructor may not finish before Test is put into the map) and memory synchronization (the constructing thread and the get-ing thread may see different memory for the Test instance). If you move the put outside of the constructor then both are handled by the synchronized-map. It doesn't matter what object it is synchronized on to guarantee that the constructor has finished before it was put into the map and the memory has been synchronized.

我相信如果你在非常上调用 testsById.put(this.id,this); 结束你的构造函数,你可能在实践中是好的,但这不是好的形式,至少需要仔细的评论/文档。如果类是子类并且初始化在 super()后的子类中完成,这将不会解决问题。我所展示的 static 解决方案是一个更好的模式。

I believe that if you called testsById.put(this.id, this); at the very end of your constructor, you may in practice be okay however this is not good form and at the least would need careful commenting/documentation. This would not solve the problem if the class was subclassed and initialization was done in the subclass after the super(). The static solution I showed is a better pattern.

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

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