Thread-safety of int field in Java

175 Views Asked by At

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();
            }
        }
        
    }
2

There are 2 best solutions below

0
dallin_sh On BEST ANSWER

Get answer from @pveentjer in comments under question:

It is important to understand that caches on modern cpus are always coherent due to the cache coherence protocol like MESI. Another important thing to understand is that correctly synchronized programs exhibit sequential consistent behavior and for sequential consistency the real time order isnt relevant. So reads and writes can be skewed as long as nobody can observe a violation of the program order.

0
Meysam Karimi On

Yes, This approach is thread-safe. If there is no thread that has requested the write lock and the lock for writing, then multiple threads can lock the lock for reading. It means multiple threads can read the data at the very moment, as long as there’s no thread to write the data or to update the data.