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

3

9

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

Felid answered 29/5, 2014 at 11:57 Comment(1)
Unluess you use some form of locking, yes it can be called from multiple threads. Maybe have a look at C#: System.Lazy<T> and the Singleton Design PatternPrecatory
C
12

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.

Carrageen answered 29/5, 2014 at 12:4 Comment(0)
U
2

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.

Ulu answered 29/5, 2014 at 12:2 Comment(0)
S
0

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

Shillong answered 29/5, 2014 at 12:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.