0

I have a class in Java which has main() function. Lets call it A. There is another class B which implements Runnable interface. In main function of class A, I create a thread of class B and that thread will start executing its logic.

Now if lets say because of some error, the thread of class B died. Then would the process A dies along with that ? If not how can we make process A die when thread of class B dies.

Is vice versa possible, like if process A dies, then would thread of class B dies along with it ? and if not how to make it die ?

Harsha Chittepu
  • 115
  • 1
  • 8
  • No it is not, But have a look anyway. And see my answer on how to do it https://ideone.com/HlPtNX – papaya Dec 02 '20 at 06:05

2 Answers2

1

Your question is on the topic of how to catch a child thread's exception and raise it in the parent thread.

Technically like the other answer, there is no relationship between what broke in the child thread which indeed raises an exception in the parent thread.

public static void main(String[] args){
 
  Thread child = new Thread(){
    public void run () {
            try {
                Object obj = null;
                String s = obj.toString(); //this will throw NullPointer
            } catch (NullPointerException e) {
                throw new RuntimeException("Hoping this reaches the parent! as NPE but it wont", e);
            }
        }
  };
  child.start();
}

However to answer your question on how to rather do it. You can employ the use of Future<?> and have a Runnable or Callable do the equivalent and see the values of the Future Result

Here's an example which can call doSomething():

void doSomething(){
  Object s = null;
  System.out.println("You want to do something here!" +  s.toString()); // This will throw NPE
}

And now lets say you want to run this in a separate thread and catch the exception

ExecutorService executor = Executors.newFixedThreadPool(1);
Future result = pool.submit(this::doSomething());
try {
   result.get();
}catch (ExcecutionException e){
  e.printStackTrace(); //will show null pointer exception 
}

Now, your function which ran in a separate thread from the threadPool will throw an execution exception which you can chose to catch at the main/parent thread and do what you please with that failure.

Hoping this will help!


UPDATE:

Why is killing parent thread from child thread bad practise?

It's a really bad idea to terminate any thread from outside that thread. This is because the terminating thread has no idea what the target is doing and whether it is at a "safe" point to terminate. For example you might be in the middle of writing output, or making calculations, or anything. ref.1

There is never really a good candidate on why you should even stop/kill/terminate the entire JVM either. Unless in my ongoing journey of mastering java and core concepts, never have I ever had to deal with a child process killing a parent.

Just to elaborate, specifically, there is infact no concept of "child" thread or "parent" thread. JVM doesn't even keep track of which thread created which thread either.

Its mostly all based on thread groups eg. "groupA" and "groupB" and there is only a "groupA" created "groupB" which JVM knows and keeps track off.

If you really wish to stop the JVM. Just call System.exit ref.2

Consider having a look at this question also

papaya
  • 1,505
  • 1
  • 13
  • 26
  • I don't want to catch exception in Parent process. I want parent process to die, if I get any exception in child. I checked that when an exception occurs in child, if we log the exception and then use System.exit(), it is killing both parent and child. Is this a good way? or would there be any consequences? – Harsha Chittepu Dec 02 '20 at 08:17
  • You can catch the exception in parent process & then do `System.exit()` which is the ideal way. You shouldn't kill the parent thread from the child thread. It is a bad pratise. – papaya Dec 02 '20 at 12:02
  • Can you explain clearly why killing parent from child is bad practise ? Or you just point to some resource. It would be helpful to me. Thanks. – Harsha Chittepu Dec 02 '20 at 16:40
0

No; there is effectively zero relationship between a thread and the thread that started it. They have no effect on each other whatsoever. Nor do threads have any relationship to processes (which you start with ProcessBuilder or Runtime.exec and have no relationship to threads).

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72
  • Your assertion, "threads have [no] relationship to processes," could mislead newbies. You said it because there is no relationship between the `java.lang.Thread` class and the `java.lang.Process` class. But, a `Thread` instance is not a thread, and a `Process` instance is not a process, and in the context of operating systems (as opposed to a discussion about some single Java program) there usually is a very tight relationship between threads and processes. – Solomon Slow Dec 02 '20 at 14:50
  • The 'java' tag on this question is plenty of context. If someone wants to misconstrue this answer by removing it from that context, I think we can put the responsibility of this entirely on the reader. – rzwitserloot Dec 02 '20 at 15:06
  • I'm not talking about somebody who knows better. I'm talking about the people who come to this site seeking knowledge or seeking solutions to their problems. I have seen hundreds of questions on this site that were asked precisely because the OP was creating and start()ing `Thread` instances in a program, and yet they had practically no understanding of what a _thread_ actually is. – Solomon Slow Dec 02 '20 at 15:21
  • Yes, and if those people don't pick up on the context based on the tag, then they're doomed. – rzwitserloot Dec 02 '20 at 15:48