Java 中静态方法的并发调用限制为最大 N
考虑以下静态方法:
public void static foo() {
// some heavy operation operating on a shared resource.
}
假设当并发调用 foo()
的数量超过十 (10) 时系统变得不稳定。
如果我在这种情况下启动 100 个线程,所有线程都用请求来敲击 foo(),那么应用程序将变得不稳定,因为我们超出了系统可以处理的并发请求数。
提高有限并发代价的稳定性的一种方法是将代码更改为:
public void static synchronized foo() {
// some heavy operation operating on a shared resource.
}
系统现在将能够处理 100 个线程,所有线程都用请求敲击 foo()
,因为一次只有一个调用将允许foo()
。
如果我想限制对 foo()
的访问,以便只允许 N
个并发请求,那么情况怎么样?在 Java 中实现这种限制的最简单方法是什么?
Consider the following static method:
public void static foo() {
// some heavy operation operating on a shared resource.
}
Assume that the system becomes unstable when the number of concurrent calls to foo()
exceeds ten (10).
If I in this scenario spin up 100 threads all hammering foo()
with requests then the application will become unstable since we exceed the number of concurrent requests which the system can handle.
One way to increase stability to the price of limited concurrency is the change the code to:
public void static synchronized foo() {
// some heavy operation operating on a shared resource.
}
The system will now be able to handle 100 threads all hammering foo()
with requests since only one call at a time will be allowed to foo()
.
What about the scenario that I want to limit access to foo()
so that only N
concurrent requests are allowed? What is the simplest way to achieve such a limitation in Java?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
信号量
初始化有 10 个许可证。在方法开始时获取许可,并在方法结束时释放它(在finally 块中)。Use a
Semaphore
initialized with 10 permits. Acquire a permit at the beginning of the method, and release it (in a finally block) at the end of the method.CountDownLatch
可以解决您的问题。
它有阻塞和非阻塞之分。
编辑:修复网址
CountDownLatch
May solve your problem.
It comes in blocking and non blocking.
Edit: Fix URL