Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 390283
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 12, 20262026-05-12T15:56:58+00:00 2026-05-12T15:56:58+00:00

The following code is thread-safe as far as I can tell, with the caveat

  • 0

The following code is thread-safe as far as I can tell, with the caveat that I am not looking for a singleton pattern (I don’t care if multiple threads get different instances of MyObject as MyObject is immutable. After the potential contention among the concurrent threads that create multiple instances, subsequent threads will all get the same intance).

private static MyObject myObject;
...
public static MyObject GetMyObject()
{
    if (myObject == null)
    {
        myObject = new MyObject(...);
    }
    return myObject;
}

The following is clearly not thread-safe, since multiple threads could attempt to access the myObject field before it is completely initialized:

private static MyObject myObject;
...
public static MyObject GetMyObject()
{
    if (myObject == null)
    {
        myObject = new MyObject();
        myObject.Initialize(...);
    }
    return myObject;
}

Is the following thread-safe, or is the volatile keyword required on the myObject field? It looks safe as it stands, since the myObject field is not assigned until the object is fully initialized. But I’d be concerned that the JITter might be able to inline the LoadMyObject method and essentially reimplement it as the above code, which isn’t thread safe.

private static MyObject myObject;
...
private static MyObject LoadMyObject()
{
    MyObject myObject = new MyObject();
    myObject.Initialize(...);
    return myObject;
}

public static MyObject GetMyObject()
{
    if (myObject == null)
    {
        myObject = LoadMyObject();
    }
    return myObject;
}

The background to the above is that I want to refactor some multithreaded code, and replace calls to a constructor by calls to a factory method. And I want to know if doing so can break thread-safety.

EDIT

Just to reiterate, I don’t care if multiple instances of MyObject are created, only that there is no way to access an instance that is not completely initialized. As a concrete example, think of a readonly XmlDocument that is loaded with the contents of a configuration file. I want a static reference to the XmlDocument available in memory to avoid the overhead of loading from disk on every access. But I don’t care if two threads happen to run concurrently and both load the document from disk.

EDIT2

If I understand it correctly, the following statement from the C# Language Specification seems to imply that the JITter won’t reorder my code, so that my last sample should be thread-safe. Am I understanding correctly?

3.10 Execution order
…
Data dependence is preserved within a
thread of execution. That is, the
value of each variable is computed as
if all statements in the thread were
executed in original program order

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-12T15:56:58+00:00Added an answer on May 12, 2026 at 3:56 pm

    It’s safe in the sense that you will get a correctly initialised object, but several threads may create objects simultaneously, and a thread might return an object that a different thread just created.

    If the compiler inlines the method, it still won’t be the same as the first code. As the reference to the object is kept in a local variable until it’s initialised, it’s still safe.

    You can inline the method yourself, there is no need to have the code in a separate method to make it safe:

    public static MyObject GetMyObject() {
       if (myObject == null) {
          MyObject newObject = new MyObject();
          newObject.Initialize(...);
          myObject = newObject;
       }
       return myObject;
    }
    

    If you want to prevent that several objects are created by separate threads, you need to use a lock.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

The following class is not thread-safe (as proven in Proving the following code not
I have a dll with source code that is not thread safe yet. The
The following code is a simple thread game, that switches between threads causing the
In this thread some one commented that the following code should only be used
I have the following code in a Runnable that gets passed to a thread
Consider the following code: while(true) { someFunction(); Thread.sleep(1000); } What I want is that,
Let's say that I have the following code that's run in one thread of
I'm currently using the following code for thread-safe access of a variable. int gnVariable;
Background I am assuming the following code is completely thread safe: // Called from
Is the following code thread safe: THREAD A std::vector<std::string> myCopy; with_locked_mutex(m) { myCopy =

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.