473,756 Members | 6,028 Online
Bytes | Software Development & Data Engineering Community
+ 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(strin g UserName)
{
//A very long process here.
//For example access to a webservice which might take 3 seconds.
//HttpContext.Cur rent.Session[UserName] = returnValueFrom Webservice;
}
}
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(strin g UserName)
{
lock(syncRoot)
{
//A very long process here.
//For example access to a webservice which might take 3 seconds.
//HttpContext.Cur rent.Session[UserName] = returnValueFrom Webservice;
}
}

Please suggest.
Jul 21 '05 #1
10 1506
Support <an*******@disc ussions.microso ft.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(strin g UserName)
{
//A very long process here.
//For example access to a webservice which might take 3 seconds.
//HttpContext.Cur rent.Session[UserName] = returnValueFrom Webservice;
}
}
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.co m>
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*******@disc ussions.microso ft.com> wrote in message
news:et******** ******@TK2MSFTN GP09.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(strin g UserName)
{
//A very long process here.
//For example access to a webservice which might take 3 seconds.
//HttpContext.Cur rent.Session[UserName] = returnValueFrom Webservice; }
}
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(strin g UserName)
{
lock(syncRoot)
{
//A very long process here.
//For example access to a webservice which might take 3 seconds.
//HttpContext.Cur rent.Session[UserName] = returnValueFrom Webservice; }
}

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.Cur rent 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*******@disc ussions.microso ft.com> wrote in message
news:et******** ******@TK2MSFTN GP09.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(strin g UserName)
{
//A very long process here.
//For example access to a webservice which might take 3 seconds.
//HttpContext.Cur rent.Session[UserName] = returnValueFrom Webservice; }
}
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(strin g UserName)
{
lock(syncRoot)
{
//A very long process here.
//For example access to a webservice which might take 3 seconds.
//HttpContext.Cur rent.Session[UserName] = returnValueFrom Webservice; }
}

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**@REMOVETHI S.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.co m>
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.co m> wrote in message
news:MP******** *************** @msnews.microso ft.com...
Phil Jenson <ph**@REMOVETHI S.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.co m>
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.co m>
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

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

Similar topics

4
6652
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 potential problems for thread-safety. So far, I'm only confused. I need a proper explanation for the concept so I can understand how to write thread-safe functions in the future. My apologies for posting a long routine.
9
2092
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 for web servers. These apps' re tested with a stress test. That doesn' t work for my module. I searched the web but didn' t find a solution that satisfies me. I think that thread safety errors don' t occur reproduceable and so they' re hard to test and...
4
2792
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 operations?
22
37748
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() However, this throws and error: System.Threading.ThreadStateException: Thread is running or terminated; it can not restart.
4
2570
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 as a single application. I was wondering if there is a "Thread-Safety Analysis Wizard"? I'm sure I'm grossly off-base with the following, so I'm prepared to be embarrassed. Please point me in the right direction!
6
3140
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 to the client. Before adding data to the arraylist, I check if the depth of the arraylist is longer than iMaxQueueDepth, and if it is, I clear the arraylist. Is it possible that while I am clearing the arraylist, the ThreadMain at the same time...
1
3635
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 thread safety issue. Are consts thread safe? Would the following example create any thread safety issues? Would you recommend using static readonly members instead of constants?
13
3602
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
4145
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 with xdebug.so. So far as I can tell, the options I used to configure php did not ask for thread-safety, and I also don't see any options to *dis*able thread-safety. Configure --help does show several threading-related options, but none for
13
11472
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
9255
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
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,...
0
9689
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
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...
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.