- volatile variables are stored in main memory, and never optimized away (for instance, storing in the CPU cache).
- 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.
- 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.
volatile in Java
最新推荐文章于 2023-08-21 20:50:55 发布