How to prevent a memory leak in quartz

后端 未结 4 680
不知归路
不知归路 2021-02-05 20:30

I\'m using quartz in my project. My web application has apparently caused a memory leak when it stops, the error is :

SEVERE: A web application appears to have          


        
4条回答
  •  灰色年华
    2021-02-05 20:51

    By implementing org.quartz.InterruptableJob you can properly interrupt threads triggered by servlet unloading.

    @DisallowConcurrentExecution
    public class Job implements InterruptableJob {
    
        private Thread thread;
    
        @Override
        public void execute(JobExecutionContext context) throws JobExecutionException {
            thread = Thread.currentThread();
            // ... do work
        }
    
        @Override
        public void interrupt() throws UnableToInterruptJobException {
            thread.interrupt();
            try {
                thread.join();
            } catch (InterruptedException e) {
                throw new UnableToInterruptJobException(e);
            } finally {
                // ... do cleanup
            }
        }
    }
    

    This example may cause a race condition bug on the thread variable, if the job has not been executed before it is interrupted. I leave the final solution open for suggestions, depending on the life cycle of the target application. If you need concurrent execution through the same job instance, augment the solution to handle multiple threads and remove the @DisallowConcurrentExecution annotation.

    In order for this to work the quartz property org.quartz.scheduler.interruptJobsOnShutdownWithWait must be set to true. This can be done by defining a property file for the scheduler, or by a bean references if using spring framework.

    Example quartz.properties file:

    org.quartz.scheduler.interruptJobsOnShutdownWithWait=true
    

    Note that the interruption only is dispatched if the scheduler is configured to wait on shutdown, resulting in a call to scheduler.shutdown(true).

提交回复
热议问题