Silly question I am sure, and I'm almost positive I know the answer to this, but, if I have a static method that has a return type that is a non-static class type, when the static method is executing and after the method has initialized the class to return (but has not returned it yet), without locking the method it IS thread safe since it is not using a shared object and if the static method is called in succession by many threads, each will return their own correct "version" of the class object, correct?

For example (this is really quick so just follow the general idea):

public class myClass
{
    int i;
    string s;

    public myClass ()
    {

    }
}

public class myOtherClass
{
    public myOtherClass()
    {

    }

    public static myClass myMethod(int i, string s)
    {
        myClass mc = new myClass();

        mc.i = i;
        mc.s = s;

        return mc;
    }
}

If multiple threads call myMethod() at the same time, is that thread safe? I would say yes. Anyone disagree?

Recommended Answers

All 2 Replies

Your method example creates a new instance of the myClass class EACH TIME it is called, and stores the value of the parameters in its own instance variables. This is thread-safe.

I'm not sure that ALL static methods are thread-safe though. It is possible to access static global variables that are potentially shared by multiple threads from within a static method.

I'm sure there are probably other ways in which a static method could be thread-unsafe but it's late here in Australia and I can't think of another example right now sorry!

Someone please correct me if I'm wrong!

That's kinda what I thought. Just wanted to make sure, I was doubting myself :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.