Question

I'm using a ThreadPool Executor and i invoke the tasks with invokeAll() method. In the callable call() method i write to a database but i only wanna write if i'm sure that the thread executed fine and didn't terminate badly.

Does any of this solutions works:

Solution 1

I think this don't work because thread can be interrupted after the database write so it doesn't return the result, i guess.

public Result call() throws exception(){

    ...

    if( !Thread.currentThread.isInterrupted() ){
       //Save to the database
    } 

    ...

    return result;
}

Solution 2

Handle the writes after the get() method to be sure that it terminated well, if i understood correctly the get() method re-throws any exception caught during the execution

...

for( Future f : futures){

   try {

       Result r = f.get();

       //Do the write with the result i got
   }
   catch( Exception e){
     //Something went wrong
   }

}

Thanks in advance.

Was it helpful?

Solution

In the callable call() method i write to a database ...

In that case, the exception handling logic needs to be in the call() method itself; e.g.

public Result call() {
    try {
       ...
       if (!Thread.currentThread.isInterrupted()) {
          // Save to the database
          return result;
       } else {
          return // some result that means interrupted.
       }
    catch (Exception ex) {
       return // some result that means failed.
    }
}

There doesn't seem to be any point in trying to get the main thread to do the database save.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top