Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread.stop() and finally [duplicate]

I created a following Class named as ThreadClass (which is a thread as you can see),its structure is something like the following

class SomeTask implements Runnable
{
    boolean someCondition=true;
    public void run() {
        try
        {
            while(someCondition)
            {
            //Here goes the Process Code
            }
        }
        catch(Exception errorException)
        {
            //Catching the Exception
        }
        finally
        {
            ////I expect that this finally should run every time ,whatever happens in the world
        }
    }

}

My question is about the finally block and the stop() method

As above class is implementing Runnable, so I can create the object of this class and start a thread of it by calling start() method.I am also aware of the fact that I can stop this thread by using stop() (Yes , I know it is deprecated) method .

What I want to clarify myself is that, if somehow I need to call the stop method on the ThreadClass's object, then can I rely on the finally block to execute even if the thread is stopped by calling stop() as I am doing some important closing things in the finally block.

like image 509
nobalG Avatar asked Oct 19 '22 15:10

nobalG


1 Answers

Thread#stop works by throwing a ThreadDeath exception, it doesn't obliterate the thread instantaneously the way System.exit blows away the JVM. ThreadDeath can even be caught, although that's not a good idea. So try blocks are still relevant.

However, complicating this is that if the thread has stop called on it multiple times then, if the second stop is called when the thread is in a finally block then it could be thrown from the finally block so that the finally block would not complete then. And if the thread's cleanup takes a while then it might be likely that stop could be called more than once on it.

Or even if you only call stop once, if at the time that stop is called the thread happens to be already executing its finally block, then the stop would interfere with completing the finally block.

This is similar to what the technotes on Thread primitive deprecation point out:

1) A thread can throw a ThreadDeath exception almost anywhere. All synchronized methods and blocks would have to be studied in great detail, with this in mind.

2) A thread can throw a second ThreadDeath exception while cleaning up from the first (in the catch or finally clause). Cleanup would have to repeated till it succeeded. The code to ensure this would be quite complex.

So there are some cases that are problematic, it would be very difficult to make sure cleanup gets done properly. James' comment is correct, if at all possible you should use interruption for this kind of thing so that the thread can reliably finish its business.

like image 165
Nathan Hughes Avatar answered Oct 24 '22 06:10

Nathan Hughes