Does a static variable accept only one memory cell for all running threads?

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

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

+3
source share
3 answers

A staticvariable classin the process will be shared between each thread contained in this process.

, class public static, Threads , .

, , synchronized.

class Foo {

    private static int aVariable = 0;

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

}
+3

, , .

+2

. 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 for a thread, see ThreadLocal .

+1
source

Source: https://habr.com/ru/post/1730235/


All Articles