开发者

Does a static variable takes only one memory location for all running threads?

Given that a static variable of a class takes only one me开发者_StackOverflow社区mory 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?


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; }

}


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜