473,473 Members | 2,004 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

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 1475
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: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
1
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...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
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...
0
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...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.