confused by synchronized usage

65 views Asked by At

I see the netflix code, in class DynamicPropertyFactory,there's a method like

public static DynamicPropertyFactory getInstance() {
    if (config == null) {
        synchronized (ConfigurationManager.class) {
            if (config == null) {
                AbstractConfiguration configFromManager = ConfigurationManager.getConfigInstance();
                if (configFromManager != null) {
                    initWithConfigurationSource(configFromManager);
                    initializedWithDefaultConfig = !ConfigurationManager.isConfigurationInstalled();
                    logger.info("DynamicPropertyFactory is initialized with configuration sources: " + configFromManager);
                }
            }
        }
    }
    return instance;
}

I'm confused on this method that why using synchronized (ConfigurationManager.class), key word synchronized was used on another class ConfigurationManager.class. From my view, synchronized is used in its current class. So, someone can help explain this simplely?

2

There are 2 answers

2
Karlo Serrano On

Probably because they expect other classes to access ConfigurationManager on some other thread.

0
Ravindra babu On

Above code was not well written.

DynamicPropertyFactory should not worry about incorporating synchronized checks to get ConfigurationManager instance.

Ideally ConfigurationManager.getConfigInstance() should have proper checks and synchronized (ConfigurationManager.class) check should be moved to ConfigurationManager.

Callers of ConfigurationManager should simply get instance with getConfigInstance() API without any synchronized checks.

Have a look at below SE question to implement Singleton object in right way:

Why is volatile used in this example of double checked locking