volatile in Java

  1. volatile variables are stored in main memory, and never optimized away (for instance, storing in the CPU cache).
  2. Once the volatile variables are changed, they would be visible to all users. this means that volatile variables are not cached, every access needs to be read directly from the physical memory.
  3. Atomic variables use low-level CPU operations. So the locking is delegated to the CPU, which is in notion much faster than what can be achieved in application-level locking. Because the application gets variables from the CPU, which might or might not read from the main memory (it could just read from the CPU cache), the added level abstraction can add overhead. After all, we need to get from the CPU, do some operations on them, and put them back in the CPU. The threads could all read from the CPU at the same time. If the CPU has some more efficient mechanisms to do atomic operations, we should allow the more efficient CPU to do its work.
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章