gpt4 book ai didi

java - Java中的构造函数同步

转载 作者:IT老高 更新时间:2023-10-28 21:04:35 28 4
gpt4 key购买 nike

有人告诉我Java构造函数是同步的,因此在构造过程中不能同时访问它,我想知道:如果我有一个将对象存储在映射中的构造函数,并且另一个线程从该映射中检索它在其构造完成之前,该线程会阻塞直到构造函数完成吗?

让我用一些代码来演示一下:

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,并尝试忽略此处的其他明显缺陷。

我想知道的是,如果另一个线程(显然不是构造对象的线程)尝试使用 getTestById 访问该对象并对其进行调用,它会阻塞吗?换句话说:

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

我只是想澄清一下构造函数同步在 Java 中能走多远,以及这样的代码是否会出现问题。我最近看到了这样的代码,而不是使用静态工厂方法,我想知道这在多线程系统中有多危险(或安全)。

最佳答案

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

当然不是这样。与构造函数没有隐含的同步。不仅可以同时发生多个构造函数,而且还可以通过例如在构造函数内部 fork 一个线程并引用正在构造的 this 来解决并发问题。

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 字段将保证在构造函数完成时完全初始化,但不会保证其他“正常”字段。

在您的情况下,由于您将 Test 放入同步映射中,并且 然后 继续进行初始化,正如@Tim 所提到的,这将允许其他线程获取可能处于半初始化状态的对象。一种解决方案是使用 static 方法来创建您的对象:

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 构造函数已完成并已与内存同步.

您的示例中的大问题是“发生之前”保证(构造函数可能在 Test 放入 map 之前无法完成)和内存同步(构造线程和获取Test 实例的线程可能会看到不同的内存)。如果将 put 移到构造函数之外,则两者都由同步映射处理。不管它是在哪个对象上同步,都可以保证构造函数在放入映射之前已经完成并且内存已经同步。

我相信,如果您在构造函数的 very 末尾调用 testsById.put(this.id, this);,那么实际上您可能没问题,但这不是好的形式,至少需要仔细的评论/文档。如果类是子类并且在 super() 之后在子类中完成初始化,这不会解决问题。我展示的 static 解决方案是更好的模式。

关于java - Java中的构造函数同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12611366/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com