Skip to content
Advertisement

Thread-safety of int field in Java

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

Advertisement

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.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement