Some doubts about volatile and Atomic classes?

前端 未结 2 1142
野性不改
野性不改 2021-01-21 00:18

i am going thru Java threads book. I came across this statement

Statement 1:- \"volatile variables can be safely used only for single load or store oper

2条回答
  •  说谎
    说谎 (楼主)
    2021-01-21 01:06

    Statement 1:- "volatile variables can be safely used only for single load or store operation and can't be applied to long or double variales. These restrictions make the use of volatile variables uncommon"

    What?! I believe this is simply flat-out wrong. Maybe your book is out of date.

    Statement 2:- "A Volatile integer can not be used with the ++ operator because ++ operator contains multiple instructions.The AtomicInteger class has a method that allows the integer it holds to be incremented atomically."

    Exactly what it says. The ++ operator actually translates to machine code like this (in Java-like pseudocode):

    sync_CPU_caches();
    int processorRegister = variable;
    processorRegister = processorRegister + 1;
    variable = processorRegister;
    sync_CPU_caches();
    

    This is not thread-safe, because even though it has a memory barrier, and reads atomically, and writes atomically, it is not guaranteed that you won't get a thread switch in the middle, and processor registers are local to a CPU core (think of them as like "local variables" inside the CPU core). But an AtomicInteger is thread-safe - it probably is implemented using special machine code instructions such as compare-and-swap.

提交回复
热议问题