Variable sharing inside static method

2020-08-17 05:50发布

问题:

I have a question about the variables inside the static method. Do the variables inside the static method share the same memory location or would they have separate memory?

Here is 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)=?

回答1:

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.



回答2:

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



回答3:

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.



回答4:

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.