Is there any point in using a volatile long?

前端 未结 3 1894
情深已故
情深已故 2020-12-04 13:15

I occasionally use a volatile instance variable in cases where I have two threads reading from / writing to it and don\'t want the overhead (or potential deadlo

3条回答
  •  无人及你
    2020-12-04 13:40

    This can be demonstrated by example

    • constantly toggle two fields, one marked volatile and one not between all bits set and all bits clear
    • read the field values on another thread
    • see that the foo field (not protected with volatile) can be read in an inconsistent state, this never happens to the bar field protected with volatile

    Code

    public class VolatileTest {
        private long foo;
        private volatile long bar;
        private static final long A = 0xffffffffffffffffl;
        private static final long B = 0;
        private int clock;
        public VolatileTest() {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        foo = clock % 2 == 0 ? A : B;
                        bar = clock % 2 == 0 ? A : B;
                        clock++;
                    }
                }
    
            }).start();
            while (true) {
                long fooRead = foo;
                if (fooRead != A && fooRead != B) {
                    System.err.println("foo incomplete write " + Long.toHexString(fooRead));
                }
                long barRead = bar;
                if (barRead != A && barRead != B) {
                    System.err.println("bar incomplete write " + Long.toHexString(barRead));
                }
            }
        }
    
        public static void main(String[] args) {
            new VolatileTest();
        }
    }
    

    Output

    foo incomplete write ffffffff00000000
    foo incomplete write ffffffff00000000
    foo incomplete write ffffffff
    foo incomplete write ffffffff00000000
    

    Note this only happens for me when running on a 32 bit VM, on 64 bit VM I couldn't get a single error in several minutes.

提交回复
热议问题