2

I need to call an external method which sometimes takes indefinite time to complete.

void doMyStuff(){
  // do my stuff
  // work is being done by doStuff thread
  externalMethod(); // This is external and sometimes takes hours
  // I need to check if current thread is interrupted and then return after a certain time 
}

However, I can't afford to keep a thread engaged, so I need to terminate the process after a fixed time. I can interrupt the doStuff thread from an external thread with the help of Websphere's WorkManager API. But only sending the interrupt signal is useless unless the interrupted thread handles it.

I want to return the doStuff thread to thread pool after a certain time no matter whether the extenalMethod() returns or not. How can this be done?

ares
  • 4,283
  • 6
  • 32
  • 63
  • You could also a handy lib like this: https://google.github.io/guava/releases/snapshot/api/docs/com/google/common/util/concurrent/TimeLimiter.html – Tom Jul 22 '16 at 10:44

1 Answers1

0

Use myThread.isInterrupted() to see if the Thread is interrupted or not.

void doMyStuffs(){
    //do my stuffs
    System.out.println(myThread.isInterrupted());
}
Frank Soll
  • 420
  • 1
  • 4
  • 15
  • writing this before `extenalMethod()` is useless and if it is written after `externalMethod()` it will never be called unless `externalMethod()` returns. – ares Jul 22 '16 at 10:46
  • @Frank **Don't** use `myThread.stop()`: ["This method is inherently unsafe"](https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#stop()). – Andy Turner Jul 22 '16 at 10:47
  • @ares so... you want to check in the middle of `externalMethod()`? Well, you need to add the check to `externalMethod()`.You can't stop `externalMethod` doing anything unless it checks for interruptions already. – Andy Turner Jul 22 '16 at 10:48
  • @ares You can't write this at the end of your stuffs? – Frank Soll Jul 22 '16 at 10:50
  • @AndyTurner: That would be ideal but as the name suggests, it's managed by an external entity and can't changed. – ares Jul 22 '16 at 10:50
  • @ares this is just the nature of cooperative interruption. If the code you are running doesn't cooperate, you can't do anything about it. – Andy Turner Jul 22 '16 at 10:50