473,756 Members | 2,703 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

thread safe singleton pattern (as a property)

Is the second version shown below better? I couldn't locate enough info
about [MethodImpl(Meth odImplOptions.S ynchronized)] in order to tell.

1.. My commonly used singleton pattern implementation looks like this (it
was inspired by Eric Gunnerson's book):

private static volatile MyClass singleton = null;
private static object sync = new object();//for static lock
public static MyClass Instance
{
get
{
if (singleton == null)
{
lock (sync)
{
if (singleton == null)
{
singleton = new MyClass ();
}
}
}
return singleton;
}
}//Instance

2. An alternate implementation inspired by 'Design Patterns Explained: A New
Perspective on Object-Oriented Design' by by Alan Shalloway, James R. Trott.

public static MyClass Instance
{
get
{
if (s_Instance == null)
{
DoSynchronizedE xistenceCheck() ;
}
return s_Instance;
}
}

[MethodImpl(Meth odImplOptions.S ynchronized)]
private static void DoSynchronizedE xistenceCheck()
{
if (s_Instance == null)
{
s_Instance = new MyClass();
}
}
Nov 15 '05 #1
15 5404
Mountain Bikn' Guy <vc@attbi.com > wrote:
Is the second version shown below better? I couldn't locate enough info
about [MethodImpl(Meth odImplOptions.S ynchronized)] in order to tell.


It's the equivalent of doing:

lock (this)
or
lock (typeof(MyClass ))

round the rest of the method, I believe. I don't believe it
particularly helps in this case.

The first version is *probably* safe due to MyClass being volatile, but
I wouldn't like to say for sure. However, there are fortunately simpler
and definitely reliable versions:

http://www.pobox.com/~skeet/csharp/singleton.html

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #2
Thanks Jon! Your page is very informative!
Mountain

"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
Mountain Bikn' Guy <vc@attbi.com > wrote:
Is the second version shown below better? I couldn't locate enough info
about [MethodImpl(Meth odImplOptions.S ynchronized)] in order to tell.


It's the equivalent of doing:

lock (this)
or
lock (typeof(MyClass ))

round the rest of the method, I believe. I don't believe it
particularly helps in this case.

The first version is *probably* safe due to MyClass being volatile, but
I wouldn't like to say for sure. However, there are fortunately simpler
and definitely reliable versions:

http://www.pobox.com/~skeet/csharp/singleton.html

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 15 '05 #3
Jon,
You mention the following:
"There are complications if one static constructor invokes another which
invokes the first again."

I have run into this problem (or a very similar one) quite frequently,
actually, using the first singleton pattern I posted. Specifically, I have
seen cases where a threadsafe singleton created in a situation where the
static constructors which refer to each other in a cycle then seemingly
contains two different values in one field, depending upon whether that
field is accessed by the other singleton or some third object. Note that I
witnessed this even thought I don't explicity use a static constructor in my
singleton pattern.

Also, you mention "It still doesn't perform as well as the later
implementations " in regard to your 3rd example. However, I assume that
whenever you are mentioning performance on this page, you are referring only
to laziness. (I ready your excellent discussion on your "beforefieldinn it"
page, which led me to understand that laziness != better performance in all
situations -- and that also led me to ask you to clarify that the word
performance on your singleton page refers strictly to laziness).

Regards,
Mountain
Nov 15 '05 #4
Mountain Bikn' Guy <vc@attbi.com > wrote:
You mention the following:
"There are complications if one static constructor invokes another which
invokes the first again."

I have run into this problem (or a very similar one) quite frequently,
actually, using the first singleton pattern I posted. Specifically, I have
seen cases where a threadsafe singleton created in a situation where the
static constructors which refer to each other in a cycle then seemingly
contains two different values in one field, depending upon whether that
field is accessed by the other singleton or some third object. Note that I
witnessed this even thought I don't explicity use a static constructor in my
singleton pattern.
I may not have been very precise here - I'll check later on. You don't
need to be using an explicit static constructor to get this kind of
behaviour, just static initialization of some description.
Also, you mention "It still doesn't perform as well as the later
implementations " in regard to your 3rd example. However, I assume that
whenever you are mentioning performance on this page, you are referring only
to laziness. (I ready your excellent discussion on your "beforefieldinn it"
page, which led me to understand that laziness != better performance in all
situations -- and that also led me to ask you to clarify that the word
performance on your singleton page refers strictly to laziness).


Nope, it's not to do with laziness (and as you've inferred, enforcing
strict laziness can reduce performance). It's to do with how many
checks need to be done - with my code, the only check done on each call
is whether or not the type has been initialized (and the JIT can cache
that information, or pre-initialize if it's marked as beforefieldinit ,
etc). With the double-check lock algorithm, you need to check whether
or not the static field is null every time, and the first time through
you need to take out a lock as well. You need to do those things *as
well* as all the checks that are in the faster version, because
obviously the type needs to still have been loaded/initialized (even if
initialization merely consists of making sure that there's no real
initialization to do).

I haven't got a handy benchmark on this ready to post, but I could
write one if you're interested.

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

"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
Mountain Bikn' Guy <vc@attbi.com > wrote:
You mention the following:
"There are complications if one static constructor invokes another which
invokes the first again."

I have run into this problem (or a very similar one) quite frequently,
actually, using the first singleton pattern I posted. Specifically, I have seen cases where a threadsafe singleton created in a situation where the
static constructors which refer to each other in a cycle then seemingly
contains two different values in one field, depending upon whether that
field is accessed by the other singleton or some third object. Note that I witnessed this even thought I don't explicity use a static constructor in my singleton pattern.
I may not have been very precise here - I'll check later on. You don't
need to be using an explicit static constructor to get this kind of
behaviour, just static initialization of some description.


Thanks. That clarification helps.
Also, you mention "It still doesn't perform as well as the later
implementations " in regard to your 3rd example. However, I assume that
whenever you are mentioning performance on this page, you are referring only to laziness. (I ready your excellent discussion on your "beforefieldinn it" page, which led me to understand that laziness != better performance in all situations -- and that also led me to ask you to clarify that the word
performance on your singleton page refers strictly to laziness).


Nope, it's not to do with laziness (and as you've inferred, enforcing
strict laziness can reduce performance). It's to do with how many
checks need to be done.


Thanks again. I recognized the error of my statement -- but only after I had
already posted it. (Where's that "Unsend" button?)

Jon, I would really appreciate your clarification on whether the explicit
static ctor can be left out of both example 4 and example 5 of your
singleton patterns without impacting their thread safety.

Regards,
Mountain
Nov 15 '05 #6
Mountain Bikn' Guy <vc@attbi.com > wrote:
Jon, I would really appreciate your clarification on whether the explicit
static ctor can be left out of both example 4 and example 5 of your
singleton patterns without impacting their thread safety.


It definitely can. The static constructor itself is *only* necessary
for laziness.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #7
Hi Lefty :)
Thanks again. I recognized the error of my statement -- but only after I had already posted it. (Where's that "Unsend" button?)


Actually there is one: Message/Cancel Message in our favorite newsreader OE.
Unfortunatelly it doesn't seem to work with ms newsgroups.

--
Miha Markic - RightHand .NET consulting & software development
miha at rthand com
www.rthand.com
Nov 15 '05 #8
Me
Jon
Double locking pattern is not thread safe in .NET as well as in Java.
See Cris Brumme's blog and other places

"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
Mountain Bikn' Guy <vc@attbi.com > wrote:
You mention the following:
"There are complications if one static constructor invokes another which
invokes the first again."

I have run into this problem (or a very similar one) quite frequently,
actually, using the first singleton pattern I posted. Specifically, I have seen cases where a threadsafe singleton created in a situation where the
static constructors which refer to each other in a cycle then seemingly
contains two different values in one field, depending upon whether that
field is accessed by the other singleton or some third object. Note that I witnessed this even thought I don't explicity use a static constructor in my singleton pattern.


I may not have been very precise here - I'll check later on. You don't
need to be using an explicit static constructor to get this kind of
behaviour, just static initialization of some description.
Also, you mention "It still doesn't perform as well as the later
implementations " in regard to your 3rd example. However, I assume that
whenever you are mentioning performance on this page, you are referring only to laziness. (I ready your excellent discussion on your "beforefieldinn it" page, which led me to understand that laziness != better performance in all situations -- and that also led me to ask you to clarify that the word
performance on your singleton page refers strictly to laziness).


Nope, it's not to do with laziness (and as you've inferred, enforcing
strict laziness can reduce performance). It's to do with how many
checks need to be done - with my code, the only check done on each call
is whether or not the type has been initialized (and the JIT can cache
that information, or pre-initialize if it's marked as beforefieldinit ,
etc). With the double-check lock algorithm, you need to check whether
or not the static field is null every time, and the first time through
you need to take out a lock as well. You need to do those things *as
well* as all the checks that are in the faster version, because
obviously the type needs to still have been loaded/initialized (even if
initialization merely consists of making sure that there's no real
initialization to do).

I haven't got a handy benchmark on this ready to post, but I could
write one if you're interested.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 15 '05 #9
Me <di******@yahoo .com> wrote:
Double locking pattern is not thread safe in .NET as well as in Java.


Indeed, that's my feeling too. That's why I've said so in the article -
or rather, I've said that although there are reports that it *is*
thread-safe in .NET, I can't see why it would be, and other people
report that it isn't. Perhaps it's time to word that even more strongly
though...

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

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

Similar topics

8
3970
by: Robert Zurer | last post by:
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...
1
2723
by: William Sullivan | last post by:
I'm trying to nail down some issues with the cache in my application. Currently, I have an object that stands between my business logic and database logic called CacheLogic (cute, no?). Global.asax.cs creates it in Application_Start, initializes it and places it in the cache. During initialization, CacheLogic retrieves data from the DB logic layer and caches it with removal callbacks set. Whenever an object in the business logic layer...
11
4924
by: Eric | last post by:
I have a VB.net dll project with a class that is a singleton. I've been using this in winform apps without any problems. I would like to use this same dll in a web form project but my singleton will cause problems because some sessions may need different values in the singleton. I want to change my singleton to store a private hashtable with different instances. I guess this is more like a factory pattern now but that doesn't matter ...
2
3929
by: Tom | last post by:
In a web-application I need to read some configuration from a database. I like to write a configuration class which will be implemented as thread-safe singleton. I connect through ODBC to the database. So to be able to do that I need to pass the Datasource Name. How can I create a singleton that has a constructor with a parameter? Standard singleton pattern always use the default constructor. To provide an init(string datasource_name)...
0
9431
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10014
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9844
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9819
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7226
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5119
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3780
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3326
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2647
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.