I have a class (class A for example) implements Runnable. In run method I have a try catch.I want to start a new thread in catch like this
new Thread(new A()).start();
Is this a true manner to handle exceptions?
I mean maybe its a dangerous way because the heap will get full very soon; in other words garbage collector will not garbage this object because another object has been just created in it.
It is not dangerous for that reason. If we assume that
new Thread(new A()).start();is the last thing that the original thread does before it exits, then by the time we need to GC the original thread will have exited, and hence its stack contents won’t be reachable. The only thread that will still be reachable will be the one that it still alive.However, it is dangerous if the new thread is liable to repeat the computation and then throw the same exception again, and again, and again … So if you do write code like this, it is a good idea for the application to keep a track of how often the thread is being re-launched, and pull the plug if it happens too often.
The other problem with the code as written is that the code that launched the original thread sees it die, but doesn’t hear about the new thread. That is problematic if your want to initiate shutdown by interrupting the worker threads.
If you put those two problems (and others) together, it is better for the code that launched the original thread to be responsible for relaunching.