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)=?
No. It is not possible. Each process is in a separate address space.
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.
No, the php interpreter would throw an error.
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.
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.
The threads would not overwrite each other's values, since the variables are entirely on the stack. Each thread has a separate stack.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With