Kris82
Kris82

Reputation: 113

Can a method from a singleton object be called from multiple threads at the same time?

I have a component registered in Castle Windsor as a singleton. This object is being used in many other places within my application which is multithreaded.

Is it possible that the two objects will invoke the same method from that singleton at the same time or 'calling it' will be blocked until the previous object will get result?

Thanks

Upvotes: 9

Views: 3948

Answers (3)

Sathish
Sathish

Reputation: 29

The normal version of Singleton may not be thread safe, you could see different implementation of thread safe singleton here.

http://tutorials.csharp-online.net/Singleton_design_pattern:_Thread-safe_Singleton

Upvotes: 0

Shakti Prakash Singh
Shakti Prakash Singh

Reputation: 2533

You can call a Singleton object method from different threads at the same time and they would not be blocked if there is no locking/ synchronization code. The threads would not wait for others to process the result and would execute the method as they would execute methods on separate objects. This is due to the fact that each thread has a separate stack and have different sets of local variables. The rest of the method just describes the process as to what needs to be done with the data which is held the variables/fields.

What you might want to take care of is if the methods on the Singleton object access any static methods or fields/variables. In that case you might need to work on synchronization part of it. You would need to ensure multi-threaded access to shared resources for the execution of the method to be reliable.

To be able to synchronize, you might need to use lock statement or other forms of thread synchronization techniques.

You might want to refer to this article from Wikipedia which provides information on C# thread local storage as well.

Upvotes: 14

peter
peter

Reputation: 15119

You can call the same method or different methods on one object simultaneously from different threads. In the specific methods you'll need to know when sensitive variables are being accessed (mostly when member-variables are changing their values) and will need to implement locking on your own, in order to solve lost updates and other anomalies.

You can lock a part of a code with the lock-statement and here an article on how Thread-Synchronization works in .Net.

Upvotes: 2

Related Questions