Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instance-controlled classes and multithreading

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?

like image 383
thee Avatar asked Aug 17 '14 22:08

thee


People also ask

What is instance control?

Each time a new system is added with a compliance objective, a new set of controls is created. This set of controls applied to an information system is called a control instance. But for the most part, the controls are the same and are configured by you to act in the same manner.

What is the current instance of a class?

An instance of a class is an object. It is also known as a class object or class instance. As such, instantiation may be referred to as construction. Whenever values vary from one object to another, they are called instance variables.


1 Answers

Make newInstance synchronized that is

public static synchronized Entity newInstance(UUID entityId){
     ...
}

so that one a thread enters the new instance method, no other thread can invoke this method unless the first thread finishes. Basically what happens is the first thread gets a lock for the entire class. For time that the first thread holds the lock for the class, no other thread can enter a synchronized static method for that class.

like image 172
committedandroider Avatar answered Sep 28 '22 07:09

committedandroider