[英]Async API giving worse performance
Interesting, I would think have 255 concurrent users, an async API would have better performance. 有趣的是,我认为有255个并发用户,异步API会有更好的性能。 Here are 2 of my endpoints in my Spring server: 这是我的Spring服务器中的两个端点:
@RequestMapping("/async")
public CompletableFuture<String> g(){
CompletableFuture<String> f = new CompletableFuture<>();
f.runAsync(() -> {
try {
Thread.sleep(500);
f.complete("Finished");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
return f;
}
@RequestMapping("/sync")
public String h() throws InterruptedException {
Thread.sleep(500);
return "Finished";
}
In the /async
it runs it on a different thread. 在/async
,它在另一个线程上运行。 I am using Siege
for load testing as follows: 我正在使用Siege
进行负载测试,如下所示:
siege http://localhost:8080/sync --concurrent=255 --time=10S > /dev/null
For the async
endpoint, I got a transaction number of 27 hits
对于async
端点,我的交易次数为27 hits
For the sync
endpoint, I got a transaction number of 1531 hits
对于sync
端点,我获得了1531 hits
的交易数
So why is this? 那为什么呢? Why isnt the async endpoint able to handle more transactions? 为什么异步端点不能处理更多事务?
Because the async endpoint is using a shared (the small ForkJoinPool.commonPool()
) threadpool to execute the sleeps, whereas the sync endpoint uses the larger threadpool of the application server. 因为异步端点正在使用共享的(较小的ForkJoinPool.commonPool()
)线程池执行睡眠,而同步端点则使用应用程序服务器的较大线程池。 Since the common pool is so small, you're running maybe 4-8 operations (well, if you call sleeping an operation) at a time, while others are waiting for their turn to even get in the pool. 由于公共池是如此之小,因此您可能一次运行4至8个操作(好吧,如果您叫sleeping一个操作),而其他人则等待轮到他们进入池中。 You can use a bigger pool with CompletableFuture.runAsync(Runnable, Executor)
(you're also calling the method wrong, it's a static method that returns a CompletableFuture
). 您可以将更大的池与CompletableFuture.runAsync(Runnable, Executor)
(您还将方法称为错误,这是一个返回CompletableFuture
的静态方法)。
Async isn't a magical "make things faster" technique. 异步并不是一种神奇的“使事情更快”的技术。 Your example is flawed as all the requests take 500ms and you're only adding overhead in the async one. 您的示例存在缺陷,因为所有请求都需要500毫秒,而您只是在异步请求中增加了开销。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.