473,386 Members | 1,710 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Thread-Safe Singleton

I have a server application that makes a MarshalByReferenceObject available
via remoting. It's lifetime is set to never expire and it is implemented as
a Singleton.

Are calls to this object inherently thread safe? If 1000 threads all call
the same method of this object at once, do I have to add anything to my code
to assure that there are no problems?

Excuse me if this is really obvious. I am somewhat new to remoting and
totally new to multithreading.

Thanks in advance.
Robert Zurer
ro****@zurer.com
Nov 15 '05 #1
8 3949
Robert,

This is a good question. If you have the object set up as a singleton,
then every call will come in to the same instance. Now if you have multiple
calls coming in to your object, then it is definitely possible that those
calls will come in on separate threads (if the calls are from seprate app
domains, or even different threads in the same app domain).

So, because of this, your object will have to handle the multithreaded
aspect. You should be placing sections of code in "lock" sections (or using
some other synchronization mechanism, but lock is the most common). For
more information on the lock keyword, check out the section of the .NET
framework documentation titled "lock Statement", located at (watch for line
wrap):

http://msdn.microsoft.com/library/de...kStatement.asp

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Robert Zurer" <ro****@zurer.com> wrote in message
news:uk**************@TK2MSFTNGP10.phx.gbl...
I have a server application that makes a MarshalByReferenceObject available via remoting. It's lifetime is set to never expire and it is implemented as a Singleton.

Are calls to this object inherently thread safe? If 1000 threads all call
the same method of this object at once, do I have to add anything to my code to assure that there are no problems?

Excuse me if this is really obvious. I am somewhat new to remoting and
totally new to multithreading.

Thanks in advance.
Robert Zurer
ro****@zurer.com

Nov 15 '05 #2
Hi Robert,

Jon Skeet has a superb article regarding this, you can find it at:
http://www.yoda.arachsys.com/csharp/singleton.html

Hope this help,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation

"Robert Zurer" <ro****@zurer.com> wrote in message
news:uk**************@TK2MSFTNGP10.phx.gbl...
I have a server application that makes a MarshalByReferenceObject available via remoting. It's lifetime is set to never expire and it is implemented as a Singleton.

Are calls to this object inherently thread safe? If 1000 threads all call
the same method of this object at once, do I have to add anything to my code to assure that there are no problems?

Excuse me if this is really obvious. I am somewhat new to remoting and
totally new to multithreading.

Thanks in advance.
Robert Zurer
ro****@zurer.com

Nov 15 '05 #3
No, they aren't safe, inherently (though they might be by accident). The
reason is simple: you *may* be referencing resources (i.e. placing them in a
state that a single method call depends on) inside any one of your methods.
If you don't reference anything external in your method (i.e. only have
primative typed, by value input parameters and no local variables or field
references in your method) then your call is probably safe.

Richard

--
C#, .NET and Complex Adaptive Systems:
http://blogs.geekdojo.net/Richard
"Robert Zurer" <ro****@zurer.com> wrote in message
news:uk**************@TK2MSFTNGP10.phx.gbl...
I have a server application that makes a MarshalByReferenceObject available via remoting. It's lifetime is set to never expire and it is implemented as a Singleton.

Are calls to this object inherently thread safe? If 1000 threads all call
the same method of this object at once, do I have to add anything to my code to assure that there are no problems?

Excuse me if this is really obvious. I am somewhat new to remoting and
totally new to multithreading.

Thanks in advance.
Robert Zurer
ro****@zurer.com

Nov 15 '05 #4

"Ignacio Machin ( .NET/ C# MVP )" <ignacio.machin AT dot.state.fl.us> wrote
in message
Jon Skeet has a superb article regarding this, you can find it at:
http://www.yoda.arachsys.com/csharp/singleton.html

Yes. I read it. I have a question though.

The code I have been using is this.
public sealed class Singleton
{

private Singleton(){}
public static readonly Singleton Instance = new Singleton();

}

This seems what Jon is referring to when he mentions a shortcut to the
fourth version of the Singleton pattern in his article. Am I right.

It's just not clear to me yet why this is thread-safe.
Nov 15 '05 #5
Robert Zurer <ro****@zurer.com> wrote:
Jon Skeet has a superb article regarding this, you can find it at:
http://www.yoda.arachsys.com/csharp/singleton.html
Yes. I read it. I have a question though.

The code I have been using is this.

public sealed class Singleton
{

private Singleton(){}
public static readonly Singleton Instance = new Singleton();

}

This seems what Jon is referring to when he mentions a shortcut to the
fourth version of the Singleton pattern in his article. Am I right.


Yes.
It's just not clear to me yet why this is thread-safe.


It's thread-safe in terms of *acquiring* the singleton - it doesn't
mean that methods within the type are automatically thread-safe. To be
honest, I don't know how/whether remoting affects this at all.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #6

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message > It's thread-safe
in terms of *acquiring* the singleton - it doesn't
mean that methods within the type are automatically thread-safe. To be
honest, I don't know how/whether remoting affects this at all.

Thank you so much for responding. I have gained a tremendous amount from
your posts and your articles. They are incredible clear. Your baby is cute
too :-)

I do understand that methods of the singleton need to use locks if they
access a resource. I guess what I still don't understand is what is it
actuially, that makes the aquiring the instance thread-safe.

You say "static constructors in C# are specified to execute only when an
instance of the class is created or a static member is referenced, and to
execute only once per AppDomain"

In the abbreviated version, the static constructor is removed. Is the
static type initialization executed only once as well? Is that what
guarantees the thread-safety?
As regards remoting, I am not traversing AppDomains, but I am going to be
intercepting calls using ContextBoundObject. I access the Singleton from a
ServerContextSink. I don't know whether it would be safer to use the
implementation below.

private static Singleton Instance
{
get
{
if (instance == null)
lock (typeof(Singleton))
if (instance == null)
instance = new Singleton();
return instance;
}
}

Thanks again for all your help.
Robert Zurer
Nov 15 '05 #7
Robert Zurer <ro****@zurer.com> wrote:
Thank you so much for responding. I have gained a tremendous amount from
your posts and your articles. They are incredible clear. Your baby is cute
too :-)
:)
I do understand that methods of the singleton need to use locks if they
access a resource. I guess what I still don't understand is what is it
actuially, that makes the aquiring the instance thread-safe.
Right.
You say "static constructors in C# are specified to execute only when an
instance of the class is created or a static member is referenced, and to
execute only once per AppDomain"

In the abbreviated version, the static constructor is removed. Is the
static type initialization executed only once as well? Is that what
guarantees the thread-safety?
Type initializers are guaranteed by the CLR specification to only be
executed once, and that anything else which would trigger type
initialization will wait until the type initializer has finished before
continuing. The difference the static constructor makes is only in
terms of exactly what triggers the initialization - you basically get
more guarantees about exact timing with it there, but the
initialization is safe either way.
As regards remoting, I am not traversing AppDomains, but I am going to be
intercepting calls using ContextBoundObject. I access the Singleton from a
ServerContextSink.
Unfortunately I know so little about remoting that I'm not much help
there - but I suspect you'll be fine with the normal methods.
I don't know whether it would be safer to use the
implementation below.

private static Singleton Instance
{
get
{
if (instance == null)
lock (typeof(Singleton))
if (instance == null)
instance = new Singleton();
return instance;
}
}


Definitely don't use the above - it's *not* threadsafe, IMO. It's
effectively the double-check lock algorithm, the third option on the
website.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #8
hi Nicholas,

I got the same problem that Robert had. I have created a server-activated
singleton object on the server. I tried to call this object from a web
service coming from 2 different clients simultaneously but one remote object
call returns successfully while the other remote object call just hangs on
the browser. I use the lock(this) to lock the lengthy process (simulated by
Thread.Sleep(10000) on the server object).

How can I make both calls return successfully?

thanks
Joseph
"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard.caspershouse.com> wrote in
message news:OX*************@TK2MSFTNGP09.phx.gbl...
Robert,

This is a good question. If you have the object set up as a singleton, then every call will come in to the same instance. Now if you have multiple calls coming in to your object, then it is definitely possible that those
calls will come in on separate threads (if the calls are from seprate app
domains, or even different threads in the same app domain).

So, because of this, your object will have to handle the multithreaded
aspect. You should be placing sections of code in "lock" sections (or using some other synchronization mechanism, but lock is the most common). For
more information on the lock keyword, check out the section of the .NET
framework documentation titled "lock Statement", located at (watch for line wrap):

http://msdn.microsoft.com/library/de...kStatement.asp
Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Robert Zurer" <ro****@zurer.com> wrote in message
news:uk**************@TK2MSFTNGP10.phx.gbl...
I have a server application that makes a MarshalByReferenceObject

available
via remoting. It's lifetime is set to never expire and it is implemented

as
a Singleton.

Are calls to this object inherently thread safe? If 1000 threads all call the same method of this object at once, do I have to add anything to my

code
to assure that there are no problems?

Excuse me if this is really obvious. I am somewhat new to remoting and
totally new to multithreading.

Thanks in advance.
Robert Zurer
ro****@zurer.com


Nov 15 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

14
by: adeger | last post by:
Having trouble with my first forays into threads. Basically, the threads don't seem to be working in parallel (or you might say are blocking). I've boiled my problems to the following short code...
4
by: Gilles Leblanc | last post by:
Hi I have started a small project with PyOpenGL. I am wondering what are the options for a GUI. So far I checked PyUI but it has some problems with 3d rendering outside the Windows platform. I...
7
by: Ivan | last post by:
Hi I have following problem: I'm creating two threads who are performing some tasks. When one thread finished I would like to restart her again (e.g. new job). Following example demonstrates...
4
by: Matthew Groch | last post by:
Hi all, I've got a server that handles a relatively high number of concurrent transactions (on the magnitude of 1000's per second). Client applications establish socket connections with the...
5
by: Razzie | last post by:
Hi all, A question from someone on a website got me thinking about this, and I wondered if anyone could explain this. A System.Threading.Timer object is garbage collected if it has no...
16
by: droopytoon | last post by:
Hi, I start a new thread (previous one was "thread timing") because I have isolated my problem. It has nothing to do with calling unmanaged C++ code (I removed it in a test application). I...
9
by: mareal | last post by:
I have noticed how the thread I created just stops running. I have added several exceptions to the thread System.Threading.SynchronizationLockException System.Threading.ThreadAbortException...
13
by: Bob Day | last post by:
Using vs2003, vb.net I start a thread, giving it a name before start. Code snippet: 'give each thread a unique name (for later identification) Trunk_Thread.Name = "Trunk_0_Thread" ' allow...
7
by: Charles Law | last post by:
My first thought was to call WorkerThread.Suspend but the help cautions against this (for good reason) because the caller has no control over where the thread actually stops, and it might have...
3
by: John Nagle | last post by:
There's no way to set thread priorities within Python, is there? We have some threads that go compute-bound, and would like to reduce their priority slightly so the other operations, like...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.