0

My frontend is timing out (504 error) when calling my backend service. This is because my backend service takes ~6 minutes to finish running. I want to return a response to the front-end within a minute and have my backend code continue running after the response is given to the frontend.

I want to use concurrency to run two code segments. One thread will return a String to the frontend, the other thread will call the code that takes around 5 minutes to run on my server.

I want my solution to be simple as this seems like a simple problem to fix, so I am using the simple Executor class from java.util.concurrent

I made my Invoker class as followed:

public class Invoker implements Executor {
    @Override
    public void execute(Runnable r) {
        r.run();
    }
}

In my actual code, I have

import java.util.concurrent.Executor;
import com.dcc.standalone.Invoker;

public String aCoolFunction() {
    String status = "good job, homie";
    Executor executor = new Invoker();
    executor.execute( () -> {
                // Call this part of the code that takes 5 minutes to run CODE_A
    });
    return status;
}

I expect status to be returned at the same time CODE_A starts running. Instead, the code runs sequentially as before, i.e., status is returned after CODE_A runs.

Jason Bak
  • 81
  • 1
  • 7

2 Answers2

0

maybe use a CompletableFuture?

Setup a ThreadPoolTaskExecutor.

@Configuration
@EnableAsync
public class SpringAsyncConfig {

    @Bean(name = "threadPoolTaskExecutor")
    public Executor threadPoolTaskExecutor() {
        return new ThreadPoolTaskExecutor();
    }
}

Define your function

public String aCoolFunction() {
    String status = "good job, homie";
    someAsyncFunction();
    return status;
}

Define a async long running function.

@Async
public void someAsyncFcuntion() {
    // Call this part of the code that takes 5 minutes to run CODE_A
}

run your cool function somewhere in a CompletableFuture

String result CompletableFuture.supplyAsync(() -> aCoolFunction()).get();

I'm writing from mobile, but this is what i could come up with from the top of my head.

Toerktumlare
  • 12,548
  • 3
  • 35
  • 54
0

Declare @Async or create a threadpool using Executors for the service field you want to use. ex)

@Service
public class SimpleService {

    private ExectorService pool = Executors.newFixedThreadPool(10);

    public String someThing() {
        String status = "good job, homie";
        pool.execute(() -> {
            // other logic
        })
        return status;
    }
}
WonChul Heo
  • 242
  • 1
  • 12