Home > Software design >  How to return try block value in java even before finally block start executing?
How to return try block value in java even before finally block start executing?

Time:10-07

I have code snippet in java like

Int methodHitByAPI() {
     List returnValue = doSomething();
     return returnValue;
     finishProcess(returnValue);
}

My doubt is that i wanted to execute doSomething() (this method was hit by a post api call from UI) and then return the response immediately and then execute finishProcess() . The finishProcess() is a very large process and frontend can't wait till it completes(HTTP time out). But one point to note here is that it's enough for frontend to execute doSomething() and it has no work to do with finishProcess(returnValue); So how can i send the response to UI quick without having any issues with finishProcess(returnValue); executing finishProcess(returnValue) is a must on backend but had no work with frontend

I had tried this

try {
    returnValue = doSomething();
    return returnValue;
}
finally {
     finishProcess(returnValue);
}

but still

return returnValue;

is executed only after finishProcess(returnValue);

What is the solution for this?

Note : We might send the return value to frontend and call another APi call to finishProcess(). But it's not the case

CodePudding user response:

Maybe an asynchronous approach would be fitting here, like...

ExecutorService executor = Executors.newFixedThreadPool(10);
public List methodHitByAPI() {
    List returnValue = doSomething();
    executor.submit(()->finishProcess(returnValue));
    return returnValue;
}

The returnValue would be returned immediately but the finishProcess will be executed in an separated thread.

  • Related