正确更新静态变量的正确方法

use*_*359 1 java

我有一个静态变量,我在类的开头加载.我想每小时更新一次变量.问题是这样做的正确方法是什么?

我试图这样做的方式如下,但它需要更新静态变量的方法在每个构造函数中:

import java.util.Date;

public class MyClass {

    private static String globalString = "";

    // initialize lastUpdate with two hours back to make sure first update happens
    private static Date lastUpdate = new Date(System.currentTimeMillis() - (2 * (3600 * 1000)));


    MyClass() {
        updateGlobalString();

        // DO MORE STUFF HERE...
    }


    MyClass(String string) {
        updateGlobalString();

        // DO MORE STUFF HERE...
    }

    private synchronized void updateGlobalString() {
        // check if we need to update
        if (lastUpdate.before(new Date(System.currentTimeMillis() - (3600 * 1000)))) {

            // DO THINGS TO UPDATE globalString HERE...

            lastUpdate = new Date();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这样做有什么其他想法/更好的方法吗?

And*_*yle 5

您应该使用某种计时器来进行更新.

例如,使用ScheduledExecutorService每小时运行一次任务,从而更新该字段.像这样的东西:

public class MyClass {

    private static volatile String globalString;
    private static ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();

    static {
        exec.scheduleAtFixedRate(new Runnable() {
            public void run() {
               // DO THINGS TO UPDATE globalString HERE...
            }
        },
        0, 1, TimeUnit.HOUR);
    }

    // Rest of class, without having to worry about the updateGlobalString
    // method, or the lastUpdate variable, or anything like that
    ...
}
Run Code Online (Sandbox Code Playgroud)

请注意,由于多个线程正在访问变量,因此您需要确保代码是线程安全的.(上面的计时器示例肯定是这种情况,但您当前的方法也可能就是这种情况.)

简单地确保看到更新的最简单方法是将globalString变量标记为volatile,但是根据类的使用方式,其他方法可能更合适.