1

Yes currently I am getting my feet wet on C# language specifications and possibly decipherable tutorials. I read multiple questions and answers/articles that talks about thread-safe singleton classes.

Here are the posts I already explored:

The more I read the more I get drown with the information. Can someone direct me to get a better understanding of

1) why do developers care about thread-safety?

2) how static class/singleton class are determined as not thread safe? (Sample code/sample tutorial to try out would be great as I love to learn these basics properly)

Community
  • 1
  • 1
aspiring
  • 1,557
  • 2
  • 20
  • 43
  • 3
    It's an *implementation* which is safe or unsafe - not "singletons in general". – Jon Skeet Feb 18 '13 at 12:38
  • 1
    Probably the best explanation: [Implementing the Singleton Pattern in C# by Jon Skeet](http://csharpindepth.com/articles/general/singleton.aspx) – Habib Feb 18 '13 at 12:39
  • 4
    `"why do developers care about thread-safety?"` - Because they like their code like they like thAsynchronous.eir punchlines. – David Feb 18 '13 at 12:39
  • @David This is the best explanation I've seen. Ever. – Theodoros Chatzigiannakis Feb 18 '13 at 12:48
  • @David `thAsynchronous.eir punchlines` that is a bit beyond my hat. Do you mean Asynchoronous? I just want to know a the right picture of the risk that is brought by static classes in threading environment. An example would be much appreciated. – aspiring Feb 18 '13 at 12:50
  • @Habib and JonSkeet thank you for the article - I am taking it up. Sure will have more question. But if any of you can kindly provide me an example that explains the risk that is brought by static classes in threading environment, then that would be excellent. – aspiring Feb 18 '13 at 12:52

4 Answers4

1

Why static class and singleton pattern class are not thread safe?

And who said all singleton pattern classes are not thread safe? Plenty of ways to make a class thread safe

See here: http://csharpindepth.com/Articles/General/Singleton.aspx

Aniket Inge
  • 25,375
  • 5
  • 50
  • 78
1
  1. When you want to increase your performance you will encouter situations where you will have to use threading, so when making your application thread-safe you avoid some race situation.

  2. Static and Singleton classes will share there values for the entire instance of your application. When you access that object from multiple threads you can reuse or overwrite variables that's also being used by another object. This will result in some very strange output and it's hard sometimes to findwhat is going on since it aint easy to simulate this in test cases. You can implement a lock in your methodes to introduce thread safety in these classes

JMan
  • 2,611
  • 3
  • 30
  • 51
  • Isn't whole point of having Static/Singleton class (with non-intantiating methods) to make sure re-usable components behaviours are well safe/encapsulated? For e.g. In a threading environment, multiple components can implements static methods in a Static class/Interface. Like 100 users keep on login into database system/ATM system. How can that be not thread safe? :) Can you clarify a bit further. – aspiring Feb 18 '13 at 12:47
  • That's indead the use. What i wanted to explain is that the values contained by static and singleton classes are shared for the entire application. So whenever you store a value in a static or Singleton you will need to make sure thats what you want for that variable to be for your entire application. – JMan Feb 18 '13 at 12:52
  • If you add 2 method to a singletone class int he first you set a variable, and in the second one you do some function using that first variable. You could encounter a situation where the variable is set by thread A, Then set by thread B, the method is performed for thread A, then for B. For the method for thread A will produce an invalid result – JMan Feb 18 '13 at 12:54
  • But if I look at from Static (interface) point of view then that has no idea of what data the components(objects) are using since it has no implementation. And each of class objects are individually implement static methods in their respective class. Perhaps what your saying is better applied for a Singleton class. But not for a static class. Am I on the right track? :) – aspiring Feb 18 '13 at 12:57
  • A static class is very different from an interface. An interface has no implementation. But a static class does. You can have the same issues on a static class as you have on a singleton. You variables will be Private Statics – JMan Feb 18 '13 at 13:00
1

There are various versions of Singleton Pattern, some are thread safe and some are not:

You can go through the article by Jon Skeet on these patterns.

http://csharpindepth.com/articles/general/singleton.aspx

Thread safety is important to ensure you are playing with right values.

In the following example two Threads call a method which means to set value x to 25 by multiplying it by 5 if it was 5.

Now there can be a scenario that Main thread enter the if block while x was 5, and starts to executes doSomething method, then comes SecondThread, enters the if loop while x was still 5. Then Main thread A will modify x to 25, and then SecondThread will modify it to 125.

So here we need some sort of synchronization so that not more than one thread could modify x at the same time.

private int x = 5;

        private void dosomething()
        {
        }
        private void multXby5if5() // Should make x =25, by multiplying 5  if it was 5, finally x should be 25
        {

            if (x == 5) // State A: SecondThread reaches here while x is still 5
            {
                dosomething(); //State A : Main thread reaches here

                x = x*5; // State B: Then Main Thread comes and makes x =25, then later SecondThread will come make x*5=25*5=125,

            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Thread tr = new Thread(multXby5if5);
            tr.Name = "SecondThread";
            multXby5if5();
            tr.Start();
        }

This is not the best of examples, but I hope it will help you.

Igoy
  • 2,942
  • 22
  • 23
  • +1 for the article. My question is to get a better picture of what is really happening in these classes in a thread environment. Although your last sentence is a one-liner still along the answer I am looking for. Can you please provide me nooby-proof example article? :) – aspiring Feb 18 '13 at 13:05
  • Thank you. I am trying out various articles and your tutorial too. Allow me sometime to get back. – aspiring Feb 18 '13 at 16:41
0

Generally speaking singleton pattern is not thread safe because every time an instance is requested by a thread the container hands over the same instance. This can result to multiple thread having the same instance.

But there are ways to make your Singleton thread safe.

Abdullah Khan
  • 12,010
  • 6
  • 65
  • 78