Play Framework: Async vs Sync performance

一曲冷凌霜 提交于 2020-01-13 19:20:28

问题


I have following code:

  def sync = Action {
      val t0 = System.nanoTime()
      Thread.sleep(100)
      val t1 = System.nanoTime()
      Ok("Elapsed time: " + (t1 - t0) / 1000000.0 + "ms") 
  }

  def async = Action {
    val t0 = System.nanoTime()
    Async { 
          Future{
            Thread.sleep(100)
            val t1 = System.nanoTime()
            Ok("Elapsed time: " + (t1 - t0) / 1000000.0 + "ms") 
            }   
    }
  }

Difference among above code is that sync will sleep on the thread that received request and async will sleep on the separate thread so that thread in charge of receiving a request can keep on receiving requests without blocking. When I profile thread, I see a sudden increase in number of threads created for async requests as expected. However both methods above with 4000 concurrent connection 20 sec ramp result in the same throughput and latency. I expected async to perform better. Why would this be?


回答1:


The short answer is that both methods are essentially the same.

Actions themselves are always asynchronous (see documentation on handling asynchronous results).

In both cases, the sleep call occurs in the action's thread pool (which is not optimal).

As stated in Understanding Play thread pools:

Play framework is, from the bottom up, an asynchronous web framework. Streams are handled asynchronously using iteratees. Thread pools in Play are tuned to use fewer threads than in traditional web frameworks, since IO in play-core never blocks.

Because of this, if you plan to write blocking IO code, or code that could potentially do a lot of CPU intensive work, you need to know exactly which thread pool is bearing that workload, and you need to tune it accordingly.

For instance, this code fragment uses a separate thread pool:

Future {
  // Some blocking or expensive code here
}(Contexts.myExecutionContext)

As additional resources, see this answer and this video for more information on handling asynchronous actions and this and this forum messages for extensive discussions on the subject.



来源:https://stackoverflow.com/questions/24540544/play-framework-async-vs-sync-performance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!