计算我们请求的活跃数量而不阻塞
在 Java Web 服务器上,我想知道是否有任何活动的 Web 请求。
我的第一个想法是这样的:
public static AtomicInteger count = new AtomicInteger();
public void processRequest() {
count.incrementAndGet();
// process my request
count.decrementAndGet();
}
public boolean areThereActiveRequests() {
return 0 == count.get();
}
这显然会使网络请求在递增或递减时相互阻塞(尽管很快),等待 count() 上的锁定 - 对于高度可扩展的服务器,我们不希望出现这种情况。
请注意,任何代码调用 areThereActiveRequests 都可能存在同步问题 - 它返回的值在返回时可能已经过时 - 但这对于我的目的来说是可以的。
有什么想法吗?
On a java webserver, I would like to know if there are any active web requests.
My first idea was something like:
public static AtomicInteger count = new AtomicInteger();
public void processRequest() {
count.incrementAndGet();
// process my request
count.decrementAndGet();
}
public boolean areThereActiveRequests() {
return 0 == count.get();
}
This obviously makes web requests block (albeit quickly) against each other waiting for a lock on count() when incrementing or decrementing - which we don't want for a highly scalable server.
Note that there may be synchronization issues with whatever code calls areThereActiveRequests - the value it returns may be stale by the time it's returned - but that's ok for my purposes.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的 Web 请求不会在等待锁定时相互阻塞,因为 AutomicInteger 不需要任何锁定并利用硬件同步原语。
查看详细信息
因此,您当前的代码看起来很适合您的问题正在努力解决。
Your web requests will not block against each other waiting for a lock, as AutomicInteger doesn't require any locks and utilizes Hardware synchronization primitive.
Check this for details
Therefore your current code looks good for the problem you are trying to solve.