Java 中的构造函数同步 [英] Constructor synchronization in Java

查看:20
本文介绍了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?

让我用一些代码来演示:

Let me demonstrate with some code:

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 是地图上唯一的操作,所以我不会通过类似迭代的方式获取 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 字段将保证在构造函数完成时完全初始化,而不是其他正常"字段.

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 fields will be guaranteed to be fully initialized by the time the constructor finishes but not other "normal" fields.

在您的情况下,由于您将 Test 放入同步映射中,然后 继续进行初始化,正如@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 forces a happens-before of Test constructor
    testsById.put(test.id, test);
    return test;
}

我的示例代码有效,因为您正在处理一个同步映射,它调用 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 被放入映射之前没有完成)和内存同步(构造线程和获取线程可能会看到 Test 实例的不同内存).如果将 put 移到构造函数之外,则两者都由同步映射处理.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天全站免登陆