Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a static method share its local variables & what happens during concurrent usage from different threads?

C# Question - I'm trying to determine whether it is OK to use a static method where, within the method it does have some local variables it uses. Are the local variables "shared" across usages of the method? What happens for example if the static method is being called/used at the same time from different threads? Does one thread block until the other is complete etc?

Perhaps the generalised question is, in a threaded application, when should one "not" being using a static method?

like image 927
Greg Avatar asked Aug 13 '10 03:08

Greg


People also ask

Can static methods have local variables?

In Java, a static variable is a class variable (for whole class). So if we have static local variable (a variable with scope limited to function), it violates the purpose of static. Hence compiler does not allow static local variable.

Are static variables shared?

Static variables are shared among all instances of a class. Non static variables are specific to that instance of a class. Static variable is like a global variable and is available to all methods. Non static variable is like a local variable and they can be accessed through only instance of a class.

Is static variable same as local variable?

A static local variable is different from a local variable as a static local variable is initialized only once no matter how many times the function in which it resides is called and its value is retained and accessible through many calls to the function in which it is declared, e.g. to be used as a count variable.

Are local variables in static method thread safe?

Local variables are stored in each thread's own stack. That means that local variables are never shared between threads. That also means that all local primitive variables are thread safe.


1 Answers

Local variables within the method live on the stack and each thread has its own stack. Therefore it's safe for multiple threads to use the method.

However if the method itself uses static variables then you should use appropriate MT protection. Also external methods you may be calling need to be safe...

like image 200
seand Avatar answered Nov 17 '22 12:11

seand