ScheduledExecutorService Exception handling

前端 未结 7 2061
再見小時候
再見小時候 2020-11-28 22:57

I use ScheduledExecutorService to execute a method periodically.

p-code:

ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecu         


        
7条回答
  •  爱一瞬间的悲伤
    2020-11-28 23:28

    I know that this is old question, but if somebody is using delayed CompletableFuture with ScheduledExecutorService then should handle this in that way:

    private static CompletableFuture delayed(Duration delay) {
        CompletableFuture delayed = new CompletableFuture<>();
        executor.schedule(() -> {
            String value = null;
            try {
                value = mayThrowExceptionOrValue();
            } catch (Throwable ex) {
                delayed.completeExceptionally(ex);
            }
            if (!delayed.isCompletedExceptionally()) {
                delayed.complete(value);
            }
        }, delay.toMillis(), TimeUnit.MILLISECONDS);
        return delayed;
    }
    

    and handling exception in CompletableFuture:

    CompletableFuture delayed = delayed(Duration.ofSeconds(5));
    delayed.exceptionally(ex -> {
        //handle exception
        return null;
    }).thenAccept(value -> {
        //handle value
    });
    

提交回复
热议问题