Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is returning a reference from static method thread-safe?

I have a class:

class PrintStringDataBuilder
{
    PrintStringDataBuilder() { }
    public static GetInstance()
    {
        return new PrintStringDataBuilder();
    }

    //other class methods and fields, properties
}

Accessed from client Code as:

PrintStringDataBuilder instance = PrintStringDataBuilder.GetInstance();

Is above call thread-safe?

Edit: Just trying to avoid writing PrintStringDataBuilder builder = new PrintStringDataBuilder(); multiple times in asp.net mvc web app. There are no other static methods, static fields or static properties in the PrintStringDataBuilder class.

like image 854
mxasim Avatar asked Apr 27 '12 17:04

mxasim


1 Answers

Yes? Without knowing the internals of the constructor of that class, you could say that calling GetInstance() was thread safe. Any methods on that instance would not be guaranteed to be thread safe though, particularly since you didnt present any of those methods.

This is simply known as the factory pattern.

EDIT: If you are trying to return a singleton, you can do it like so:

.NET 4+

private static Lazy<PrintStringDataBuilder> _instance = new Lazy<PrintStringDataBuilder>(() =>
  {
      return new PrintStringDataBuilder();
  });

public static PrintStringDataBuilder GetInstance()
{
    return _instance.Value;
}

.NET 3.5 and below

private static PrintStringDataBuilder _instance = null;
private static object _lockObject = new object();

public static PrintStringDataBuilder GetInstance()
{
    if(_instance == null)
    {
         lock(_lockObject)
         {
              if(_instance == null)
                 _instance = new PrintStringDataBuilder();
         }
    }

    return _instance;
}
like image 115
Tejs Avatar answered Nov 07 '22 17:11

Tejs