Exceptions in child thread

Hello,
I am writing a few classes that i plan on reusing a lot. The classes create
child threads that do ... work. If a exception is cought in one of the child threads
I want to send it up to the caller. I can't declare the run() method of a thread to throw
an exception ... so could someone suggest a nice clean way to get the cought exception back to the caller.
Thanks,
jd

To answer that question, you need to think about what the "caller" (the parent thread) is doing while the child thread is executing.
Is it waiting in a join() call?
Is it doing its own processing?
What do you expect it to do when a child thread throws an exception?
(The answer to the bolded questions may drive how you report the exception back to the parent thread.)
With a typical single-threaded chain of calls, when an exception is encountered, there is a well defined stack back to the main() method--main called foo which called bar which called baz, etc. In a multithreaded context, the parent thread could potentially be executing any of its instructions when the exception occurs. Remember, the parent thread and child thread are executing independently of each other.

Similar Messages

  • Why can't I interrupt the main thread from a child thread with this code?

    I am trying to find an elegant way for a child thread (spawned from a main thread) to stop what its doing and tell the main thread something went wrong. I thought that if I invoke mainThread.interrupt() from the child thread by giving the child thread a reference to the main thread, that would do the trick. But it doesn't work all the time. I want to know why. Here's my code below:
    The main class:
    * IF YOU RUN THIS OFTEN ENOUGH, YOU'LL NOTICE THE "Child Please!" MESSAGE NOT SHOW AT SOME POINT. WHY?
    public class InterruptingParentFromChildThread
         public static void main( String args[] )
              Thread child = new Thread( new ChildThread( Thread.currentThread() ) );
              child.start();
              try
                   child.join();
              catch( InterruptedException e )
    // THE LINE BELOW DOESN'T GET PRINTED EVERY SINGLE TIME ALTHOUGH IT WORKS MOST TIMES, WHY?
                   System.out.println( "Child please!" );
              System.out.println( "ALL DONE!" );
    The class for the child thread:
    public class ChildThread implements Runnable
         Thread mParent;
         public ChildThread( Thread inParent )
              mParent = inParent;
         public void run()
              System.out.println( "In child thread." );
              System.out.println( "Let's interrupt the parent thread now." );
              // THE COMMENTED OUT LINE BELOW, IF UNCOMMENTED, DOESN'T INVOKE InterruptedException THAT CAN BE CAUGHT IN THE MAIN CLASS' CATCH BLOCK, WHY?
              //Thread.currentThread().interrupt();
              // THIS LINE BELOW ONLY WORKS SOMETIMES, WHY?
              mParent.interrupt();
    }

    EJP wrote:
    I'm not convinced about that. The wording in join() suggests that, but the wording in interrupt() definitely does not.Thread.join() doesn't really provide much in the way of details, but Object.wait() does:
    "throws InterruptedException - if any thread interrupted the current thread +before+ or while the current thread was waiting for a notification. The interrupted status of the current thread is cleared when this exception is thrown."
    every jdk method i've used which throws InterruptedException will always throw if entered while a thread is currently interrupted. admitted, i rarely use Thread.join(), so it's possible that method could be different. however, that makes the thread interruption far less useful if it's required to hit the thread while it's already paused.
    a simple test with Thread.sleep() confirms my expected behavior (sleep will throw):
    Thread.currentThread().interrupt();
    Thread.sleep(1000L);

  • Initialize QTMovie in a child thread by passing Movie object.

    I'm working on an Qt (Qt framework) application in which I'm making use of a .mm file to call MAC specific functions.
    I need to initialize QTMovie in a child thread by passing Movie object.
    [QTMovie movieWithQuickTimeMovie:movie disposeWhenDone:TRUE error:nil]
    It appears like I have to initialize QTMovie in main thread. I came across performSelectorOnMainThread which might be of some help. Could anyone please show me the right usage of the same?
    I need to call a method using performSelectorOnMainThread by passing the Movie object to it and which returns the initialized QTMovie object.
    Thanks in advance.

    Ah, you seem to be on to something, there. The main thread gives
    sun.misc.Launcher$AppClassLoader@111f71
    while the child thread gives null. The same occurs whether the experiment is in
    the same JVM instance or not.
    So presumably this means I need to get the context loader from the main thread
    and set it in the child thread manually!?
    - Angus.
    Patrick Linskey wrote:
    Angus Monro <[email protected]> writes:
    Okay.... I'm not really sure what you're asking for. What I've done is
    printed the ClassLoader object as given by
    com.solarmetric.util.app.Prefs.class.getClassLoader(), along with its
    parent recursively up the tree of loaders. This gave:
    sun.misc.Launcher$AppClassLoader@111f71
    sun.misc.Launcher$ExtClassLoader@256a7c
    This result was exactly the same irrespective of whether I did it from the
    main thread or the child thread. But the exception still happens only the
    child thread.Sorry, I should have been more clear. Can you print out the current
    thread's context's classloader?
    System.out.println (Thread.currentThread ().getContextClassLoader ());
    Also, what happens if you run the test in the main thread and then in
    the child thread, all in the same JVM?
    -Patrick
    - Angus.
    Patrick Linskey [email protected]
    SolarMetric Inc. http://www.solarmetric.com

  • TIme taken by Child threads to execute

    Hi
    I have a small query related to multithreading. I have a main thread launching a few Child threads. Now I want to check how much time all the 10000 child threads are taking to execute. I cannot write a System.currentTimeMillis(); before a main thread exits because I want the Child threads to keep executing even after the Main thread exits because I do not know how much time the child threads will take. I have made the child threads as non-deamon
    class ChildThread implements Runnable {
         Thread t;
         int i;
         ChildThread(int i) {
              t = new Thread(this, "SMS Thread");
              this.i = i;
              t.setDaemon(false);
              t.start();
         public void run() {
              try {
                   System.out.println(i);
              } catch (Exception smsex) {
                   System.out.println("Exception occured while sending message :"
                             + smsex.getMessage());
                   smsex.printStackTrace();
    public class MainThread {
         public static void main(String args[]) {
              long start = System.currentTimeMillis();
              ChildThread thread = null;
              try {
                   for (int i = 10000; i > 0; i--) {
                        thread = new ChildThread(i); // create a new thread
              } catch (Exception e) {
                   System.out.println("Main thread interrupted.");
              long end = System.currentTimeMillis();
              System.out.println("Main thread exiting. Took " + (end - start)
                        + " ms.");
    }

    This is a sample i have assumed.. dont have the complete code.
    I will just explain this
    Create an executor service object in a class called ThreadDispatcher.
    And create your chileThread as given below
    class ChildThread implements Runnable {
         ChildThread() {                    
         public void run() {
              try {
                   System.out.println(i);
              } catch (Exception smsex) {
                   System.out.println("Exception occured while sending message :"
                             + smsex.getMessage());
                   smsex.printStackTrace();
    }And the ThreadDispatcher class as below -This is just to beautify the code :)
    public class ThreadUtil {
    private static ExecutorService exec = Executors.newFixedThreadPool(some_value);
    public static List<Future> executionResults = new ArrayList<Future>();
    }And finaly come to the main Thread class
    public class MainThread {
         public static void main(String args[]) {
              ChildThread thread = null;
              try {
                             long start = System.currentTimeMillis();
                   for (int i = 10000; i > 0; i--) {
                        thread = new ChildThread(i); // create a new thread
                                    ThreadDispatcher.executionResults.add(ThreadDispatcher.exec.submit(thread));
              } catch (Exception e) {
                   System.out.println("Main thread interrupted.");
                    //Here place the while loop to check each thread status
                     while (ThreadDispatcher.executionResults.size() > 0) {
                   try {
                        Future task = ThreadDispatcher.executionResults.get(0);
                        task.get();//Wait until the thread finishes execution
                                    ThreadDispatcher.executionResults.remove(task);
                   } catch (InterruptedException e) {
                        e.printStackTrace();
                   } catch (ExecutionException e) {
                        e.printStackTrace();
              long end = System.currentTimeMillis(); //This time will probably be the end time.
              System.out.println("Main thread exiting. Took " + (end - start)
                        + " ms.");
    }Hope this will be helpful...

  • Can a parent thread kill a child thread?

    I'm writing a multi-threaded application in which it is possible for one of the threads to go into an infinite loop. Is there any way for a parent thread to actually kill the child thread that has gone into the infinite loop? Of course the parent thread won't actually be able to discern whether or not the child thread is in an infinite loop. I would specify some time out value, and when it has been exceeded, then I would want to kill the child thread. Is this possible without setting any sort of flag that the child would read, because once it gets stuck inside an infinite loop, there will be no way to read the flag.

    Here's an example of a program that I wrote to simply ping a server. It works somewhat backwards from what you were looking for (the child interrupts the parent) but should provide some clue:
    import java.net.*;
    import java.io.*;
    import java.util.Date;
    public class ServerPing extends Thread {
      String [] args;
      public static void main(String[] args) throws Exception {
        ServerPing sp = new ServerPing(args);
        sp.start();
      ServerPing(String [] args) {
        this.args = args;
      public void run() {
        Pinger pinger = new Pinger(this);
        pinger.start();
        try {
          sleep(30000);
        catch (InterruptedException x) {
          System.exit(0); // this is ok. It means the pinger interrupted.
        System.out.println("TIMEOUT");
        System.exit(1);
    class Pinger extends Thread {
      Thread p = null;
      Pinger (Thread p) {
        this.p = p;
      public void run() {
        try {
          URL simpleURL = new URL("http://localhost:7001/ping.jsp");
          BufferedReader in = new BufferedReader(new InputStreamReader(simpleURL.openStream()));
          String inputLine;
          while ((inputLine = in.readLine()) != null)
          System.out.println(inputLine);
          in.close();
          p.interrupt();   // <<-- interrupt the parent
        catch (Exception x) {
          x.printStackTrace();
    }

  • Java Thread - difficulty while passing value from parent to child thread

    Hi All,
    I am calling a java program from a unix script .
    My oblectives are
    1)to pass value from scripts to main java class
    2)main class should create a child thread and pass data to child and should return control back to script
    3)child thread should run independtly of parent
    The calling unix script is part of process and hence should return control back to its calling script immediately.
    Findings
    1)Without passing data thru setter getter /constructor method to child thread my objectives are met
    2)When I pass the data from parent thread to child thread calling unix scripts wait till child thread finishesh its working
    call.scr
    java Main <list of Arguments>
    Main.java
    public class Main
                 public static void main(String args[]) throws Exception
                 String data2="Z";
                 String data1=null;
                 for(int i=0;i<args.length;i++)
                      data2=data2+","+args;
    data1=data2;
    Child cu=new Child();
    cu.setData(data1);
    data2=null;
    data1=null;
    cu.start();
    Child.javaclass Child extends Thread
    public String data;
    void setData(String data)
    this.data=data;
    public void run()
    ----------> processing on data
    I think due to passing of data from parent thread to child thread (Inter thread data communication/Inter process communication)
      the threads are not working as desired.
    Plz anybody can suggest something.....
    Thanx.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    aschin,
    You seem to be confusing Java Threads with Operating System Processes.
    If you want you're java program to run in the unix background then you'll need to run it in the unix background. Java (being o/s agnostistic) doesn't provide process manipulation functionality (which would include the ability to throw itself into the background, as a C program can) in the standard API, and it's hard to imagine any third party producing anything as low level as a process controler... so yeah, just start the java program in the background... and you'll need to workout some interprocess communication protocol... named pipes have worked well for me in the past, as they doesn't suffer from the quit same performance issues as real disk files.
    Good luck. Keith.

  • How can I pass an exception from one thread to another thread

    If I create a new class, that will extends the class Thread, the methode run() can not be use with the statement Throws Exeption .
    The question now: Is there any possibility to pass an exception from one thread to another thread?
    Thx.

    It really depends on what you want to do with your exception. Is there some sort of global handler that will process the exceptions in some meaningful way? Unless you have that, there's not much point in throwing an exception in a thread, unless you simply want the stack trace generated.
    Presuming that you have a global handler that can catch exceptions, nest your Exception subclass inside a RuntimeException:
    public class NestedRuntimeException extends RuntimeException
        private final m_nestedException;
        public NestedRuntimeException(final Exception originalException)
            super("An exception occurred with message: " + originalException.getMessage());
            m_nestedException;
        public Exception getNestedException()
            return m_nestedException;
    }Your global handler can catch the NestedRuntimeException or be supplied it to process by the thread group.

  • How to kill parent and child thread in sequnece

    Hello freinds,
    I have one class FirstClass which creates one thread Pserver and Pserver creates three threads then how to kill parent Pserver and child threads.........

    define a method that requests that the parent thread terminate itself, and within the code called when the thread is shutting itself down, have it do something similar to its child threads: call methods that request they shutdown themselves.
    One common way to do this is to interrupt the thread.

  • Waiting the main thread till all child thread has completed

    I am in the process of developing a batch application in Java 5.0 which extensively uses the java.util.concurrency API. Here is a small description of what the batch process will do,
    1. Retrieve values from DB and populate a blocking queue in main thread.
    2. Instantiate a Threadpool by calling, Executors.newFixedThreadPool(2)
    3. Invoking the following block of code from the main thread,
    while(!iBlockingQueue.isEmpty()) {
        AbstractProcessor lProcessor = new  DefaultProcessor((BusinessObject)iBlockingQueue.remove());
        iThreadPool.execute(lProcessor);
    }DefaultProcessor is a class that extends Thread.
    4. Invoking the following block of code from the main thread,
    iThreadPool.shutdown();
    try {
         iThreadPool.awaitTermination(30, TimeUnit.SECONDS);
         } catch (InterruptedException interruptedException) {
              iLogger.debug("Error in await termination...", interruptedException);
    Since, this is the first time I am using the java.util.concurrency API, I want to know whether this is the right way to wait for all the child threads to complete before executing further statements in the main (parent) thread. Or do I necessariliy have to call join() to ensure that the main thread waits for all the child threads to finish which can only happen when the queue is empty.
    Please note here that as per the requirements of the application the blocking queue is filled only once at the very beginning.
    I will appreciate any inputs on this.
    Thanks.

    looks like you would be waiting on a queue twice, once in the loop and again, under the hood, in the threadpool's execute()
    the threadpool's internal queue is all that is needed
    if your iBlockingQueue is also the threadpool's internal queue, you might have a problem when you remove() the BusinessObject
    by making DefaultProcessor extend Thread you are, in effect, implementing your own threadpool without the pooling
    DefaultProcessor need only implement Runnable, it will be wrapped in a thread within the pool and start() called
    to implement a clean shutdown, I suggest writing DefaultProcessor.run() as an infinite loop around the blocking queue poll(timeout) and a stop flag that is checked before going back to poll
    class DefaultProcessor implements Runnable {
      private BlockingQueue myQ;
      private boolean myStopFlag;
      DefaultProcessor( BlockingQueue bq ) { myQ = bq; }
      public void run() {
        BusinessObject bo = null;
        while( !myStopFlag && (bo=myQ.poll( 10, SECONDS )) ) {
          // business code here
      public void stop() { myStopFlag = true; }
    } Now, after iThreadPool.shutdown(), either call stop() on all DefaultProcessors (or alternatively send "poison" messages to the queue), and give yourself enough time to allow processing to finish.

  • Exception handling in threads

    Hi all,
    I'm trying to figure out an efficient way for my main process that creates a few threads to know if an exception occurred in any of them. The best solution I think of is using Callable to return any exceptions that occurred. I don't need the main process to know what the exception was exactly (logging will happen in the thread), just that the thread ended prematurely. Is there another way to test for this?
    Any suggestions would be appreciated!
    Leon

    how would this idea work in your case?
    public interface ExceptionCallback {
      public void exception(Worker w);
    public class Main implements ExceptionCallback {
      public static main(String[] args) {
        (new Main()).init();
      private void init() {
        (new Worker(this)).start();
      public void exception(Worker w) {
        Thread.State ts = w.getState();
         ... // deal with any problems
    public class Worker extends Thread {
      ExceptionCallback main;
      Worker(ExceptionCallback ec) {
        main = ec;
      public void run() {
        try {
        } finally {
              main.exception(this);
    }detecting if a thread exits abnormally sounds difficult. the only thing i have learned is that a thread can never die without invoking the "finally" block.
    and, maybe it is best to have the thread inform the main method when it exits, rather than have the main method try and monitor each thread? that's what i tried to do in my code.

  • Can i catch an exception from another thread?

    hi,guys,i have some code like this:
    public static void main(String[] args) {
    TimeoutThread time = new TimeoutThread(100,new TimeOutException("超时"));
    try{
    t.start();
    }catch(Exception e){
    System.out.println("eeeeeeeeeee");
    TimeoutThread will throws an exception when it runs ,but now i can't get "eeeeeeeeeee" from my console when i runs the main bolck code.
    i asked this question in concurrent forums,somebody told me that i can't.so ,i think if i can do this from aspect of jvm.
    thank you for your help
    Edited by: Darryl Burke -- Double post of how to catching exceptions from another thread locking

    user5449747 wrote:
    so ,i think if i can do this from aspect of jvm. What does that mean? You think you'll get a different answer in a different forum?
    You can't catch exceptions from another thread. It's that easy. You could somehow ensure that exceptions from that other thread are always caught and somehow passed to your thread, but that would be a different thing (you would still be catching the exception on the thread it is originating from, as is the only way).
    For example you can use setUncaughtExceptionHandler() on your thread to provide an object that handles an uncaught exceptions (and you could pass that uncaught exception to your other thread in some way).

  • Exception in handler thread. in BI Presentation Services

    Hi
    We are revicing following error in OBIEE 11g presentation services
    Dose anyone know the reason?
    +Exception in handler thread. An error occurred during execution of "send". Broken pipe [Socket:82]^M+
    Error Codes: ETI2U8FA^M
    Location: saw.rpc.variablemos.finalize, saw.rpc.server.responder, saw.rpc.server, saw.rpc.server.handleConnection, saw.rpc.server.dispatch, saw.threadpool, saw.threadpool, saw.threads^M
    +[[+
    File:socketrpcserver.cpp
    Line:565
    Location:
    saw.rpc.server.handleConnection
    saw.rpc.server.dispatch
    saw.threadpool

    Hi ,
    By any chance have you changed anything in socketrpcserver.cpp ??
    looks like the file has changed or not copied propelry.
    Open the socketrpcserver.cpp in vi editor and check if it contains any control M charatcers (^M).
    Or
    It can be because of the JavaHost process not running. Check instanceconfig.xml (check the port number)
    If you have changed the JavaHost Port Number (default is 9810), you need to update it in instanceconfig.xml.
    <JavaHostProxy>
    <Hosts><Host address="myhost.domain.com" port="newport>" /></Hosts>
    </JavaHostProxy>

  • Running bat file in Child Thread

    Hi
    Please first of all i will tell you my application flow.
    I have an application you can say Parent Process/application , In execution of this Process or thread my application start/run batch file before dying using "exec() funtion" .In batch i have some scripts.and after initiating batch command my application main process ends up.
    Now problem is
    I am not sure that child process or Batch script which main program called is alive when my main application closed or its running?
    i want to see its output on console?
    Is it possible that Parent Thread ends up and child is still running , how can i achieve this .
    OR is it possible that i create seprate thread to start batch and my main thread ends. and i will show batch file output on console.

    I'm having a hard time understanding what you're
    saying, so here are a few general things that may be
    relevant:Sorry for that , well you are very much near which i want.But Thanks
    * Child threads can keep running after the thread
    that spawned them dies. You don't need to do anything
    special here.
    * The VM will exit when there are no more non-daemon
    threads running. So if you make all threads other
    than your main thread daemons, then when main ends,
    the rest of the threads will die and the VM will
    exit. See Thread.setDaemon.Here in above two point i have confusion.that by VM you mean Parent process,
    VM is parent process of all java programs that we run.please clarify this
    Lets say VM is parent process than your first statement is no valid as in first you say that parent die it will not effect child threads.
    well i have test this case with my program i write a program like
    public class ThreadTest
         public static void main(String [] arg)
              Work work=new Work(1000);
              System.out.println("Main Thread Started"+work.isDaemon());
              work.setDaemon(false);
              work.start();
              System.out.println("Main Thread stopped");
    class Work extends Thread
         int count=0;
         public Work(int cou)
              super("Workere");
              count=cou;
         public void run()
              while(count-->0)
                   System.err.println("Worker Thread is running................");
    }Now bydefault work thread is deamon,when all work thread steps executed program finished, tell me here as its concurent execution,
    main is alive or die when it execute its all statements or it waits for work thread which it spawned.
    Secondly when i change deamon to true, when main statements finished it also stoped work thread.mean work thread just print some messages.
    Actually what i want is that, when my main progam ends up, before ending it spawned new thread which start batch script and i want to see its output on seprate screen just like when we run IE with exec it starts IE window.
    Hope fully this time its clear

  • Closing all child threads when closing the stage

    I have multiple instances of child threads which are started and should continue to execute in till the applications exits.
    I have classes which extends Task and I create the threads as
    new Thread(object of the class).start();
    when it comes to interrupting/stoping (dont know which one is correct, please let me know) the threads which should be done inside
    primaryStage.onCloseOperation(){}
    here i want to end all child threads but since my threads are spreaded across different classes, my not having a clear picture how to achieve this.
    I know there is some designing problem, in my application, when it comes to threads, but I am not able to figure out how to resolve out.

    Use thread.setDaemon(true) Thread (Java Platform SE 7 )
    I suggest to use the Executor Framework and a ThreadFactory, to only need to create a daemon thread once.
    Something like this:
    Executor executor = Executors.newCachedThreadPool(new ThreadFactory() {
                @Override
                public Thread newThread(Runnable r) {
                    Thread thread = new Thread(r);
                    thread.setDaemon(true);
                    return thread;
    And then use it like this:
    executor.execute(yourTaskOrRunnable);
    When there are only daemon threads running, the JVM will halt and also stop all daemon threads.

  • Running child thread till completion even after main thread is terminated

    I am running some task in background using Task and Service Api's. When the main application spawns few threads, can the main thread be terminated without terminating the child thread. Is it possible. Thanks.

    Read up on daemon threads.
    multithreading - What is Daemon thread in java - Stack Overflow
    Also read the
      Application Lifecycle section in the javadoc.

Maybe you are looking for

  • How to process reports with two different date fields

    Morning all, This question is somewhat similar to what I asked few days back. I created two different reports for two different departments (Credit Control and Free of Charge Control). These two reports pull data from two different date fields and ha

  • Questions on Connection Pooling

    I already read the documentations on data-sources.xml, but I still have questions. In the following data-sources.xml (for OC4J 9.0.3): <data-source class="com.evermind.sql.ConnectionDataSource" name="ccf" location="jdbc/ccf" xa-location="jdbc/xa/ccf"

  • Query regarding Concatenate statement functionality from ECC 6.0 to 46B ver

    Hi, I got new requirement ie I have to copy reports from ECC6.0 to 46B version. While copying I faced number of issues and I am not clear for below one. concatenate i_result1-result p_delim into i_result1-result respecting blanks. ( this is in ECC6.0

  • A question about config adapter for GP

    Hi all, I followed the configuration document and configure all parameters step by step. When I configured adapter for GP and created communication, I had no idea about all parameters about adapter description. For example: protocol, server,  client,

  • Stopping a Thread when downloading

    Hi everyone! I'm develop a app to connect to a FTP Server and dowload and upload files. When I click on Cancel button, the app will still running but the download will stop. So, my problem is: How can I stop a Thread when i'm donwloading a file? I'm