Search code examples
scalaplayframeworkfutureblocking

Play framework scala POST and Future


I have this action in my controller

def doRegister = Action { implicit request =>
    Future {
      Thread.sleep(5000)
    }
    Ok("")
  }

This is the route

POST /api/checkout/register controllers.shop.checkout.CheckoutAuthController.doRegister

I want to return the Ok result, without waiting for the Future.

It works with a GET requests (returns instantly), but not with POST. The timeout applies and the javascript vuejs project that make the call, has to wait.


Solution

  • As per Mateusz's advice, offload blocking calls to a separate thread pool, for example

    val ecForBlockingTasks = ExecutionContext.fromExecutor(Executors.newFixedThreadPool(5))
    
    def doRegister = Action { implicit request =>
      Future {
        Thread.sleep(5000)
      }(ecForBlockingTasks)
    
      Ok("")
    }
    

    Make sure you create the thread pool only once at app launch, otherwise you might end up with a resource leak.