Search code examples
javathread-safetysingletonproperties-file

Is my PropertyLoader singleton threadsafe?


I get errors due to an unexpected property value and I am trying to narrow down the cause. The property is loaded from a file by the following example class:

public final class PropertyLoader {

    private enum Instances{
        ELVIS;

        private final PropertyLoader loader;

        Instances() {
            this.loader = new PropertyLoader();
        }
    }

    private boolean isPropertyEnabled;

    private PropertyLoader() {
        loadProperties();
    }


    public static PropertyLoader getInstance() {
        Instances.ELVIS.loader;
    }

    private void loadProperties() {
        this.isPropertyEnabled = loadPropertyFromFile(FILE, "enabled");
        //... more properties
    }

    public boolean isPropertyEnabled() {
        // eventually returns unexpected value
        return this.isPropertyEnabled;
    }
}

Is this implementation threadsafe? If not, how can I improve the implementation without changing the interface? Is there an efficient strategy to test this class for concurrency issues?


Solution

  • It is thread safe. Because all the initialization is basically done during initialization of the class. So there is no way how two threads would be able to get data from the object until class loading is finished.