Reputation: 8995
I have a method which is long and has many inner loops, at some point in the inner loop if a certain condition is met, I want the thread to be terminated but I also want the finally block to be called so clean up also happens. How can I do this?
Upvotes: 0
Views: 159
Reputation: 21805
Remember that "terminating the thread" really just means-- or should mean!-- that the run() method exits. Put the finally outside the loop, as the last thing in the thread's/Runnable's run() method.
Upvotes: 1
Reputation: 9721
Call return;
when you want to stop. That will leave the loop and run the finally (so long as the loop with the return statement is within the try
block).
E.g.
pseudocode:
public void run () {
try {
loop {
loop {
if (condition) return;
}
}
} finally {
// always run
}
}
Upvotes: 1