3

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 ?

1 Answer 1

1

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;
  }

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.