Multithreaded behavior of volatile Java variable

I recently received an interview test and fumbled on this issue. I will tell you what I explained and what I want to know what is the right behavior. I want my understanding to be right, not for the sake of an interview, but to get better.

** Que: ** We have a counter below (java code), and if it is said that 20 threads run this code in parallel, will the value of a and b be the same? What if b is not valiatile

My answer: may or may not be. Why - when there is a race condition, there is no guarantee that different threads will see the updated values ​​of b or a, in which case the values ​​will be different. Here, I do not think that variability matters.

I wrote a simple client and ran this code with up to 50 threads on a 16-core laptop, and I could see the same values ​​for a and b when I tried to work 500 times. However, when I increased the number of threads to 200, sometimes I saw different values.

The question is what is the correct answer to this and do I understand correctly? And why did I see different results on my laptop?

public class VolatileCounter implements Runnable {


    private static int a;
    private volatile static int b;

    public VolatileCounter() {
    }

    @Override
    public void run() {
        try{

            b++;
            a++;
        }finally {
                      //some system println....
        }

    }

    public void printNumbers() {
        System.out.println(b);
        System.out.println(a);
    }

}
+4
source share
3 answers

, - : , , , . . pre-increment ?. ( , -, , - .)

:

  • , concurrency, , . concurrency , .

  • , , . volatile, , JVM. JVM . .

  • printlns , , .

  • , , a, .: . ?

+1

50 , . a b , ,

+1

50 , , , , . , , .

. volatile b, b i.e, a.

The increment operation is actually a load, growth, and retention, so it is not actually thread safe.

+1
source

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


All Articles