Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
226 views
in Technique[技术] by (71.8m points)

java - State of ScheduledFuture after exception has suppressed further execution

The docs for scheduleAtFixedRate() and scheduleWithFixedDelay() of ScheduledExecutorService says that:

If any execution of the task encounters an exception, subsequent executions are suppressed

Maybe a simple question, but how can I programmatically detect that this has happened (without calling ScheduledFuture.get())? Is this case reflected by isCancelled() returning true?

question from:https://stackoverflow.com/questions/65903846/state-of-scheduledfuture-after-exception-has-suppressed-further-execution

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To answer this question, I wrote a small unit test:

import static org.assertj.core.api.BDDAssertions.then;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.Test;

class ScheduledExecutorServiceLT {
    
    @Test
    void test() throws InterruptedException {
        
        final AtomicInteger counter = new AtomicInteger();
        
        final ScheduledExecutorService scheduledExecutor = Executors.newSingleThreadScheduledExecutor();
        
        final ScheduledFuture<?> scheduledFuture = scheduledExecutor.scheduleWithFixedDelay(() -> {
            if (counter.incrementAndGet() == 3) {
                throw new RuntimeException();
            }
        }, 0L, 100L, TimeUnit.MILLISECONDS);

        then(scheduledFuture.isCancelled()).isFalse();
        then(scheduledFuture.isDone()).isFalse();
        
        Thread.sleep(500L);
        
        then(counter.get()).isEqualTo(3);
        then(scheduledFuture.isCancelled()).isFalse();
        then(scheduledFuture.isDone()).isTrue();
    }
}

Conclusions:

  • the Runnable will not be executed again, after the exception occured
  • In contrast to my expectations, cancelled stays false, but
  • done becomes true, if an exception was raised

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...