Using Atomic Variables

Using volatile for a variable reduces the risk of memory consistency errors (please correct me if this reveals some flaws in my understanding of any relevant concept). Thus, in the following example, although the variable c1 is volatile, still the occurrence of a memory constancy error causes c1 to become 15, and sometimes 14, at the output, and then the correct output is 16.

class Lunch implements Runnable {

    private volatile long c1 = 0;
    private Object lock1 = new Object();
    private Object lock2 = new Object();
    public void inc1() {
       // synchronized(lock1) { c1 is volatile
            c1++;
       // }
    }

    public void run() {
        try {
            inc1();
            Thread.sleep(1000);
            inc1();
            Thread.sleep(1000);
            inc1();
            Thread.sleep(1000);
            inc1();
            inc1();
            Thread.sleep(1000);
            inc1();
            Thread.sleep(1000);
            inc1();
            Thread.sleep(1000);
            inc1();
        }
        catch(InterruptedException e) {
            return;
        }
    }
    public long value() {
        return c1;
    }
    public static void main(String args[]) throws InterruptedException {
        Lunch l = new Lunch();
       Thread t1 = new Thread(l);
       Thread t2 = new Thread(l);
       t1.start();
       t2.start();
       t1.join();
       t2.join();
       System.out.println(l.value());
    }
} 
+3
source share
3 answers

. ++ , , // .

AtomicInteger .

+6

- . . ( ) , .

+3

Source: https://habr.com/ru/post/1763076/


All Articles