views:

206

answers:

3

Given that a static variable of a class takes only one memory location, is it shared by all threads of process? Or is one memory location for such a variable created for each of the running threads?

Also, if all threads share the same memory location, how can we ensure mutual exclusion?

+3  A: 

A static variable of a class in a process will be shared between every thread contained in that process.

You can verify this by creating a simple class with a public static field, and then start up a couple of Threads and have them increment the variable and see what happens.

If you want to ensure mutual exclusion you can make the variable private, and only allow access to it through methods that are defined using the synchronized keyword.

class Foo {

    private static int aVariable = 0;

    public static synchronized void increment() { aVariable++; }
    public static synchronized int getVariable() { return aVariable; }

}
jjnguy
Is that by specification or just how certain JVMs do it?
NickLarsen
The nature of a thread is to share memory. It is specified in the language. I don't have a reference to it though.
jjnguy
+2  A: 

It's shared between threads, you can ensure mutual exclusion by making the variable itself private and only accessing it using a synchronized accessor.

psyho
+1  A: 

Static fields are shared by all threads. There is only one copy of the field in the JVM.

To control access to a static field, you can use the synchronized keyword or use the concurrency utilities provided by JDK 5.0.

There is a way to create a variable that has one instance per thread, see ThreadLocal.

Ken Liu