views:

112

answers:

4

I have a question about the variables inside the static method. Does the variables inside the static method shares the same memory location or would the have separate memory?

Let me make an example.

public class XYZ
{
    Public Static int A(int value)
    {
      int b = value;
      return b;
    }
}

If 3 different user calls execute the method A

XYZ.A(10);
XYZ.A(20);
XYZ.A(30);

at the same time. What would be the return values of each call?

XYZ.A(10)=?
XYZ.A(20)=?
XYZ.A(30)=?
+3  A: 

The threads would not overwrite each other's values, since the variables are entirely on the stack. Each thread has a separate stack.

Justin
+5  A: 

They're still local variables - they're not shared between threads. The fact that they're within a static method makes no difference.

If you used a static variable as the intermediate variable, that would be unsafe:

public class XYZ
{
    // Don't do this! Horribly unsafe!
    private static int b;
    public static int A(int value)
    {
        b = value;
        return b;
    }
}

Here, all the threads would genuinely be using the same b variable, so if you called the method from multiple threads simultaneously, thread X could write to b, followed by thread Y, so that thread X ended up returning the value set by thread Y.

Jon Skeet
A: 

This is not a thread safe method but all automatic varibles are thread safe automaticly since ever time the function is called you get a new stack frame. All of the locals are created upon entry to the function and destroed upon exit. As said above if you had used static storage then you would get unexpected results.

rerun
+1  A: 

No, they do not share the same space in memory. For your call, they would return, (in the order you listed): 10, 20, and 30.

Honestly, with your code this would be true in any case (since you're just assigning a value, not doing anything with it) but consider:

Class XYZ
{
   public static int A (int value)
   {
      b += value;  \\Won't compile: b not initialized
      return b;
   }
}

Or

Class XYZ
{
   public static int A (int value)
   {
      int b = 0;  \\Initialized 'b' for each call
      b += value;  
      return b;
   }
}

Since a Static method cannot access an instance variable (at least, not without having a reference to an instance), there is no way to initialize a variable once in a static method without it being reinitialized every time the code is called. To allow a static method to change a variable, you would need to pass in two values to operate on eachother.

AllenG
Unless you had a static variable, of course.
Jon Skeet
True. Use them so infrequently I forgot about them... for this specific question, that doesn't seem like an issue, however.
AllenG