java atomic volatile,关于volatile和Atomic类的一些疑问?

博客讨论了Java中volatile关键字的使用限制,指出它仅适用于单次加载或存储操作,不适合long和double变量,这使得其应用不常见。volatile不能与自增运算符(++)一起使用,因为++包含多个指令,可能导致线程不安全。AtomicInteger类提供了一种原子性地增加整数的解决方案,通过特殊机器指令确保线程安全。
摘要由CSDN通过智能技术生成

i am going thru Java threads book. I came across this statement

Statement 1:- "volatile variables can be safely used only for single load or store operation and can't be

applied to long or double variales. These restrictions make the use of volatile variables uncommon"

I did not get what does single load or store operation mean here? why volatile can't be

applied to long or double variales?

Statement 2:- "A Volatile integer can not be used with the ++ operator because ++ operator contains

multiple instructions.The AtomicInteger class has a method that allows the integer it holds to be

incremented atomically."

Why Volatile integer can not be used with the ++ operator and how AtomicInteger addresses it?

解决方案

Statement 1:- "volatile variables can be safely used only for single load or store operation and can't be applied to long or double variales. These restrictions make the use of volatile variables uncommon"

What?! I believe this is simply flat-out wrong. Maybe your book is out of date.

Statement 2:- "A Volatile integer can not be used with the ++ operator because ++ operator contains multiple instructions.The AtomicInteger class has a method that allows the integer it holds to be incremented atomically."

Exactly what it says. The ++ operator actually translates to machine code like this (in Java-like pseudocode):

sync_CPU_caches();

int processorRegister = variable;

processorRegister = processorRegister + 1;

variable = processorRegister;

sync_CPU_caches();

This is not thread-safe, because even though it has a memory barrier, and reads atomically, and writes atomically, it is not guaranteed that you won't get a thread switch in the middle, and processor registers are local to a CPU core (think of them as like "local variables" inside the CPU core). But an AtomicInteger is thread-safe - it probably is implemented using special machine code instructions such as compare-and-swap.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值