3 Replies Latest reply on Aug 2, 2009 7:39 AM by timfox

    An Exception handling case in threads

    gaohoward

      While working on https://jira.jboss.org/jira/browse/JBMESSAGING-1680, I need to create a thread and move some existing piece of code inside a method to that thread for concurrent execution. The method can be simplified as this:

      public void methodA() throw Exception
      {
       doWork1();
      
       doWork2();
      }
      


      doWork1() and doWork2() are two tasks independent of each other so they can be optimized using thread. So I plan to move doWork1() to another thread, like:

      public void methodA() throw Exception
      {
       new Thread() { public void run() { doWork1(); } }.start();
      
       doWork2();
      }
      


      The problems is that both doWork1() and doWork2() may throw Exception. So after my change, the doWork1() will be executed in a separate thread and it's exception will never be thrown from the calling thread of methodA(). To solve this, I uses a variable to hold the exception, like this:

      public void methodA() throw Exception
      {
       final ExceptionHolder holder = new ExceptionHolder(); //a holder simply holds an exception reference.
      
       new Thread() { public void run() {
       try
       {
       doWork1();
       }
       catch (Exception e)
       {
       holder = e; //pass the exception to holder.
       }
       } }.start();
      
       doWork2();
      
       //here using join() to wait for the thread finish and then
       if (holder.e != null)
       {
       throw holder.e;
       }
      }
      


      I don't know if this is the proper way. But that's my current solution.