Arya
Arya

Reputation: 8995

Stop current running thread with certain condition, with finally block being called

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

Answers (2)

Neil Coffey
Neil Coffey

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

xagyg
xagyg

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

Related Questions