Search code examples
javamultithreadingexceptionconcurrencyrunnable

Throw an exception from a thread WITHOUT using Callable?


So I am in a scenario where I have a method that returns absolutely nothing. (Return type Void). I need to run it another Thread though. I know you can throw an exception using callable, but unfortunately the exception won't be thrown until the Future.get() is called and since it returns nothing, calling the future.get() just seems like a waste. Is there any more elegant solution to my problem? Here is mockup of the issue I am running into:

public static void main(String[] args){
    Callable<Void> upStreamer = new Callable<Void>(){
        public Void call() throws IOException{
            throw new IOException("I want this exception to be thrown!");
        }
    };
    FutureTask<Void> futureTask = new FutureTask<Void>(upStreamer);
    Thread uploadThread = new Thread(futureTask);
    uploadThread.start();   
}

Here is the real issue in pseudocode:

public static void main(String[] args){
new somekindOfThreadLikeThing...
     //inside the method
     if(criticalCondition == false){
        throw new IOException("halt everything and tell the programmer what's wrong.");
     }
     //Import code that is the part that needs to be multithreaded but the final references will screw it up. (There are inmutable Strings involved. Code will throw uncaught exception if criticalCondition == false. This part will also throw an exception.
}.startOrWhatever();
}

Solution

  • I decided to use CompletableFuture. Thanks so so much ssedano!

    http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html