当前位置:网站首页>看看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并不提供原子性的保证。
由于及时更新,很可能导致另一线程访问最新变量值,无法跳出循环的情况
多线程下计数器必须使用锁保护
边栏推荐
- 数据类型占内存大小?LongVsObject
- Eight misunderstandings, broken one by one (final): the cloud is difficult to expand, the customization is poor, and the administrator will lose control?
- Filter filter
- Etcd tutorial - Chapter 5 etcd etcdctl usage
- Read datasets iteratively with xgboost
- oracle怎样将字符串转为多行
- 【论文阅读】Intrinsically semi-supervised methods
- 100% understanding of 5 IO models
- [batch dos-cmd command - summary and summary] - map folder to virtual disk - subst
- 直接修改/etc/crontab 文件内容,定时任务不生效
猜你喜欢

Experience record of Luogu's topic brushing

Redis transactions

Oracle uses an SQL to find out which data is not in a table

Redis的持久化机制

Correctly understand MySQL mvcc

Redis的事务

关联GIS:条条道路通UE5城

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

After working in a large factory for ten years with an annual salary of 400000 yuan, I was suddenly laid off. If the company wanted to abandon you, it wouldn't leave any kindness

DataV轮播表组件dv-scroll-board宽度问题
随机推荐
[batch dos-cmd command - summary and summary] - parameters%0,%1,%2,%[0-9],%0-9 in the batch command and batch command parameter position switching command shift, operator% usage in the DOS command
Etcd教程 — 第五章 Etcd之etcdctl的使用
If xn > 0 and X (n+1) /xn > 1-1/n (n=1,2,...), Prove that the series Σ xn diverges
Game asset reuse: a new way to find required game assets faster
LVGL GUI GUIDER移植代码到STM32
Is futures reverse documentary reliable?
JS EventListener
[daily practice] realization of product card animation effect
DataV轮播表组件dv-scroll-board宽度问题
关于放大器失真的原因你了解多少呢?
並發編程JUC的AQS底層源碼
多网络设备存在时,如何配置其上网优先级?
(原创)自定义Drawable
0号进程,1号进程,2号进程
Helix QAC更新至2022.1版本,将持续提供高标准合规覆盖率
oracle用一条sql查出哪些数据不在某个表里
数字IC-1.9 吃透通信协议中状态机的代码编写套路
Matlab tips (18) matrix analysis -- entropy weight method
Five basic types of redis
Persistence mechanism of redis