If class has field with int type (not Atomic Integer and without volatile keyword) and all access to this field happens under read/write locks - will this field thread-safe in this case? Or in some moment some thread can see not real value of this field but something from cache?
public static class Example {
private int isSafe;
private final ReadWriteLock lock;
public Example(int i) {
isSafe = i;
lock = new ReentrantReadWriteLock();
}
public int getIsSafe() {
final Lock lock = this.lock.readLock();
lock.lock();
try {
return isSafe;
} finally {
lock.unlock();
}
}
public void someMethod1() {
final Lock lock = this.lock.writeLock();
lock.lock();
try {
isSafe++;
} finally {
lock.unlock();
}
}
}
Get answer from @pveentjer in comments under question: