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);
}
}
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.
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?
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.
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
thisbeing constructed.No it won’t.
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.
finalfields will be guaranteed to be fully initialized by the time the constructor finishes but not other “normal” fields.In your case, since you are putting your
Testinto 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 astaticmethod to create your object:My example code works since you are dealing with a synchronized-map, which makes a call to
synchronizedwhich ensures that theTestconstructor has completed and has been memory synchronized.The big problems in your example is both the “happens before” guarantee (the constructor may not finish before
Testis put into the map) and memory synchronization (the constructing thread and the get-ing thread may see different memory for theTestinstance). If you move theputoutside of the constructor then both are handled by the synchronized-map. It doesn’t matter what object it issynchronizedon to guarantee that the constructor has finished before it was put into the map and the memory has been synchronized.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 thesuper(). Thestaticsolution I showed is a better pattern.