Is there any point in using a volatile long?

前端 未结 3 1881
情深已故
情深已故 2020-12-04 13:15

I occasionally use a volatile instance variable in cases where I have two threads reading from / writing to it and don\'t want the overhead (or potential deadlo

3条回答
  •  一生所求
    2020-12-04 13:42

    "volatile" serves multiple purposes:

    • guarantees atomic writes to double/long
    • guarantees that when a thread A sees change in volatile variable made by thread B, thread A can also see all other changes made by thread B before the change to volatile variable (think setting the number of used cells in array after setting the cells themselves).
    • prevents compiler optimization based on assumption that only one thread can change the variable (think tight loop while (l != 0) {}.

    Is there more?

提交回复
热议问题