[jboss-dev-forums] [Design of Messaging on JBoss (Messaging/JBoss)] - An Exception handling case in threads
gaohoward
do-not-reply at jboss.com
Fri Jul 31 11:39:51 EDT 2009
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.
View the original post : http://www.jboss.org/index.html?module=bb&op=viewtopic&p=4247310#4247310
Reply to the post : http://www.jboss.org/index.html?module=bb&op=posting&mode=reply&p=4247310
More information about the jboss-dev-forums
mailing list