Singleton Class and Performance issues

  • Thread starter Thread starter Ajay Pal Singh
  • Start date Start date
A

Ajay Pal Singh

Hi,

I've one question related to singelton implementation of a class. Suppose a
class is as Singelton and contains a public method. If there are more than
one requests for the same method simultaneously. How the dotnet runtime
handles this scenario.
Will it force the second request to wait the till the execution of first
request for the same method.
Please throw some light.
Regards,
Ajay
 
Unless you are using threads you, a method can only have one invocation at a
time.

If you are using threads, you might need to do something like
"lock(this){...}" when in the factory method so that you can ensure that an
object is not partially created when the next tread tries to access it.
 
Multiple threads can call a single method almost "simultaneously" so in
a free
threaded environment you will need to consider if a race condition or
concurrency conflict can occur. Thread local storage and immutable
variables
and objects are generally free of race condition, concurrency conflicts.
So to be
clear, if two threads call the same method "almost simultaneously", both
threads
will get a separate stack frame for local storage.

http://www.geocities.com/Jeff_Louie/OOP/oop25.htm

Regards,
Jeff
 
Ajay Pal Singh said:
I've one question related to singelton implementation of a class. Suppose a
class is as Singelton and contains a public method. If there are more than
one requests for the same method simultaneously. How the dotnet runtime
handles this scenario.
Will it force the second request to wait the till the execution of first
request for the same method.

Not by default, no - assuming the methods are being called in different
threads, the same code can be executing in two threads unless you put
some locking in. Depending on your situation, you may need locking or
it may be a terrible idea.

I suggest you read
http://www.pobox.com/~skeet/csharp/singleton.html for how to make the
"singleton" bit of your code threadsafe, and
http://www.pobox.com/~skeet/csharp/threads
for general threading advice.
 
Back
Top