Java Exceptions in Threads
I wrote some code in java to push exceptions from a thread to the main thread, by queueing them in a wrapper (seperate class). Now, if there is any exception present in the wrapper, the thread dies. Then the exceptions have to be thrown on the main thread. There doesn't seem to be a standard java event that is called on the ma开发者_如何学JAVAin thread, so I had to use the join function on the thread somewhere. I can't use join in the main thread, because then the main thread blocks. I can't use it in another thread, then I couldn't throw exceptions any more. I can't think of any other way to throw exceptions on the main thread. Anyone here has an idea?
Use an ExecutorService to do your threading and Future.get() to get the result of executed tasks and/or any exception that happened.
Use an ExecutorService to do your threading and Future.get() to get the result of executed tasks and/or any exception that happened.
As mentioned by @Ryan Stewart you can use Executros framework. In this case you do not create thread yourself: the big brother helps you to do that. You can use Callable instead of Runnable to implement your logic. In this case you can get Future and ask it what's the thread status.
Unfortunately I am afraid this helps you only partially because you have to call Future actively.
If I understood you correctly you want your main thread to be notified when exception is thrown by one of wrorker threads. I do not think you should get exception from worker thread and re-throw it in main thread.
I'd recommend you to use one of the following strategies.
A. Use listener pattern. Create
interface ExceptionListener {
public void exceptionThrown(Exception e);
}
Create abstract class ExceptionNotifierThread extends Thread
.
This class will have collection of ExceptionListener and method addExceptionListener(ExceptionListener l)
.
Method run()
of the thread will catch all Exceptions and then call all exceptiton listeners in loop.
Now you crete your thread and before calling its start()
method you can register as an excption listener.
That's it. When thread throws exception your listener will be called back.
B. It is a version of the same solution. Just instead of notification of listeners synchronously the thread my push excption to queue and everyone may read it from queue. User executors and Blocking queues for this.
Good luck and welcome to stackoverflow!
精彩评论