Search code examples
javamultithreadinglockup

Best way to identify and dispose locked thread in java


I have to call a function 3rd party module on a new thread. From what I've seen, the call either completes quickly if everything went well or it just hangs for ever locking up the thread. What's a good way to start the thread and make the call and wait for a few secs and if the thread is still alive, then assuming it's locked up, kill (or stop or abandon) the thread without using any deprecated methods.

I have something like this for now, but I'm not sure if this is the best way to do it and I want to avoid calling Thread.stop() as it's deprecated. Thanks.

private void foo() throws Exception
{
        Runnable runnable = new Runnable()
        {

            @Override
            public void run()
            {
                    // stuff that could potentially lock up the thread.
            }
        };
        Thread thread;
        thread = new Thread(runnable);
        thread.start();
        thread.join(3500);
        if (thread.isAlive())
        {
            thread.stop();
            throw new Exception();
        }

}

Solution

  • public void stop() {
            if (thread != null) {
               thread.interrupt();
            }
        }
    

    See this link on How to Stop a Thread, it covers the subject well