I have a method that creates a future:
@Service
public class TestService {
@Async
public Future<TestClass> testCancelFuture() throws InterruptedException {
TestClass testClass = new TestClass();
testClass.loop();
return new AsyncResult<TestClass>(testClass);
}
}
And this is my TestClass
public class TestClass {
public void loop() throws InterruptedException {
for (int i=0; i<100; i++) {
System.out.println("[" + i + "] loop");
Thread.sleep(1000);
}
}
}
Now, I invoke the method testCancelFuture and cancel it:
@Controller
@RequestMapping("/test")
public class TestController() {
@Autowired
TestService testService;
@RequestMapping(method = RequestMethod.GET)
public String testMethod () throws InterruptedException {
Future<TestClass> test = testService.testCancelFuture();
test.cancel(true);
return "test";
}
}
I would expect the loop to stop , as i cancel the future soon after starting it. However the loop keep going. So, how can I stop the loop in the future ?