1

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

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

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();
        }
    }
}

还有其他想法/更好的方法吗?

4

2 回答 2

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
    ...
}

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

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

于 2013-05-09T16:21:31.000 回答
1

一个简单的解决方案是使用 Executors 框架:

public class MyClass {
   public static String globalString = "";

   private static ScheduledExecutorService s = Executors.newSingleThreadScheduledExecutor();

   //static block of code
   static {
     s.scheduleAtFixedRate(new Runnable() {
        public void run() {
           globalString = System.currentTimeMillis() + "";
        }
     }, 0, 1, TimeUnit.HOUR);
   } 
}
于 2013-05-09T16:24:16.207 回答