Thread safety for static variables

前端 未结 4 1461
天涯浪人
天涯浪人 2021-02-19 03:12
class ABC implements Runnable {
    private static int a;
    private static int b;
    public void run() {
    }
}

I have a Java class as above. I hav

4条回答
  •  广开言路
    2021-02-19 03:40

    I'd like to add some details about the answer to this question.

    Firstly, the OP is asking about :

    How can I make these operations thread safe?

    Before answer this question, we need to reach the consistency about what is thread safe. The definition I like mostly is that from "Java Concurrency In Practice" and it's

    A class is thread safe if it behaves correctly when accessed from multiple threads, regardless of the scheduling or interleaving of the execution of those threads by the runtime environment, and with no additional synchronization or other coordination on the part of the calling code.

    If you agree with the definition, it means we reach the consistency before further discussion. Let's return to the operations you meant, it's a++ and b++, after the increment, you will put them into a HashTable.

    For the a++ operation, it's not really a single operation. It obeys the model of read modify write. As you can see, it actually contains three individual steps. Read the value, add one to it and save it back. If you have two threads read the variable a with value 1 at the same time, after the modifications and save back operations. The value will be 2, but it actually should be 3. To avoid this situation happen, like what others have suggested, you can use AtomicInteger instead of int type directly. The AtomicInteger will guarantee some operations like increment to execute atomically. That means, the read modify write operations can't be divided and will be executed as one individual step.
    After that, the OP wants to save the value into a HashTable. The HashTable is a thread safe container, no other synchronization needed.
    Hope this clarification can help someone in other way. Thanks.

提交回复
热议问题