Question

I have declared an enum and this is what it looks like (not real code)

public enum MySession {

    INSTANCE;

    MySession() {
        loadFactory();
    }

    public void refreshMyFactory() {
        //Is it OK to call "loadFactory" here as-is, or should I worry about concurrency
    }

    private void loadFactory() {
        MyFactory factory = null;
        try {
            //Initialize factory by doing some IO.
        } catch (final Exception exception) {
            //Handle Exception
        } finally {
            myFactory = factory;
            //If NULL, log FATAL exception...
        }
    }

    private MyFactory myFactory;

    /**
     * @return the sessionFactory
     */
    public MyFactory getMyFactory() {
        return myFactory;
    }

}

There are multiple threads that may access MySession.INSTANCE.getMyFactory() and use the factory. The factory is created by reading a file from the Input Stream.

The use case is that I need to refresh this factory programmatically.

Questions:

Is there a way to lock access to the factory till it gets updated? How messy would that be?

Is it OK to simply update the factory as is without any locking. What are the implications of doing so?

Was it helpful?

Solution 2

replace the following code snippets:

private void loadFactory() {
    ...
    myFactory = factory;
}
private MyFactory myFactory;
public MyFactory getMyFactory() {
    return myFactory;
}

with:

private void loadFactory() {
    ...
    myFactoryRef.set(factory);
}
private AtomicReference<MyFactory> myFactoryRef;
public MyFactory getMyFactory() {
    return myFactoryRef.get();
}

and you do not need to bother with any additional synchronization. The atomic reference ensures that updates to the variable are atomic. So other threads calling getMyFactory() will either see the old instance or the new instance of MyFactory and no additional synchronization will be required in loadFactory() or refreshMyFactory().

OTHER TIPS

Is there a way to lock access to the factory till it gets updated? How messy would that be?

You can make both getMyFactory and loadFactory synchronized.

Is it OK to simply update the factory as is without any locking. What are the implications of doing so?

You would need to make myFactory volatile to ensure the change can be seen. The implication is you don't need any other operations to be thread safe. i.e. for the code you have, its fine.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top