java - Proper way to update static variable periodically -


i have static variable load @ beginning of class. want update variable every hour. question proper way of doing this?

the way trying following requires method updates static variable in every constructor:

import java.util.date;  public class myclass {      private static string globalstring = "";      // initialize lastupdate 2 hours make sure first update happens     private static date lastupdate = new date(system.currenttimemillis() - (2 * (3600 * 1000)));       myclass() {         updateglobalstring();          // more stuff here...     }       myclass(string string) {         updateglobalstring();          // more stuff here...     }      private synchronized void updateglobalstring() {         // check if need update         if (lastupdate.before(new date(system.currenttimemillis() - (3600 * 1000)))) {              // things update globalstring here...              lastupdate = new date();         }     } } 

any other ideas/better way of doing it?

you should use sort of timer update.

for example, use scheduledexecutorservice have task run every hour, updates field. this:

public class myclass {      private static volatile string globalstring;     private static scheduledexecutorservice exec = executors.newsinglethreadscheduledexecutor();      static {         exec.scheduleatfixedrate(new runnable() {             public void run() {                // things update globalstring here...             }         },         0, 1, timeunit.hour);     }      // rest of class, without having worry updateglobalstring     // method, or lastupdate variable, or     ... } 

note because variable being accessed multiple threads, you'll need ensure code threadsafe. (this case timer example above, case current approach too.)

the easiest way ensure updates seen mark globalstring variable volatile, depending on how class used other approaches may more appropriate.


Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -