Hi All,
I'm reading a
post on singleton
pattern and I wanted to check, if below code is threadsafe, i.e each
thread do not get into race condition and do not break singleton, if yes at what point. I tried to create singleton objects by 50 threads and in all cases, I'm able to see only one object being created. But I can't still say, singleton is not broken
My thread
and I spawned 50 threads and started them and I see only one object.
I know there is lot of discussion on synchronizing , articles supporting double checked locking and some not supporting like
this
But since private static EagerSingleton singleton = new EagerSingleton(); is a static variable, only one instance exists per class per jvm. and the very first thread managed to call getInstance(), is able to create the singleton object and any subsequent threads gets a reference of it. Even when two threads call getInstance() concurrently, since it is a static variable, would not there be only one invocation of object creation.
If the above setup is not thread safe, could some one help me how to break this. I tried increasing the number of threads to 100 and also added some sleep(), but could not achieve that. I basically wanted to see, if I can break this code by creating more than on object and if not, can I conclude that to be a safer approach.