Вопрос

I have a static, periodic, java Timer/TimerTask that I would like to shutdown when the app does. I don't want the app hanging because some thread is still running (like what happens in debug mode in eclipse, some environments may kill the thing anyway). The reason I have it static is I plan to have some (very simple, probably just a counter) shared memory in all of the containing class's instances with the Timer so I feel class scope is appropriate.

My question is how best to do the shutdown of the Timer? Is this an appropriate time to use finalize? This timer seems benign enough that having a non-deterministic call to finalize may work? Would probably need to do some kind of instance counting to verify that there are no longer any instances of the class out there? Suggestions on ways to manage the shutdown of the static Timer are welcome.

pseudo code:

class foo {

private static Timer someTimer = null;

public foo() {
  if(someTimer == null) {
     someTimer = new Timer(new TimerTask(...));
  }

}

//how should I shut this thing down?
protected void finalize() throws Throwable {

}

//or is better to have shutdown() called explicitly?

}
Это было полезно?

Решение

It all depends on what your app actually does, but in general there will be some kind of event to signal that the app is being shutdown. For example if it's a GUI app, then maybe this will be the "user clicked on the Quit button" event. Or it's a webapp based on the servlet API, it will be an event fired by a ServletContextListener.

You should add a listener for this event, which calls some kind of shutdown method on your foo object. Inside this shutdown method the foo should take care of cleaning up its resources, including stopping the timer.

As a last resort, you might want to investigate JVM shutdown hooks

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top