Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC async controller implementation with parameters

As per this blog, one can avoid blocking of HTTP Request thread from waiting for longer IO by making it asynchronous. Here, separate thread takes the responsibility of returning the result when it is available. The basic implementation is as follows

@RestController
public class RequestController {

  private final TaskService taskService;

  private final Logger logger = LoggerFactory.getLogger(this.getClass());


  @Autowired
  public RequestController(TaskService taskService) {
    this.taskService = taskService;
  }

  @RequestMapping(value = "/callable", method = RequestMethod.GET, produces = "text/html")
  public Callable<String> executeSlowTaskWithCallable() {
    logger.info("Request received");
    Callable<String> callable = taskService::execute;
    logger.info("Servlet thread released");

    return callable;
  }
  :
}

Instead of "execute" (that takes no arguments and returns a result), I want to create Callable using method that takes arguments and returns some result. Like

Callable<String> callable = taskService.execute(request, headers);

How to achieve this ?

like image 718
DanglingPointer Avatar asked Jun 15 '26 11:06

DanglingPointer


1 Answers

Just use a lambda:

Callable<String> callable = () -> taskService.execute(request, headers);

Like so:

@RestController
public class RequestController {

  private final Logger logger = LoggerFactory.getLogger(this.getClass());
  private final TaskService taskService;

  @Autowired
  public RequestController(TaskService taskService) {
    this.taskService = taskService;
  }

  @RequestMapping(value = "/callable", method = RequestMethod.GET, produces = "text/html")
  public Callable<String> executeSlowTaskWithCallable() {
    logger.info("Request received");
    Object request, headers = // initialize variables
    Callable<String> callable = () -> taskService.execute(request, headers);
    logger.info("Servlet thread released");

    return callable;
  }

}
like image 138
Miloš Milivojević Avatar answered Jun 17 '26 23:06

Miloš Milivojević



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!