0

I have a question in java concurrency.

I use the sout in Producer thread with class variable private static boolean FLAG and you can already see FLAG variable without volatile.

I want to change FLAG = true to FLAG = !FLAG in Producer thread and after that I expected to read this value in Consumer thread.

Ofcourse FLAG doesn’t have volatile and Consumer thread will read the old FLAG value.

So when I change position

System.out.println("Flag to " + !FLAG);

FLAG = !FLAG;

private static boolean FLAG = true;

public static void main(String[] args) {
    new Consumer().start();
    new Producer().start();
}

static class Consumer extends Thread {

    @Override
    public void run() {

        boolean local = FLAG;

        while ( local ){

            local = FLAG;

            if (!local) {
                System.out.println("exit");
            }
        }

    }
}

static class Producer extends Thread{

    @Override
    public void run() {

        System.out.println("Flag to " + !FLAG);
        FLAG = !FLAG;
    }
}

to

private static boolean FLAG = true;

public static void main(String[] args) {
    new Consumer().start();
    new Producer().start();
}

static class Consumer extends Thread {

    @Override
    public void run() {

        boolean local = FLAG;

        while ( local ){

            local = FLAG;

            if (!local) {
                System.out.println("exit");
            }
        }

    }
}

static class Producer extends Thread{

    @Override
    public void run() {

        FLAG = !FLAG;
        System.out.println("Flag to " + !FLAG);
    }
}

FLAG = !FLAG;

System.out.println("Flag to " + !FLAG);

Consumer thread printing the " exit ".

So where is the my fault or what is the explanation this case.

hozze
  • 1
  • (1) Possibly related: [Loop doesn't see value changed by other thread without a print statement](https://stackoverflow.com/q/25425130) (2) Regarding `extends Thread` please see: [“implements Runnable” vs “extends Thread” in Java](https://stackoverflow.com/q/541487). – Pshemo Jul 02 '20 at 14:25
  • `System.out.println` is typically implemented using synchronization (to avoid garbling the output of multiple threads printing at the same time), but it's not actually required. If you are using an implementation with synchronization, you do indeed get volatile-like behavior, because of the happens-before created by a synchronized block; however, this is not something you can rely upon happening. – Andy Turner Jul 02 '20 at 14:26

0 Answers0