g**e 发帖数: 6127 | 1 除了一个是object一个是premitive type
多线程操作的时候,这两个哪个性能好? | g*****g 发帖数: 34805 | 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 : 多线程操作的时候,这两个哪个性能好?
| h*****0 发帖数: 4889 | 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.
| g**e 发帖数: 6127 | 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.
| g*****g 发帖数: 34805 | 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?
| g**e 发帖数: 6127 | 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.
| h*****0 发帖数: 4889 | 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.
| g*****g 发帖数: 34805 | 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.
|
|