Taras
Taras

Reputation: 2576

How to stop thread in java, when it is hanged?

How to stop thread in Java, when it is hanged? I can't use interrupt(), because I can't check interruption flag within hanged thread. Also stop() is deprecated, because it's unsafe.

Thanks in advance.

update: thread hangs on Socket.connect():

Method m = device.getClass().getMethod("createInsecureRfcommSocket",
            new Class[] { int.class });
final BluetoothSocket socket = (BluetoothSocket) m.invoke(device, port);
socket.connect();

Upvotes: 1

Views: 234

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533492

The only way to shut a thread down cleanly is to have to stop itself gracefully.

If a Thread is blocked on a resource like a Socket read or write, you can try closing it and it will trigger an IOException. How to unblock a thread depends entirely on why it is blocked.

If you are forcing a thread to stop, you have given up the idea it will be stopped gracefully, in which case Thread.stop() or System.exit() are your only options.

Upvotes: 3

Related Questions