Java – can nested threads throw exceptions for parent threads?

I have a controller class and a monitor worker thread

public class ControllerA {
    public void ControllerA(){
        try{
            doWork();
        }
        catch(OhNoException e){
        //catch exception
        }

    public void doWork() throws OhNoException{

      new Thread(new Runnable(){
        public void run(){
        //Needs to monitor resources of ControllerA,//if things go wrong,it needs to throw OhNoException for its parent
        }
        }).start();

      //do work here

    }
}

Is this setting feasible? How to throw an exception outside the thread?

Solution

The couple can do this You can set uncaughtexceptionhandler on the thread or use executorservice Submit (callable) and use from future Exception obtained by get()

The easiest way is to use executorservice:

ExecutorService threadPool = Executors.newSingleThreadScheduledExecutor();
Future<Void> future = threadPool.submit(new Callable<Void>() {
      public Void call() throws Exception {
         // can throw OhNoException here
         return null;
     }
});
// you need to shut down the pool after submitting the last task
threadPool.shutdown();
// this can throw ExecutionException
try {
   // this waits for your background task to finish,it throws if the task threw
   future.get();
} catch (ExecutionException e) {
    // this is the exception thrown by the call() which Could be a OhNoException
    Throwable cause = e.getCause();
     if (cause instanceof OhNoException) {
        throw (OhNoException)cause;
     } else if (cause instanceof RuntimeException) {
        throw (RuntimeException)cause;
     }
}

If you want to use uncaughtexceptionhandler, you can do the following:

Thread thread = new Thread(...);
 final AtomicReference throwableReference = new AtomicReference<Throwable>();
 thread.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
     public void uncaughtException(Thread t,Throwable e) {
         throwableReference.set(e);
     }
 });
 thread.start();
 thread.join();
 Throwable throwable = throwableReference.get();
 if (throwable != null) {
     if (throwable instanceof OhNoException) {
        throw (OhNoException)throwable;
     } else if (throwable instanceof RuntimeException) {
        throw (RuntimeException)throwable;
     }
 }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>