In Effective Java Chapter 2, Item 1 Bloch suggests to consider static factory methods instead of constructors to initalize an object. On of the benefits he mentions is that this pattern allows classes to return the same object from repeated invocations:
The ability of static factory methods to return the same object from repeated invocations allows classes to maintain strict control over what instances exist at any time. Classes that do this are said to be instance-controlled. There are several reasons to write instance-controlled classes. Instance control allows a class to guarantee that it is a singleton (Item 3) or noninstantiable (Item 4). Also, it allows an immutable class (Item 15) to make the guarantee that no two equal instances exist: a.equals(b) if and only if a==b.
How would this pattern work in a multi threaded environment? For example, I have an immutable class that should be instance-controlled because only one entity with the given ID can exist at a time:
public class Entity {
private final UUID entityId;
private static final Map<UUID, Entity> entities = new HashMap<UUID, Entity>();
private Entity(UUID entityId) {
this.entityId = entityId;
}
public static Entity newInstance(UUID entityId) {
Entity entity = entities.get(entityId);
if (entity == null) {
entity = new Entity(entityId);
entities.put(entityId, entity);
}
return entity;
}
}
What would happen if I call newInstance()
from separated threads? How can I make this class thread-safe?