Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synchronized blocks in constructors

I have a class with a static var like so

private static Object sMyStaticVar;

if i want to assign a value to this var in the constructor I have code like

if(sMyStaticVar == null) sMyStaticVar = new CustomObject(someRuntimeObject);

where someRuntimeObject is an object that is not available at the time my class is loaded and therefore prevents me from declaring my static var like the below

private static Object sMyStaticVar = new CustomObject(someRuntimeObject);

my question is, is the initialization of the static var object in the constructor thread safe? My instincts tell me its not and i should synchronise using the non-runtime class type as the lock, like the below

synchronized(MyClass.class)
{
    if(sMyStaticVar == null) sMyStaticVar = new CustomObject(someRuntimeObject);
}

(as opposed to the runTime type obtained from getClass())

but as my instincts are usually wrong I would be grateful if anyone could shed some light on this for me!

like image 692
Dori Avatar asked Mar 26 '26 08:03

Dori


1 Answers

If it is static, you should not assign it in the constructor. Make a static initializer method that does that public static synchronized void initialize(someRuntimeObject).

Note the synchronized keyword: it is is the same as synchronizing on MyClass.class

like image 65
Bozho Avatar answered Mar 28 '26 22:03

Bozho



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!