为什么有必要复制volatile变量而不是直接使用它?

ada*_*liu 4 java synchronization volatile

实践中的Java并发性一书中,有一个自定义线程的例子(参见8.3.4节中的清单8.7).我粘贴了下面的代码.有一点我不太明白.也就是说,该run()方法debugLifecycle在使用之前复制volatile变量.它有一个注释复制调试标志,以确保始终如一的价值.有没有必要在这里复制变量?如果是,为什么?

public class MyAppThread extends Thread {
    public static final String DEFAULT_NAME = "MyAppThread";
    private static volatile boolean debugLifecycle = false;

    public MyAppThread(Runnable r) {
        this(r, DEFAULT_NAME);
    }

    public MyAppThread(Runnable runnable, String name) {
        super(runnable, name + "-" + created.incrementAndGet());
        setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            public void uncaughtException(Thread t,
                                          Throwable e) {
                log.log(Level.SEVERE,
                        "UNCAUGHT in thread " + t.getName(), e);
            }
        });
    }

    public void run() {
        // Question: why copy the volatile variable here?
        // Copy debug flag to ensure consistent value throughout.
        boolean debug = debugLifecycle;
        if (debug) log.log(Level.FINE, "Created " + getName());
        try {
            alive.incrementAndGet();
            super.run();
        } finally {
            alive.decrementAndGet();
            if (debug) log.log(Level.FINE, "Exiting " + getName());
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

use*_*300 10

volatile关键字通常意味着该变量是由多个线程访问.所以你要复制一次状态.如果在您运行时,另一个线程修改它,您的副本将不受影响.

否则可能是第一个log.log()被执行但不是finally子句的情况log.log().这可能是令人困惑或不正确的行为.

即使debugLifecycle是不是在少数情况下挥发性它仍然可能会更好使用副本.但这volatile是一个"红旗",这个变量可能随时改变.