I am facing an issue that when I run second instance of my application on the same port - I am getting SocketException: java.net.BindException: Address already in use: bind
The problem is that after getting this exception my application continue running.
After some hours I have noticed that (using "Get thread dump" tool) there are some threads still alive even after main is died.
I don't have access to that threads that means that I am not able to design it in way that I can interrupt them properly
Also, thread.interrupt, thread.setDaemon(true), thread.stop
- nothing helped me.
How to stop that threads?
I am working on very big legacy application and threads that I want to stop are created in library that I don't access
You cannot forcibly stop threads in java. The thread has to work with you: It needs to have a core loop that looks a bit like this:
while (running && !Thread.interrupted()) {
// do something that won't take long.
try {
Thread.sleep(1000L); // or some other 'wait a while' code.
} catch (InterruptedException e) {
return;
}
}
If the code of the thread doesn't have this, and you can't change it, there's not a lot you can do about it. Thread.stop
does not work on modern javas because that 'model' (throw a particular exception inside the thread, where-ever it is right now) is just something that makes for buggy software (because locks and such are unlikely to be properly closed and such): Therefore it has been deprecated for a decade now and no longer works at all. Even if it did, a thread can prevent you from stopping it.
Which leads us to the one surefire way to definitely, absolutely, kill a thread:
System.exit(0);
that'll do it. It is a common misconception that 'nice' code style is to never forcibly exit like that, with the right style being to tell all (non-daemon-status) alive threads to clean up their business and exit.
This is mistaken. Just exit. Your code should be written not to need to do any cleanup of resources, because if you write it like that, it means if someone trips over a powercable or java is hard-killed, your app just created a mess. The few cleanup jobs you do have should be registered as shutdown hooks.
So, if you want to quit the VM, just System.exit
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments