I have a scenario where n threads from an executor thread pool call different web services but all threads should finish their task within a specified time limit else all the pool threads should quit processing their task and return back to their executors pool.
The code I have written works well but the only scenario which is bothering me is that I am not able cancel the already started task i.e a thread waiting for an external web service response.
I understand that future.cancel(true) can not help me achieve this but is there any way I can achieve what I am looking for?
I can not afford to wait for a web service response indefinitely with a pools thread. Thanks in advance !
public class CallProductServiceTask implements Callable<Object>{
public Object call(){
// Call to product service
// For SOAP Client
ProductRequest productRequest = new ProductRequest("prodId");
ProductResponse response = (ProductResponse)webServiceTemplate.marshalSendAndReceive(productRequest);
// For REST Client
ResponseEntity<ProductResponse> response = restTemplate.exchange(productResourceUrl, HttpMethod.POST, productRequest, ProductResponse.class);
}
}
class Test{
ExecutorService executor = Executors.newFixedThreadPool(2);
public static void main(String args[]){
Future ft = executor.submit(new CallProductServiceTask());
try{
Object result = ft.get(3, TimeUnit.SECONDS);
} catch (TimeoutException e) {
boolean c = future.cancel(true);
System.out.println("Timeout " + c);
} catch (InterruptedException | ExecutionException e) {
System.out.println("interrupted");
}
System.out.println("END");
}
}