Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 549
SME_Dev Avatar asked Apr 26 '26 04:04

SME_Dev


1 Answers

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.

like image 98
Zbynek Vyskovsky - kvr000 Avatar answered Apr 27 '26 16:04

Zbynek Vyskovsky - kvr000



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!