contextrefreshed后SpringWebApp中scheduledfuturetask中的rejectedexecutionexception

k7fdbhmy  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(147)

我使用以下代码在java 8 spring webapp中计划任务:
在@控制器中;

@EventListener(ContextRefreshedEvent.class)
public void doSomethingAfterContextRefreshed() {

    ScheduledFuture<?> countdown = scheduler.schedule(new Runnable() {
        @Override
        public void run() {

            try {
                Execute();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }}, 10, TimeUnit.SECONDS);

    while (!countdown.isDone()) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    scheduler.shutdown();
}

当应用程序启动时 Execute() 方法在启动10秒后被调用,没有错误,但在它完成后,我得到以下堆栈跟踪:
java.util.concurrent.rejectedexecutionexception:任务java.util.concurrent。scheduledthreadpoolexecutor$scheduledfuturetask@52518e6[未完成,任务=java.util.concurrent。executors$runnableadapter@759546c8[wrapped task=com.mycompany.myproject.service。loadservice$1@4871ba3f]]从java.util.concurrent拒绝。scheduledthreadpoolexecutor@798daafa[已终止,池大小=0,活动线程=0,排队任务=0,在java.base/java.util.concurrent.threadpoolexecutor$abortpolicy.rejectedexecution(threadpoolexecutor)处完成的任务=1]。java:2055)在java.base/java.util.concurrent.threadpoolexecutor.reject(threadpoolexecutor。java:825)在java.base/java.util.concurrent.scheduledthreadpoolexecutor.delayedexecute(scheduledthreadpoolexecutor。java:340)在java.base/java.util.concurrent.scheduledthreadpoolexecutor.schedule(scheduledthreadpoolexecutor。java:562)
你知道我为什么会有这个例外吗?

q9rjltbz

q9rjltbz1#

让我们简化一下:

public class DeleteMe {

    public static void main(String[] args) {
        doSomethingAfterContextRefreshed();
        doSomethingAfterContextRefreshed();
    }

    static ScheduledThreadPoolExecutor scheduler = new ScheduledThreadPoolExecutor(1);

    public static void doSomethingAfterContextRefreshed() {

        ScheduledFuture<?> countdown = scheduler.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("Some message");
            }}, 100, TimeUnit.MILLISECONDS);

        while (!countdown.isDone()) {
            LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(10));
        }
        scheduler.shutdown();
    }

}

在第一次调用 doSomethingAfterContextRefreshed -你是做什么的? scheduler.shutdown(); .
在第二次调用 doSomethingAfterContextRefreshed(); 你是做什么的? scheduler.schedule(....) .
scheduler 此时关机?什么是文档 schedule 说要把这些案子扔进去?你现在有答案了。

相关问题