出于教育目的,我正在编写一个简单的版本AtomicLong,其内部变量受到保护ReentrantReadWriteLock.这是一个简化的例子:
public class PlainSimpleAtomicLong {
private long value;
private final ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
public PlainSimpleAtomicLong(long initialValue) {
this.value = initialValue;
}
public long get() {
long result;
rwLock.readLock().lock();
result = value;
rwLock.readLock().unlock();
return result;
}
// incrementAndGet, decrementAndGet, etc. are guarded by rwLock.writeLock()
}
Run Code Online (Sandbox Code Playgroud)
我的问题:由于"value"是非易失性的,其他线程是否有可能通过不正确的初始值来观察PlainSimpleAtomicLong.get()?例如,线程T1创建L = new PlainSimpleAtomicLong(42)并与线程共享引用T2.为T2保证遵守L.get()为42?
如果没有,包装this.value = initialValue;到写锁定/解锁会有所作为吗?