不会吧,是不是 timer离开了自己的名字空间?放到main函数里面定义timer

解决方案 »

  1.   

    为避免被回收,最好将timer放在一个公共的地方定义,如果你只需要一个定时器,最好静态定义,用时再设置其任务。
      

  2.   

    再详细说明一下:
    timer放servlet调用的一个线程类的run方法中,所以按照我的理解运行完下面两句
    Timer timer = new Timer(true);
    timer.schedule(new GetFilesService.GetFilesTask(), 0, 3000);
    线程类完结。
    所以在今后的运行时刻,timer失去ref,并且在间隔中,也可能没有内部任务,所以被回收。
    sun的文档如下:
    After the last live reference to a Timer object goes away and all outstanding tasks have completed execution, the timer's task execution thread terminates gracefully (and becomes subject to garbage collection). However, this can take arbitrarily long to occur. By default, the task execution thread does not run as a daemon thread, so it is capable of keeping an application from terminating. If a caller wants to terminate a timer's task execution thread rapidly, the caller should invoke the the timer's cancel method