AtomicReference原子引用详解
概述
AtomicReference提供对引用对象的原子操作,用于解决多线程下对象引用的线程安全问题。
基本用法
1 2 3 4 5 6 7 8 9 10
| AtomicReference<User> atomicRef = new AtomicReference<>();
atomicRef.set(new User(1, "Tom"));
User user = atomicRef.get();
atomicRef.compareAndSet(oldUser, newUser);
|
CAS操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| boolean success = atomicRef.compareAndSet( currentUser, newUser );
while (true) { User current = atomicRef.get(); User next = update(current); if (atomicRef.compareAndSet(current, next)) { break; } }
|
场景
总结
AtomicReference是实现无锁并发的重要工具,比synchronized更高效。