473,324 Members | 2,246 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,324 software developers and data experts.

Thread safety ??

This doubt is regarding synchronisation question in Singleton pattern code
of C#

I had created a class as

public sealed class SecuriteManager
{
private static volatile SecurityManager instance;
private static object syncRoot = new Object();

private SecurityManager() { }

public static SecurityManager GetInstance
{
get{
if(null == instance){
lock(syncRoot){
if (instance == null)
instance = new SecurityManager();
}
}
return instance;
}
}

public bool IsAllowed(string UserName)
{
//A very long process here.
//For example access to a webservice which might take 3 seconds.
//HttpContext.Current.Session[UserName] = returnValueFromWebservice;
}
}
Now when 2 users access IsAllowed at the same time, is the process thread
safe ?
Or should I use lock for each call in my function as

public bool IsAllowed(string UserName)
{
lock(syncRoot)
{
//A very long process here.
//For example access to a webservice which might take 3 seconds.
//HttpContext.Current.Session[UserName] = returnValueFromWebservice;
}
}

Please suggest.
Jul 21 '05 #1
10 1471
Support <an*******@discussions.microsoft.com> wrote:
This doubt is regarding synchronisation question in Singleton pattern code
of C#

I had created a class as

public sealed class SecuriteManager
{
private static volatile SecurityManager instance;
private static object syncRoot = new Object();

private SecurityManager() { }

public static SecurityManager GetInstance
{
get{
if(null == instance){
lock(syncRoot){
if (instance == null)
instance = new SecurityManager();
}
}
return instance;
}
}
Any reason to use this complicated pattern rather than a simple one as
specified on

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

?
public bool IsAllowed(string UserName)
{
//A very long process here.
//For example access to a webservice which might take 3 seconds.
//HttpContext.Current.Session[UserName] = returnValueFromWebservice;
}
}
Now when 2 users access IsAllowed at the same time, is the process thread
safe ?


Well, that depends on what IsAllowed *actually* does. Two threads will
certainly be able to call it at the same time, but for many things
that's just fine. If, on the other hand, IsAllowed needs to read and
write some variables from the singleton, it may *not* be threadsafe.

Put it this way: being part of a singleton isn't relevant here. If it
would normally be okay for two threads to execute your method at a
time, that's fine - otherwise you'll need locking just as you would
elsewhere.

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

You should take a look at Jon Skeet article about singleton in
http://www.yoda.arachsys.com/csharp/singleton.html It explain in details how
to make it thread safe in the more efficient way.

Regarding your IsAllowed method, as long as you don't use any instance
variable you are fine, if you use an instance variable you should take care
of sync. the access to it.

Cheers,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation
"Support" <an*******@discussions.microsoft.com> wrote in message
news:et**************@TK2MSFTNGP09.phx.gbl...
This doubt is regarding synchronisation question in Singleton pattern code
of C#

I had created a class as

public sealed class SecuriteManager
{
private static volatile SecurityManager instance;
private static object syncRoot = new Object();

private SecurityManager() { }

public static SecurityManager GetInstance
{
get{
if(null == instance){
lock(syncRoot){
if (instance == null)
instance = new SecurityManager();
}
}
return instance;
}
}

public bool IsAllowed(string UserName)
{
//A very long process here.
//For example access to a webservice which might take 3 seconds.
//HttpContext.Current.Session[UserName] = returnValueFromWebservice; }
}
Now when 2 users access IsAllowed at the same time, is the process thread
safe ?
Or should I use lock for each call in my function as

public bool IsAllowed(string UserName)
{
lock(syncRoot)
{
//A very long process here.
//For example access to a webservice which might take 3 seconds.
//HttpContext.Current.Session[UserName] = returnValueFromWebservice; }
}

Please suggest.

Jul 21 '05 #3
I can't see anything in that pseudo-code worth looking.

If the method isn't accessing shared resources, there's no reason for
locking. The HttpContext.Current will be unique for each user who sent a
HTTP request to your application and aren't shared between users.

Also, for just reading there's seldom any need for locking, if the object
isn't written to from some other thread in your application.

--
Patrik Löwendahl [C# MVP]
www.cshrp.net - "Elegant code by witty programmers"

"Support" <an*******@discussions.microsoft.com> wrote in message
news:et**************@TK2MSFTNGP09.phx.gbl...
This doubt is regarding synchronisation question in Singleton pattern code
of C#

I had created a class as

public sealed class SecuriteManager
{
private static volatile SecurityManager instance;
private static object syncRoot = new Object();

private SecurityManager() { }

public static SecurityManager GetInstance
{
get{
if(null == instance){
lock(syncRoot){
if (instance == null)
instance = new SecurityManager();
}
}
return instance;
}
}

public bool IsAllowed(string UserName)
{
//A very long process here.
//For example access to a webservice which might take 3 seconds.
//HttpContext.Current.Session[UserName] = returnValueFromWebservice; }
}
Now when 2 users access IsAllowed at the same time, is the process thread
safe ?
Or should I use lock for each call in my function as

public bool IsAllowed(string UserName)
{
lock(syncRoot)
{
//A very long process here.
//For example access to a webservice which might take 3 seconds.
//HttpContext.Current.Session[UserName] = returnValueFromWebservice; }
}

Please suggest.

Jul 21 '05 #4
>private static volatile SecurityManager instance;

In addition to the other comments, should you wish to continue with a singleton class then the volatile keyword is not needed.

Phil&hellip;
Jul 21 '05 #5
Phil Jenson <ph**@REMOVETHIS.jenson.co.uk> wrote:
>private static volatile SecurityManager instance;


In addition to the other comments, should you wish to continue with a
singleton class then the volatile keyword is not needed.


Yes it is - otherwise the double-checked locking he's got isn't thread-
safe. It's not the nicest way of achieving thread-safety in the first
place, but at least it *is* safe at the moment.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Jul 21 '05 #6
Jon
Yes it is - otherwise the double-checked locking he's got isn't thread-


Thanks for the feedback. Will look into this further.

Phil..


Jul 21 '05 #7
Didn't we conclude before that even with volatile this may not be safe? The
null check is still disturbing as I think thread2 can see a "not" null ref
and the instance still not fully constructed by thread1 yet, and possibly
other complicated scenarios that I have forgot. As there was still some
question on this and CLR memory model, I thought explicit lock (then check)
or static construction were the safe ways for now? Or has someone proved
this works in all cases?

--
William Stacey, MVP

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP***********************@msnews.microsoft.co m...
Phil Jenson <ph**@REMOVETHIS.jenson.co.uk> wrote:
>private static volatile SecurityManager instance;


In addition to the other comments, should you wish to continue with a
singleton class then the volatile keyword is not needed.


Yes it is - otherwise the double-checked locking he's got isn't thread-
safe. It's not the nicest way of achieving thread-safety in the first
place, but at least it *is* safe at the moment.

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


Jul 21 '05 #8
William Stacey [MVP] <st***********@mvps.org> wrote:
Didn't we conclude before that even with volatile this may not be safe?
I don't *think* so.
The null check is still disturbing as I think thread2 can see a "not" null ref
and the instance still not fully constructed by thread1 yet, and possibly
other complicated scenarios that I have forgot.
It shouldn't do - the write to the volatile variable should have made
sure that everything's been fully constructed before thread2 can see
it.
As there was still some
question on this and CLR memory model, I thought explicit lock (then check)
or static construction were the safe ways for now? Or has someone proved
this works in all cases?


I think the discussion from a while ago was trying to find a way of
avoiding it being volatile.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Jul 21 '05 #9
> It shouldn't do - the write to the volatile variable should have made
sure that everything's been fully constructed before thread2 can see
it.


True, but I think that is any writes before the read, but does not mean all
writes have completed yet. So internal may write 1 as first step, then
thread switch happens, then finishes writing ref var (I saw this doc'd
somewhere.) Also, the ref may get written and read correctly, but fields
inside the object may not be set before a thread switch and the other thread
runs with a ref that is not fully constructed yet. I think you can force
this to happen with a bit of playing. Cheers!

--
William Stacey, MVP
Jul 21 '05 #10
William Stacey [MVP] <st***********@mvps.org> wrote:
It shouldn't do - the write to the volatile variable should have made
sure that everything's been fully constructed before thread2 can see
it.


True, but I think that is any writes before the read, but does not mean all
writes have completed yet. So internal may write 1 as first step, then
thread switch happens, then finishes writing ref var (I saw this doc'd
somewhere.) Also, the ref may get written and read correctly, but fields
inside the object may not be set before a thread switch and the other thread
runs with a ref that is not fully constructed yet. I think you can force
this to happen with a bit of playing. Cheers!


No, the point of the volatile write is that all "pending" writes happen
before it.

From the spec:

<quote>
A volatile write has "release semantics" meaning that the write is
guaranteed to happen after any memory references prior to the write
instruction in the CIL instruction sequence.
</quote>

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

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

Similar topics

4
by: Jonathan Burd | last post by:
Greetings everyone, Here is a random string generator I wrote for an application and I'm wondering about the thread-safety of this function. I was told using static and global variables cause...
9
by: Alexander Fleck | last post by:
Hi, I' ve to make a software module thread safe. I know how to realize that and what' re the main topics of thread safety. But I don' t know how thread safety can be tested. I read about a test...
4
by: The Crow | last post by:
for example i have static readonly SqlParameter and i want to clone them at runtime. as clone operation will not write to SqlParameter object, just reading, should i lock that object during read...
22
by: Brett | last post by:
I have a second thread, t2, that errors out and will stop. It's status is then "Stopped". I try to start t2 from thread 1, t1, by checking If t2.threadstate = "Stopped" Then t2.start() ...
4
by: Warren Sirota | last post by:
Hi, I've got a method that I want to execute in a multithreaded environment (it's a specialized spider. I want to run a whole bunch of copies at low priority as a service). It works well running...
6
by: fniles | last post by:
I am using VB.NET 2003 and a socket control to receive and sending data to clients. As I receive data in 1 thread, I put it into an arraylist, and then I remove the data from arraylist and send it...
1
by: paul.hester | last post by:
Hi all, All of the classes in my DAL are static, with constants defining the stored procedures and parameters. I've been having some problems with my site which makes me wonder if there's a...
13
by: arun.darra | last post by:
Are the following thread safe: 1. Assuming Object is any simple object Object* fn() { Object *p = new Object(); return p; } 2. is return by value thread safe?
0
by: Graham Wideman | last post by:
Folks: Can anyone tell me what controls php's "thread safety" feature? I have an installation where phpinfo() is showing Thread safety: enabled, whereas I need it disabled in order to work...
13
by: Henri.Chinasque | last post by:
Hi all, I am wondering about thread safety and member variables. If I have such a class: class foo { private float m_floater = 0.0; public void bar(){ m_floater = true; }
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
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: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
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...

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.