Home > Enterprise >  Getting data back from @Async function call
Getting data back from @Async function call

Time:04-17

Hi I am new to multithreading in java. Can someone please help me with this:

My service:

@Async
public List<String> doSomething(int a){
    //Do something
    return list;
}

SpringbootApplication:

@SpringBootApplication
@EnableAsync
public class Test {

    public static void main(String[] args) {
        SpringApplication.run(Test.class, args);
    }

}

Async config:

@Configuration
@EnableAsync
public class AsyncConfig {

    @Bean(name ="taskExecutor")
    public Executor taskExecutor(){
        ThreadPoolTaskExecutor executor=new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(2);
        executor.setMaxPoolSize(2);
        executor.setQueueCapacity(100);
        executor.setThreadNamePrefix("userThread-");
        executor.initialize();
        return executor;
    }
}

Controller:

@RestController
public class Controller{
    
    @Autowired
    private Service service;

    @GetMapping("test")
    public List<String> getAll(){
        return service.doSomething(1);
    }
}

When I hit this get request from postman it is showing up blank in the response. I understand that my call is going asynchronously and the response is coming back even before the my method is called. Is there any way to see this response by changing some settings in either my postman or spring boot application

CodePudding user response:

You can return CompletableFuture. You will receive http response when CompleteableFuture will be completed.

Service:

@Async
public CompletableFuture<List<String>> doSomething() {
    return CompletableFuture.completedFuture(Arrays.asList("1", "2", "3"));
} 

Controller:

@GetMapping("test")
public CompletableFuture<List<String>> getAll(){
    return service.getAll();
}

CodePudding user response:

If you want to use async I would split your single request into so called "start task" and "get task result" requests. Your application returns "request id" for "start task" request. Then you use "request id" when performing "get task result". Such a scenario is a common way in the Batch Processing task. If you use Spring, you may be interesting investigating Spring Batch framework, which has Start/Stop/Restart job functionality among others.

  • Related