当前位置:网站首页>看看volatile你深知多少
看看volatile你深知多少
2022-06-27 08:25:00 【C_x_330】
出于运行速率的考虑,java编译器会把经常经常访问的变量放到缓存(严格讲应该是工作内存)中,读取变量则从缓存中读。但是在多线程编程中,内存中的值和缓存中的值可能会出现不一致。volatile用于限定变量只能从内存中读取,保证对所有线程而言,值都是一致的。但是volatile不能保证原子性,也就不能保证线程安全
volatile关键字对任意单个volatile变量的的读写操作可以保证原子性,但类似于volatile++这种复合操作就无法保证原子性了。如果需要对这种复合操作保证原子性,最好用synchronized关键字。即synchronized保证三大性,原子性,有序性,可见性,volatile保证有序性,可见性,不能保证原子性。
总的来说: volatile的特性有
有序性,可见性
但是
新增
一旦一个共享变量(类的成员变量、类的静态成员变量)被volatile修饰之后,那么就具备了两层语义:1)保证了不同线程对这个变量进行操作时的可见性,即一个线程修改了某个变量的值,这新值对其他线程来说是立即可见的。
2)禁止进行指令重排序。
volatile只提供了保证访问该变量时,每次都是从内存中读取最新值,并不会使用寄存器缓存该值——每次都会从内存中读取。
而对该变量的修改,volatile并不提供原子性的保证。
由于及时更新,很可能导致另一线程访问最新变量值,无法跳出循环的情况
多线程下计数器必须使用锁保护
边栏推荐
- MATLAB小技巧(18)矩阵分析--熵权法
- [12. maximum continuous non repeating subsequence]
- Matlab tips (18) matrix analysis -- entropy weight method
- 参考 | Win11 开启热点之后电脑不能上网
- MySQL environment variable configuration tutorial
- PayPal账户遭大规模冻结!跨境卖家如何自救?
- About the problem that the El date picker Click to clear the parameter and make it null
- Reference | upgrade win11 mobile hotspot can not be opened or connected
- "Short video" Linxia fire rescue detachment carries out fire safety training
- 05 observer mode
猜你喜欢

MySQL environment variable configuration tutorial
![[10. difference]](/img/15/ffd93da75858943fe887de1718e0f6.png)
[10. difference]

Eight misunderstandings, broken one by one (final): the cloud is difficult to expand, the customization is poor, and the administrator will lose control?

Redis五种基本类型

MATLAB小技巧(18)矩阵分析--熵权法

PayPal账户遭大规模冻结!跨境卖家如何自救?

Game asset reuse: a new way to find required game assets faster
![[11. two dimensional difference]](/img/b2/da624f8a7f97c46b8e346cf6d6da49.png)
[11. two dimensional difference]

Creation process and memory layout of objects at JVM level

05 observer mode
随机推荐
lvgl使用demo及说明2
Understanding mvcc in MySQL transactions is super simple
No matter how good LCD and OLED display technologies are, they cannot replace this ancient display nixie tube
Redis五种基本类型
Helix QAC is updated to 2022.1 and will continue to provide high standard compliance coverage
盲测调查显示女码农比男码农更优秀
[11. two dimensional difference]
About the problem that the El date picker Click to clear the parameter and make it null
The difference between ArrayList and LinkedList
0号进程,1号进程,2号进程
Design of a solar charge pump power supply circuit
参考 | Win11 开启热点之后电脑不能上网
PayPal账户遭大规模冻结!跨境卖家如何自救?
Index +sql exercise optimization
05 观察者(Observer)模式
[batch dos-cmd command - summary and summary] - how to distinguish the internal command and external command of CMD, and the difference between CMD command and run (win+r) command,
[batch dos-cmd command - summary and summary] - output / display command - echo
[notes on c++ primer] Chapter 3 string, vector and array
ArrayList和LinkedList的区别
八大误区,逐个击破(终篇):云难以扩展、定制性差,还会让管理员失去控制权?