Java long running timer is being consumed by GC

I have a java.util.Timer and I am scheduling TimerTasks that run every 24 hours at 3:00:00 AM, however after 5-8 days the Timer is consumed by GC and all my tasks are cancelled because the timer instance no longer exists.

How can I prevent this ?

I use:

t.schedule(timerTask, date);

And then the tasks starts again itself (when the task is executed is also calls method that schedules this task again)

The timer is defined like that:

public static Timer t = new java.util.Timer();

static variables are part of the class where they are defined and are initialized when the class is loaded. The GC may decide at some point (especially when memory is low and more is required for a pending operation) to unload a class that is no longer needed. This is what might happen to you here. You could try to create the Timer object as a non static member of a class which is guaranteed to have an instance that is still referenced by the GC.


If the Timer is declared and created like this:

    public static Timer t = new java.util.Timer();

then I think there are only two scenarios where the Timer can be garbage collected:

  • Somewhere in your application, something is assigning a new value to t , causing the previous value to become unreachable.

  • The class containing the t declaration has become unreachable and has been unloaded.

  • The first scenario is by far the most likely, and there is a simple way to avoid it. Change the declaration to this:

       public static final Timer t = new java.util.Timer();
    

    The second scenario is only plausible if your application (or maybe, the framework it is using) loads the class dynamically using a classloader that itself becomes unreachable.

    链接地址: http://www.djcxy.com/p/74914.html

    上一篇: 如何停止已经执行的TimerTask?

    下一篇: GC正在使用Java长时间运行计时器