有人告诉我,Java构造函数是同步的,所以在构造期间不能并发访问,我想知道:如果我有一个将对象存储在map中的构造函数,而另一个线程在其构造完成之前从该map检索对象,那么该线程是否会阻塞,直到构造函数完成?
让我用一些代码来演示:
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中走了多远,以及这样的代码是否会有问题。我最近看到这样的代码实现了这一点,而不是使用静态工厂方法,我想知道这在多线程系统中有多危险(或安全)。
https://stackoverflow.com/questions/12611366
复制相似问题