I want to cancel the task sent to the ExecutorService, which will allow the corresponding thread to select a new task from the queue.
Now this question has many answers in this forum .... for example, checking Thread.currentThread().interrupt() or catch (InterruptedException e) . But if the control flow covers several methods, then performing these checks makes the code awkward. Therefore, if possible, suggest some elegant ways in java to achieve this functionality.
The problem I am facing is that future.cancel does not actually cancel the task. Instead, it simply throws an InterruptedException executing task and is responsible for flagging itself and freeing the thread.
So what I did was that I had to put a block of code below whenever an exception was thrown at any place in the execution, which obviously does not look good!
if(e instanceof InterruptedException) { throw e; }
So, how to achieve this functionality in the following code fragment:
public class MonitoringInParallelExp { public static void main(String[] args) throws InterruptedException { MyClass1 myClass1 = new MyClass1(); ExecutorService service = Executors.newFixedThreadPool(1); Future<String> future1 = service.submit(myClass1); Thread.sleep(2000); System.out.println("calling cancel in Main"); future1.cancel(true); System.out.println("finally called cancel in Main"); service.shutdown(); } } class MyClass1 implements Callable<String> { @Override public String call() throws Exception { try{ MyClass2 myClass2 = new MyClass2(); myClass2.method2(); } catch (Exception e){ if(e instanceof InterruptedException) { System.out.println("call:"+"e instanceof InterruptedException="+"true"); throw e; } System.out.println("Got exception in method1. " + e); } System.out.println("returning Myclass1.method1.exit"); return "Myclass1.method1.exit"; } } class MyClass2 { public void method2() throws Exception{ try{ MyClass3 myClass3 = new MyClass3(); myClass3.method3(); } catch (Exception e){ if(e instanceof InterruptedException) { System.out.println("method2:"+"e instanceof InterruptedException="+"true"); throw e; } System.out.println("Got exception in method2. " + e);
source share