473,385 Members | 1,630 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,385 software developers and data experts.

Singlton implementation

Does any one know how to implment a singlton in c#. I have done the
implementation but I ran in to "Double-checked locking alert"
implemenation and not sure how to implement it. Or let me put it this
way, what is the equivalent of the following java code to resolve the
double-checked locking alert???

private volatile static Singlton uniqueInstance

public static Singlton getInstance()
{
if (uniqueInstance == null)
{
synchornized(Singlton.class) { <-- how can we do this in c#
if (uniqueInstance == null){
uniqueInstance = new Singlton();
}
}
}
}

Sep 12 '06 #1
10 3466
DBC User,

The following article describes what's required in detail and offers
other suggestions as well.

http://www.yoda.arachsys.com/csharp/singleton.html

Brian

DBC User wrote:
Does any one know how to implment a singlton in c#. I have done the
implementation but I ran in to "Double-checked locking alert"
implemenation and not sure how to implement it. Or let me put it this
way, what is the equivalent of the following java code to resolve the
double-checked locking alert???

private volatile static Singlton uniqueInstance

public static Singlton getInstance()
{
if (uniqueInstance == null)
{
synchornized(Singlton.class) { <-- how can we do this in c#
if (uniqueInstance == null){
uniqueInstance = new Singlton();
}
}
}
}
Sep 12 '06 #2
DBC User wrote:
Does any one know how to implment a singlton in c#. I have done the
implementation but I ran in to "Double-checked locking alert"
implemenation and not sure how to implement it. Or let me put it this
way, what is the equivalent of the following java code to resolve the
double-checked locking alert???

private volatile static Singlton uniqueInstance

public static Singlton getInstance()
{
if (uniqueInstance == null)
{
synchornized(Singlton.class) { <-- how can we do this in c#
if (uniqueInstance == null){
uniqueInstance = new Singlton();
}
}
}
}
private static Singlton instance = null;
private static object mylock = new object();
public static Singlton Instance
{
get {
lock(mylock)
{
if(instance == null)
{
instance = new Singlton();
}
}
return instance;
}
}

is what I would call the canonical form.

NB: Double locking does not work properly in Java and last
time I read the verdict was that it did not work in .NET
either (just works accidentally on x86 platform).

Arne
Sep 12 '06 #3
Brian Gideon wrote:
The following article describes what's required in detail and offers
other suggestions as well.

http://www.yoda.arachsys.com/csharp/singleton.html
It is a very good article with some interesting
insight in both C# and .NET runtime.

But I do not like it if all programmer think
that they have to write one of the fancy solutions.

Unless one have special requirements the simple
solution is usually good enough and make it a lot
easier for people to read the code.

Arne
Sep 12 '06 #4
Arne Vajhøj <ar**@vajhoej.dkwrote:
Brian Gideon wrote:
The following article describes what's required in detail and offers
other suggestions as well.

http://www.yoda.arachsys.com/csharp/singleton.html
It is a very good article with some interesting
insight in both C# and .NET runtime.

But I do not like it if all programmer think
that they have to write one of the fancy solutions.

Unless one have special requirements the simple
solution is usually good enough and make it a lot
easier for people to read the code.
But interestingly, the solution you've just proposed is:

private static Singlton instance = null;
private static object mylock = new object();
public static Singlton Instance
{
get {
lock(mylock)
{
if(instance == null)
{
instance = new Singlton();
}
}
return instance;
}
}

I think the following is simpler:

private static Singleton instance = new Singleton();
public static Singlton Instance
{
get
{
return instance;
}
}

That's just as lazy *unless* you call other static members on the type
before accessing the singleton, at which point I think we're into
"special requirements".

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Sep 12 '06 #5
Jon Skeet [C# MVP] wrote:
Arne Vajhøj <ar**@vajhoej.dkwrote:
>But I do not like it if all programmer think
that they have to write one of the fancy solutions.

Unless one have special requirements the simple
solution is usually good enough and make it a lot
easier for people to read the code.

But interestingly, the solution you've just proposed is:

private static Singlton instance = null;
private static object mylock = new object();
public static Singlton Instance
{
get {
lock(mylock)
{
if(instance == null)
{
instance = new Singlton();
}
}
return instance;
}
}

I think the following is simpler:

private static Singleton instance = new Singleton();
public static Singlton Instance
{
get
{
return instance;
}
}

That's just as lazy *unless* you call other static members on the type
before accessing the singleton, at which point I think we're into
"special requirements".
It is simpler and sufficient in most cases.

Which makes it good by definition in my book.

So I can follow your argument.

The only con I can see is that it is a bit different than GoF and C++
programmer will feel uncomfortable about it.

Arne
Sep 12 '06 #6
May as well toss more wood on. Here are two other methods. The first is
probably the easiest to remember, however it does require your singleton can
handle multiple instances for a short time (only 1 will ever be used
however). This method is can also be seen inside the framework. The second
method solves that issue by using a lock in the slow path. Neither method
takes a lock in the fast path.

public sealed class Singleton
{
private static Singleton instance;
private static readonly object syncRoot = new object();

private Singleton()
{
Console.WriteLine("Created Singleton.");
}

/// <summary>
/// This is a fast and easy to remember way to create a singleton.
However, your singleton *must be able to survive
/// multiple instances for a short time. Only 1 will every be "seen"
by user code however.
/// </summary>
/// <returns></returns>
public static Singleton Create1()
{
// This is a simple and fast double-checked locking pattern that
works. Also note instance does not
// need to be volatile. The Interlocked operation does not
block nor does it transition to kernel mode.

if (instance == null)
Interlocked.CompareExchange(ref instance, new Singleton(),
null);
return instance;

/*
* We could rewrite this as below to show why multiple
Singletons could be created.
* 1 or more threads could race passed the if test and each
would create another instance. Only the first
* we be used however and the other(s) will be collected. This
is why the singleton must be able to handle
* multiple instances for some time.
*
* if (instance == null )
* {
* Singleton s = new Singleton();
* Interlocked.CompareExchange(ref instance, s, null);
* }
* return instance;
*/
}

/// <summary>
/// This method is slightly more complex, but does guarantee only 1
instance will ever be created. The fast path is still a single "if" test
/// and takes no locks or Interlocked operations.
/// The lock is used for exclusive access to the block, not to
provide a memory barrier. The Interlocked.Exchange provides the
/// memory barrier and guarantees "instance" is always "seen"
correctly by other threads.
/// </summary>
/// <returns></returns>
public static Singleton Create2()
{
if (instance == null)
{
lock (syncRoot) // Exclusive lock to ensure we only create 1
instance of Singleton.
{
// Test again so that we don't run Interlocked again and
create another Singleton.
if (instance == null)
Interlocked.Exchange(ref instance, new Singleton());
}
}
return instance;
}
}

--
William Stacey [MVP]

"Arne Vajhøj" <ar**@vajhoej.dkwrote in message
news:odGNg.37751$_q4.34234@dukeread09...
| DBC User wrote:
| Does any one know how to implment a singlton in c#. I have done the
| implementation but I ran in to "Double-checked locking alert"
| implemenation and not sure how to implement it. Or let me put it this
| way, what is the equivalent of the following java code to resolve the
| double-checked locking alert???
| >
| private volatile static Singlton uniqueInstance
| >
| public static Singlton getInstance()
| {
| if (uniqueInstance == null)
| {
| synchornized(Singlton.class) { <-- how can we do this in c#
| if (uniqueInstance == null){
| uniqueInstance = new Singlton();
| }
| }
| }
| }
|
| private static Singlton instance = null;
| private static object mylock = new object();
| public static Singlton Instance
| {
| get {
| lock(mylock)
| {
| if(instance == null)
| {
| instance = new Singlton();
| }
| }
| return instance;
| }
| }
|
| is what I would call the canonical form.
|
| NB: Double locking does not work properly in Java and last
| time I read the verdict was that it did not work in .NET
| either (just works accidentally on x86 platform).
|
| Arne
Sep 13 '06 #7

Arne Vajhøj wrote:
private static Singlton instance = null;
private static object mylock = new object();
public static Singlton Instance
{
get {
lock(mylock)
{
if(instance == null)
{
instance = new Singlton();
}
}
return instance;
}
}

is what I would call the canonical form.

NB: Double locking does not work properly in Java and last
time I read the verdict was that it did not work in .NET
either (just works accidentally on x86 platform).

Arne
Arne,

It may work on x86 because that architecture has a relatively strong
memory model. But, remember, we don't code against x86, IA64, etc.
Instead we code against the CLR memory model which is weaker. So if it
works by accident then it's because the JIT compiler wasn't as
aggressive as the CLR specification allows in whatever version of the
framework was used. Change version of the framework and you may start
noticing problems.

I *think* double-checked locking does work in .NET if the volatile
keyword is used on the instance variable. At least that's what Vance
Morrison, et al. say.

Brian

Sep 13 '06 #8
Brian Gideon wrote:
Arne Vajhøj wrote:
>NB: Double locking does not work properly in Java and last
time I read the verdict was that it did not work in .NET
either (just works accidentally on x86 platform).
It may work on x86 because that architecture has a relatively strong
memory model. But, remember, we don't code against x86, IA64, etc.
Instead we code against the CLR memory model which is weaker. So if it
works by accident then it's because the JIT compiler wasn't as
aggressive as the CLR specification allows in whatever version of the
framework was used. Change version of the framework and you may start
noticing problems.
As I understand it the cause is at Intel not the JIT compiler
writer. Meaning that no framework upgrade will ever change it
on x86.

I may be wrong though. I am not a memory model expert. But that
is how I have read the writing about the topic.
I *think* double-checked locking does work in .NET if the volatile
keyword is used on the instance variable. At least that's what Vance
Morrison, et al. say.
True.

Arne
Sep 13 '06 #9
| I *think* double-checked locking does work in .NET if the volatile
| keyword is used on the instance variable. At least that's what Vance
| Morrison, et al. say.

In his article, I think he said it does work in 2.0 without volatile, but
not ECMA.
http://msdn.microsoft.com/msdnmag/is.../MemoryModels/
http://www.bluebytesoftware.com/blog...1e3992bf6.aspx
http://msdn.microsoft.com/library/de...tondespatt.asp

--
William Stacey [MVP]

Sep 13 '06 #10
Arne Vajhøj <ar**@vajhoej.dkwrote:
That's just as lazy *unless* you call other static members on the type
before accessing the singleton, at which point I think we're into
"special requirements".
It is simpler and sufficient in most cases.

Which makes it good by definition in my book.

So I can follow your argument.

The only con I can see is that it is a bit different than GoF and C++
programmer will feel uncomfortable about it.
That just shows that the idiomatic way to implement a pattern (or even
how to tackle a problem) varies by language/platform - a very important
lesson.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Sep 13 '06 #11

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

Similar topics

9
by: Anon Email | last post by:
Hi people, I'm learning about header files in C++. The following is code from Bartosz Milewski: // Code const int maxStack = 16; class IStack
12
by: Daedalus.OS | last post by:
Ok first I'm pretty new to OOP, so my question may sound stupid to some of you. If the only answer you can provide is "get a book about OOP" then don't loose your time and mine cause it's already...
29
by: Enrico `Trippo' Porreca | last post by:
Both K&R book and Steve Summit's tutorial define a getline() function correctly testing the return value of getchar() against EOF. I know that getchar() returns EOF or the character value cast to...
52
by: lovecreatesbeauty | last post by:
Why the C standard committee doesn't provide a standard implementation including the C compiler and library when the language standard document is published? C works on the abstract model of low...
4
by: DBC User | last post by:
I have a class with bunch of static methods. I could regourp all the static methods into seperate 3 or 4 classes. I was thinking about using Singlton pattern for all these 4 classes so that it...
20
by: Luc Kumps | last post by:
(Sorry about the previous post, it got transmitted before it was complete) We try to separate implementation and interface defintions, but we run into a problem. I hope the guru's can solve this,...
0
by: anto.anish | last post by:
Hi , Since, i did not want to write instantiations in Source file of all template methods for various different datatypes that my client might use, i choose to write implementation of template...
1
by: anto.anish | last post by:
Hi , Since, i did not want to write explicit instantiations in Source file of all template methods for various different datatypes that my client might use, i choose to write implementation of...
173
by: Ron Ford | last post by:
I'm looking for a freeware c99 compiler for windows. I had intended to use MS's Visual C++ Express and use its C capability. In the past with my MS products, I've simply needed to make .c the...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
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
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?

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.