当ScheduledExecutorService的任务抛出异常时,不会打印堆栈跟踪

时间:2016-10-11 20:04:18

标签: java dropwizard

我正在通过Dropwizard的LifecycleEnvironment.scheduledExecutorService()创建一个ScheduledExecutorService。我安排了四个任务,在3秒后抛出异常。问题是没有为异常打印堆栈跟踪,因此我无法追踪它发生的原因。抛出异常1的任务永远不会重新启动。

我尝试设置默认的未捕获异常处理程序,但它也没有帮助:

Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread thread, Throwable throwable) {
                System.err.println("An exception occurred as below:");
                throwable.printStackTrace(System.err);
            }
        });

以下是完整的代码:

这是扩展应用程序的主要驱动类:

App.java

import io.dropwizard.Application;
import io.dropwizard.setup.Environment;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class App extends Application<AppConfiguration> {

    public void run(AppConfiguration appConfiguration, Environment environment) throws Exception {
        final ScheduledExecutorService scheduledExecutorService = environment.lifecycle()
                .scheduledExecutorService("throwing-exception-threads").threads(4)
                .build();

        scheduledExecutorService.scheduleAtFixedRate(new ThreadToDie(), 0,5, TimeUnit.SECONDS);
        scheduledExecutorService.scheduleAtFixedRate(new ThreadToDie(), 0,5, TimeUnit.SECONDS);
        scheduledExecutorService.scheduleAtFixedRate(new ThreadToDie(), 0,5, TimeUnit.SECONDS);
        scheduledExecutorService.scheduleAtFixedRate(new ThreadToDie(), 0,5, TimeUnit.SECONDS);

        final HelloWorldResource resource = new HelloWorldResource();
        environment.jersey().register(resource);
    }

    public static void main(String[] args) throws Exception {
        new App().run(args);
    }
}

以固定间隔安排的任务代码如下。它打印计数器值,每秒递增一次。当计数器为3时,它会抛出NullPointerException。

ThreadToDie.java

public class ThreadToDie implements Runnable {

    int i = 0;

    @Override
    public void run() {
        i++;
        System.out.printf("Value of i: %d\n", i);
        if (i % 3 == 0) {
            System.out.printf("Throwing NullPointerException\n");
            throw new NullPointerException("This should be printed.");
        }
    }
}

为了完整性,以下是Configuration类和HelloWorld API类。虽然在问题中询问它们包含的内容是不相关的。

AppConfiguration.java

import io.dropwizard.Configuration;

public class AppConfiguration extends Configuration {
}

HelloWorldResource.java

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import java.util.Optional;

@Path("/hello")
@Produces(MediaType.APPLICATION_JSON)
public class HelloWorldResource {

    @GET
    public String hello(@QueryParam("name") Optional<String> name) {
        final String retVal = String.format("Hello %s!", name.orElse("World"));
        return retVal;
    }
}

1 个答案:

答案 0 :(得分:1)

请参阅Why is UncaughtExceptionHandler not called by ExecutorService?,了解永不触发UncaughtExceptionHandler的原因 - 您提供的每项任务都由捕获所有异常的工作人员处理。

当您向执行人提交任务时,您会收到Future并以这种方式访问​​该例外:

ScheduledFuture<?> future = scheduledExecutorService.scheduleAtFixedRate(new ThreadToDie(), 0,5, TimeUnit.SECONDS);
try {
   future.get();
} catch (ExecutionException ex) {
   ex.getCause().printStackTrace();
}

Future.get将等到任务完成或出错。