What effect does using Action.async have, since Play uses Netty which is non-blocking

后端 未结 2 1592
梦毁少年i
梦毁少年i 2021-02-04 04:57

Since Netty is a non-blocking server, what effect does changing an action to using .async?

def index = Action { ... }

versus

2条回答
  •  攒了一身酷
    2021-02-04 05:25

    I happened to come across this question, I like the answer from @vptheron, and I also want to share something I read from book "Reactive Web Applications", which, I think, is also great.

    The Action.async builder expects to be given a function of type Request => Future[Result]. Actions declared in this fashion are not much different from plain Action { request => ... } calls, the only difference is that Play knows that Action.async actions are already asynchronous, so it doesn’t wrap their contents in a future block.

    That’s right — Play will by default schedule any Action body to be executed asynchronously against its default web worker pool by wrapping the execution in a future. The only difference between Action and Action.async is that in the second case, we’re taking care of providing an asynchronous computation.

    It also presented one sample:

    def listFiles = Action { implicit request =>
      val files = new java.io.File(".").listFiles
      Ok(files.map(_.getName).mkString(", "))
    }
    

    which is problematic, given its use of the blocking java.io.File API.

    Here the java.io.File API is performing a blocking I/O operation, which means that one of the few threads of Play's web worker pool will be hijacked while the OS figures out the list of files in the execution directory. This is the kind of situation you should avoid at all costs, because it means that the worker pool may run out of threads.

    -

    The reactive audit tool, available at https://github.com/octo-online/reactive-audit, aims to point out blocking calls in a project.

    Hope it helps, too.

提交回复
热议问题