Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable sharing inside static method

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)=?
like image 437
Krishna Avatar asked Aug 03 '10 19:08

Krishna


People also ask

Can static variables be shared?

No. It is not possible. Each process is in a separate address space.

Can we use the static variables inside static methods?

we can't declare Static variable inside the method or constructor. Because static variables are class level variables. Most of the programmer says "YES". But we can't declare Static variable inside the method or constructor.

Can we print normal variable inside static function?

No, the php interpreter would throw an error.

Are static variables shared by all objects?

As in the concept of static data, all objects of the class in static functions share the variables. This applies to all objects of the class.


2 Answers

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.

like image 116
Jon Skeet Avatar answered Sep 22 '22 22:09

Jon Skeet


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

like image 32
Justin Avatar answered Sep 24 '22 22:09

Justin