1,105,208 Community Members

Static method returning a non-static class and thread safety?

Member Avatar
zachattack05
Posting Pro
592 posts since Dec 2009
Reputation Points: 56 [?]
Q&As Helped to Solve: 16 [?]
Skill Endorsements: 0 [?]
 
0
 

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?

Member Avatar
darkagn
Veteran Poster
1,199 posts since Aug 2007
Reputation Points: 279 [?]
Q&As Helped to Solve: 216 [?]
Skill Endorsements: 21 [?]
 
0
 

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!

Member Avatar
zachattack05
Posting Pro
592 posts since Dec 2009
Reputation Points: 56 [?]
Q&As Helped to Solve: 16 [?]
Skill Endorsements: 0 [?]
 
0
 

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

Question Answered as of 1 Year Ago by darkagn
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article