The easiest to understand example of volatile keyword in Java

I am reading the volatile keyword in Java and fully understand its theoretical part

But what I'm looking for is a good example of what happens if variables are not mutable

The following code snippet does not work as expected (taken from here):

class Test extends Thread {

    boolean keepRunning = true;

    public void run() {
        while (keepRunning) {
        }

        System.out.println("Thread terminated.");
    }

    public static void main(String[] args) throws InterruptedException {
        Test t = new test();
        t.start();
        Thread.sleep(1000);
        t.keepRunning = false;
        System.out.println("keepRunning set to false.");
    }
}

Ideally, if keeprunning is not volatile, the thread should continue running indefinitely However, it will stop in a few seconds

I have two basic questions:

>Can anyone explain volatile with examples? Not from JLS. > Is it a volatile alternative to synchronization? Does it achieve atomicity?

Solution

Volatility – > ensures visibility rather than atomicity

Synchronization (locking) – > ensure visibility and atomicity (if done correctly)

Volatile cannot replace synchronization

Use volatile. Only when updating a reference and not performing some other operation on it

Example:

volatile int i = 0;

public void incrementI(){
   i++;
}

Not using synchronization or atomicinteger will not be thread safe because increment is a compound operation

That depends on all the circumstances In most cases, the JVM is smart enough to refresh the content

Correct use of volatile discusses various possible uses of volatile substances Using volatile correctly is tricky. I'll say "keep it if in doubt". Use synchronized blocks

Also:

You can use synchronized blocks instead of volatile, but not vice versa

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>