Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to interrupt a function call in Java

I am trying to use a Third Party Internal Library which is processing a given request. Unfortunately it is synchronous in nature. Also I have no control on the code for the same. Basically it is a function call. This function seems to a bit erratic in behavior. Sometimes this function takes 10 ms to complete processing and sometimes it takes up to 300 secs to process the request.

Can you suggest me a way to write a wrapper around this function so that it would throw an interrupted exception if the function does not complete processing with x ms/secs. I can live with not having the results and continue processing, but cannot tolerate a 3 min delay.

PS: This function internally sends an update to another system using JMS and waits for that system to respond and sends apart from some other calculations.

like image 571
Prasanth Kumar Avatar asked May 29 '26 22:05

Prasanth Kumar


1 Answers

Can you suggest me a way to write a wrapper around this function so that it would throw an interrupted exception if the function does not complete processing with x ms/secs.

This is not possible. InterruptException only gets thrown by specific methods. You can certainly call thread.stop() but this is deprecated and not recommended for a number of reasons.

A better alternative would be for your code to wait for the response for a certain amount of time and just abandon the call if doesn't work. For example, you could submit a Callable to a thread pool that actually makes the call to the "Third Party Internal Library". Then your main code would do a future.get(...) with a specific timeout.

// allows 5 JMS calls concurrently, change as necessary or used newCachedThreadPool()
ExecutorService threadPool = Executors.newFixedThreadPool(5);
...
// submit the call to be made in the background by thread-pool
Future<Response> future = threadPool.submit(new Callable<Response>() {
   public Response call() {
      // this damn call can take 3 to 3000ms to complete dammit
      return thirdPartyInternalLibrary.makeJmsRequest();
   }
});
// wait for some max amount of time
Response response = null;
try {
    response = future.get(TimeUnit.MILLISECONDS, 100);
} catch (TimeoutException te) {
    // log that it timed out and continue or throw an exception
}

The problem with this method is that you might spawn a whole bunch of threads waiting for the library to respond to the remote JMS query that you would not have a lot of control over.

No easy solution.

like image 86
Gray Avatar answered May 31 '26 12:05

Gray



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!