Check for interruption in zero loop thread in java

I need to constrain a long running function that has zero cycles. I run this function with Callable

and call get

in the future with a timeout value. AFAIU, will future.cancel(true)

set the interrupt flag for the function thread. But until I check and handle Thread.isInterrupted () in longRunningFunction()

, my code won't know that it should exit, and even after the shutdownNow()

function is completed.

  • How do I check for interruption in longRunningFunction()

    ? The check should be a hint, if the check is placed at certain points, then until these points are removed the thread will not handle the interrupt.
  • Is there any other nifty way to time limit?
  • Why can't I just kill all threads in the executor pool? According to the JavaDocs for ExecutorService, the pool will never complete until the threads handle the 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 tagging duplicates suggests shared variables are the path, which is a known fact mentioned in the question. The question is how easy it is to check this boolean ie flag Thread.isInterrupted

.

+3


source to share


1 answer


The only way to check a checkbox isInterrupted

is to kill the thread, manage the current state, and reconcile it in some way. You can obviously encapsulate this inside a class that makes it appear as a flag isInterrupted

.



+1


source







All Articles