Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for interrupt in zero loop thread in java

I need to time limit a long running function which has zero loops. I run that function using a Callable and call get on the future with a timeout value. AFAIU, future.cancel(true) will set the interrupt flag for the function thread. But until and unless I check and handle Thread.isInterrupted() in longRunningFunction() my code will be unaware that it has to exit and even after shutdownNow() the function will not terminate.

  • How to check for interrupted in longRunningFunction()? The check needs to be prompt i.e if the check is put at specific points then until those points are hit, the thread will not handle the interrupt.
  • Is there any other graceful way to time limit function?
  • Why can't I just kill all threads in executor pool? As per JavaDocs for ExecutorService the pool will never terminate until the threads handle interrupt and terminate themselves.
public class Test {

  public void longRunningFunction() {
    /*
   Long running code without loop
     */
  }

  public Void call() {
    try {
      longRunningFunction()
    } catch (InterruptedException exception) {
      logger.error("{} Error : {}", TAG, exception.getStackTrace().join("\n"))
    } catch (Exception exception) {
      logger.error("[call]{} Error : {}", TAG, exception.getStackTrace().join("\n"))
    }
  }

  public static void main(String[] args) {
    ExecutorService executor = Executors.newSingleThreadExecutor()
    Future<Void> future = executor.submit(new Test())
    int timeoutSeconds = 5
    println "Setting timeout to " + timeoutSeconds
    try {
      future.get(timeoutSeconds, TimeUnit.SECONDS) 
    } catch (TimeoutException e) {
      future.cancel(true)
      logger.error("Could not finish processing within {} seconds", timeoutSeconds)
    } finally {
      executor.shutdownNow()
      executor.awaitTermination(3, TimeUnit.SECONDS)
      logger.error("Shutting down")
    }
  }
}

Edit The question linked for marking duplicate suggests that shared variables are the way to go, which is a known fact as mentioned in the question. The question is to how seamlessly check for that boolean flag i.e Thread.isInterrupted.

like image 886
ankshah Avatar asked May 20 '26 14:05

ankshah


1 Answers

The only way beyond checking the isInterrupted flag is to kill the thread, control the current state and reconcile it somehow. You can obviously encapsulate this inside a class that makes it appear as the isInterrupted flag has been checked.

like image 90
snovelli Avatar answered May 22 '26 04:05

snovelli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!