I have a method which, conceptually, looks something like:
Object f(Object o1) {
Object o2 = longProcess1(o1);
Object o3 = longProcess2(o2);
return longProcess3(o3);
}
Where the processes themselves might also be compound:
Object longProcess1(Object o1) {
Object o2 = longSubProcess1(o1);
return longSubProcess2(o2);
}
And so forth, with the different processes potentially sitting in different modules. Most of the processes are long because they are computationally expensive, not IO-bound.
So far so good, but now I want f
as a whole to be interruptable. The recommended Java way to do that is to periodically check for the interrupted flag with Thread.interrupted()
. It's pretty straightforward, but it can quickly become cumbersome if I need to change my methods to something like:
Object f(Object o1) {
Object o2 = longProcess1(o1);
if (Thread.interrupted()) throw new InterruptedException();
Object o3 = longProcess2(o2);
if (Thread.interrupted()) throw new InterruptedException();
return longProcess3(o3);
}
Object longProcess1(Object o1) {
Object o2 = longSubProcess1(o1);
if (Thread.interrupted()) throw new InterruptedException();
return longSubProcess2(o2);
}
...
Now, I do understand the rational for working like that - it allows me to better control when the InterruptedException (for example) will be thrown, avoiding leaving objects in inconsistent states - but I am curious to know if there's a more elegant way of doing that*.
* In Java, not AspectJ, which I guess is very appropriate here but I'm stuck with Java.