Complete example for use of volatile key word in Java?

感情迁移 提交于 2019-12-05 06:35:10
aioobe

First of all, there's no guaranteed way of exposing caching due to non-volatile variables. Your JVM might just be very kind to you all the time and effectively treat every variable as volatile.

That being said, there are a few ways to increase probability of having threads caching their own versions of a non-volatile variable. Here is a program that exposes the importance of volatile in most machines I've tested it on (adapted version 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.");
    }
}

This program will typically just output

keepRunning set to false.

and continue running. Making keepRunning volatile causes it to print

keepRunning set to false.
Thread terminated.

and terminate.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!