Redian新闻
>
AtomicInteger和volatile int有啥区别
avatar
AtomicInteger和volatile int有啥区别# Java - 爪哇娇娃
g*e
1
除了一个是object一个是premitive type
多线程操作的时候,这两个哪个性能好?
avatar
g*g
2
Take it this way, volatile int, you still need to
sync blocks to do read/write. AtomicInteger you don't.
You can check the latter's source code to see why.

【在 g**e 的大作中提到】
: 除了一个是object一个是premitive type
: 多线程操作的时候,这两个哪个性能好?

avatar
h*0
3
why do we need to sync blocks to read and write on a volatile int?

【在 g*****g 的大作中提到】
: Take it this way, volatile int, you still need to
: sync blocks to do read/write. AtomicInteger you don't.
: You can check the latter's source code to see why.

avatar
g*e
4
为啥volatile需要sync?

【在 g*****g 的大作中提到】
: Take it this way, volatile int, you still need to
: sync blocks to do read/write. AtomicInteger you don't.
: You can check the latter's source code to see why.

avatar
g*g
5
volative only guarrantee you'll get the latest value on read,
it's not atomic. Let's say you have two threading trying to do
increment. Both threads see the initial value 0, and write
1 back. With sync block, the result value is guarranteed to be 2.
That's AtomicInteger gives you too.

【在 g**e 的大作中提到】
: 为啥volatile需要sync?
avatar
g*e
6
volatile is actually write safe. but its value to write doesn't depend on
the current value.
In your example, i++ or i+=1 is not thread safe, because this actually
involves reading the current value, incrementing it, then setting the new
value.

【在 g*****g 的大作中提到】
: volative only guarrantee you'll get the latest value on read,
: it's not atomic. Let's say you have two threading trying to do
: increment. Both threads see the initial value 0, and write
: 1 back. With sync block, the result value is guarranteed to be 2.
: That's AtomicInteger gives you too.

avatar
h*0
7
ok...
but for get or set method, we don't need to sync

【在 g*****g 的大作中提到】
: volative only guarrantee you'll get the latest value on read,
: it's not atomic. Let's say you have two threading trying to do
: increment. Both threads see the initial value 0, and write
: 1 back. With sync block, the result value is guarranteed to be 2.
: That's AtomicInteger gives you too.

avatar
g*g
8
But i++ kind of stuff is why you want to use AtomicInteger,
very handy for a counter. If it's just get and set, there's no
difference, that can easily tell by looking into the source code.

【在 g**e 的大作中提到】
: volatile is actually write safe. but its value to write doesn't depend on
: the current value.
: In your example, i++ or i+=1 is not thread safe, because this actually
: involves reading the current value, incrementing it, then setting the new
: value.

相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。