static methods and thread safety

G

Guest

Is a static method that uses local variables thread safe (eg in a web service)

In the following code assuming GetRandomValue() and DoSomethingElse() are thread safe, is the static method thread safe

public class Cach

public static int GetAValue(

int x = 0
x = GetRandomValue()
DoSomethingElse(x)
return x



The issue I think I need to understand is if there is only one instance of this method shared across all threads or one instance per thread. If there is only one instance shared across all threads then I assume there is only one instance of the local variable x and therefore this method is not thread safe

Comments pleas

Steve
 
M

Mattias Sjögren

If there is only one instance shared across all threads then I assume there is only one instance of the local variable x and therefore this method is not thread safe?

There will be one x variable on the stack every time you enter the
method. Plus each thread has its own stack.



Mattias
 
B

Bruno Jouhier [MVP]

This is thread safe: x is allocated on the stack and every thread has its
own stack.

The big deal is not really with static methods, but with static variables.
Static variables (and any object they may reference directly or indirectly)
may be accessed concurrently by several threads. So, you need to synchronize
access to static variables. But don't worry about local variables in static
methods.

Bruno.

Steve said:
Is a static method that uses local variables thread safe (eg in a web service)?

In the following code assuming GetRandomValue() and DoSomethingElse() are
thread safe, is the static method thread safe?
public class Cache
{
public static int GetAValue()
{
int x = 0;
x = GetRandomValue();
DoSomethingElse(x);
return x;
}
}

The issue I think I need to understand is if there is only one instance of
this method shared across all threads or one instance per thread. If there
is only one instance shared across all threads then I assume there is only
one instance of the local variable x and therefore this method is not thread
safe?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top