Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what happens if more than one thread tries to access singleton object

Tags:

singleton

Not during instantiation, but once instantiation of singleton object is done, what will happen if two or more threads are trying to access the same singleton object? Especially in the case where the singleton object takes lot of time to process the request (say 1 min)... In this case, if for ex., 5 threads try to access the same singleton object, what will the result be?

Additional question: normally when should we go for the singleton pattern and when should we avoid it?

like image 411
siva Avatar asked Aug 24 '09 13:08

siva


People also ask

What happens when two threads access Singleton at same time?

Now coming to your question: if you share your singleton object among multiple threads and access it concurrently, every single thread will execute Singleton object's portion of code, wrapped in its own execution. Also if you write a Thread.

Can a singleton class be accessed by multiple threads?

A singleton class itself is not thread safe. Multiple threads can access the singleton same time and create multiple objects, violating the singleton concept. The singleton may also return a reference to a partially initialized object.

Can you have more than one singleton?

Since there is only one Singleton instance, any instance fields of a Singleton will occur only once per class, just like static fields. Singletons often control access to resources such as database connections or sockets.

What is multithreaded Singleton?

Thread Safe Singleton: A thread safe singleton is created so that singleton property is maintained even in multithreaded environment. To make a singleton class thread safe, getInstance() method is made synchronized so that multiple threads can't access it simultaneously.


1 Answers

Unless synchronization (locking) is being performed within the Singleton, the answer is this: it's a free-for-all.

Though the Singleton ensures that only one instance of an object is used when requested, the pattern itself doesn't inherently provide any form of thread safety. This is left up to the implementer.

In the specific case you cited (with a long running method), it would be critical to synchronize access to any method that uses class or object-level variables. Failure to do so would, in all likelihood, lead to race conditions.

Good luck!

like image 161
Sean P. McDonough Avatar answered Oct 12 '22 09:10

Sean P. McDonough