Is this a correct way to stop Execution Task

Posted by Yan Cheng CHEOK on Stack Overflow See other posts from Stack Overflow or by Yan Cheng CHEOK
Published on 2011-01-16T18:10:22Z Indexed on 2011/01/16 18:53 UTC
Read the original article Hit count: 225

Filed under:
|

I came across code to stop execution's task.

private final ExecutorService executor = Executors.newSingleThreadExecutor();

public void stop() {
    executor.shutdownNow();
    try {
        executor.awaitTermination(100, TimeUnit.DAYS);
    } catch (InterruptedException ex) {
        log.error(null, ex);
    }
}


public Runnable getRunnable() {
    return new Runnable() {
        public void run() {
            while (!Thread.currentThread().isInterrupted()) {
                // What if inside fun(), someone try to clear the interrupt flag?
                // Say, through Thread.interrupted(). We will stuck in this loop
                // forever.
                fun();
            }
        }
    };
}

I realize that, it is possible for Runnable to be in forever loop, as

  1. Unknown fun may Thread.sleep, clear the interrupt flag and ignore the InterruptedException
  2. Unknown fun may Thread.interrupted, clear the interrupt flag.

I was wondering, is the following way correct way to fix the code?

private final ExecutorService executor = Executors.newSingleThreadExecutor();
private volatile boolean flag = true;

public void stop() {
    flag = false;
    executor.shutdownNow();
    try {
        executor.awaitTermination(100, TimeUnit.DAYS);
    } catch (InterruptedException ex) {
        log.error(null, ex);
    }
}


public Runnable getRunnable() {
    return new Runnable() {
        public void run() {
            while (flag && !Thread.currentThread().isInterrupted()) {
                // What if inside fun(), someone try to clear the interrupt flag?
                // Say, through Thread.interrupted(). We will stuck in this loop
                // forever.
                fun();
            }
        }
    };
}

© Stack Overflow or respective owner

Related posts about java

Related posts about multithreading