Question

I have a method which is actually a scheduler which runs a process in every one hour and create a log file every hour.
I want to call this method once in the application life cycle so I call it from a static block.
But I feel this is not working because the file is sometimes generated in one hour and sometimes early. I heard somewhere that static block only execute once is it not true?
If yes than what should I do?

Was it helpful?

Solution

Static initializer blocks are executed only once when the classloader loads the class. The time they're executed is so bound to your application logic. To be more precise different classloaders might load your class so the static block can be executed more than one time theoretically.

For scheduling purposes try using out of the box a scheduler library, for example Quartz scheduler. ( http://quartz-scheduler.org) This might seem a bit of overhead the first time, however these libs offer advanced features that you may need eventually. Just a simple example: what if your program is stopped and restarted in an hour? Then the process might be run twice in this particular hour. Using quartz you can handle this situation as well.

OTHER TIPS

You need a variable, too.

class ...

  private static hasRun = false;

  public static synchronize boolean runOnce ()
  {
     if (hasRun) return false;

     hasRun = true;
     // do something
     return true;
  }

A static block may never be called when there is no usage of this class.

There is a discussion about unloading classes Unloading classes in java?

When unloading classes happens than multiple loading are possible than multiple call of static initializer may happen. However, in this case my solution will fail as in this case ANY solution must fail.

I feel this is extremely uncommon and unlikely. But maybe you have to case when you not control the environment

Static method does not mean it runs only once. static means it can be access outside method without instantiating an instance of the class.

Best solution off the top of my head. Have a static variable so it can be refresh along with your static method, and increment that static variable as soon as that method is executed. Every time this method executes, check that variable and exit right away if it has been incremented already.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top