原子类的线程安全性原理
2017-02-22 15:17
106 查看
以AtomicInteger来说明
1.value实例变量是用来存储整数的时间变量,这里被声明为volatile,确保了并发情况下的可见性
2.valueOffset实例变量是用来记录value本身在内存的偏移地址,在更新操作在内存中找到value的位置,方便比较。
3.以getAndSet为例。使用了Unsafe 的getAndInt方法,该方法先取AtomicInteger存储的value值,然后调用compareAndSwapInt方法(native方法),一直到compareAndSwapInt返回true时循环操作。
4.compareAndSwapInt方法根据根据offset获取o的value值,若value和v相同,设置value值为newValue,返回true;否则返回false。
2.存在ABA问题。
1.value实例变量是用来存储整数的时间变量,这里被声明为volatile,确保了并发情况下的可见性
2.valueOffset实例变量是用来记录value本身在内存的偏移地址,在更新操作在内存中找到value的位置,方便比较。
3.以getAndSet为例。使用了Unsafe 的getAndInt方法,该方法先取AtomicInteger存储的value值,然后调用compareAndSwapInt方法(native方法),一直到compareAndSwapInt返回true时循环操作。
4.compareAndSwapInt方法根据根据offset获取o的value值,若value和v相同,设置value值为newValue,返回true;否则返回false。
/** * Atomically sets to the given value and returns the old value. * * @param newValue the new value * @return the previous value */ public final int getAndSet(int newValue) { return unsafe.getAndSetInt(this, valueOffset, newValue); }
public final int getAndSetInt(Object o, long offset, int newValue) { int v; do { v = this.getIntVolatile(o, offset); } while(!this.compareAndSwapInt(o, offset, v, newValue)); return v; }
优缺点
1.避免了多线程下对共享变量必须加锁进行访问,提高效率。2.存在ABA问题。
相关文章推荐
- 多线程下的设计模式研究(一):原子对象模式
- java.util.concurrent系列文章--(3)基于硬件同步原语的原子类型
- OpenMP创建线程中的锁及原子操作性能比较
- 得到单词有效原子集合的算法
- 内核同步方法之原子操作
- [转]Effective C# 原则7: 选择恒定的原子值类型数据
- Windows Via C/C++:用户模式下的线程同步——原子操作:Interlocked函数族
- 用汇编实现原子操作
- sigsuspend 将重设signal mask和等待合成原子操作
- 关于原子锁的理解
- 没有atomic.h后如何在linux实现原子操作
- 《深入浅出 Java Concurrency》——原子操作
- 原子访问--- Interlocked系列函数
- <转载>SQLITE中原子提交的实现
- Java中的原子操作和volatile关键字
- 关于原子操作的一些总结
- 多线程程序中操作的原子性
- linux实现原子操作的内建函数
- 多线程环境下对变量的读写操作的原子性问题【baidu】