Java 中的构造函数同步
有人告诉我,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 是地图上唯一的操作,所以我不会通过类似迭代的方式获取 CME,并尝试忽略此处的其他明显缺陷。
我想知道的是,如果另一个线程(显然不是构造对象的线程)尝试使用并在其上调用某些内容来访问对象,它会阻塞吗?换句话说:getTestById
Test test = getTestById(someId);
test.doSomething(); // Does this line block until the constructor is done?
我只是试图澄清构造函数同步在Java中走了多远,以及这样的代码是否会有问题。我最近看到像这样的代码,它这样做而不是使用静态工厂方法,我想知道这在多线程系统中有多危险(或安全)。