java中的同步辅助
我正在运行一个网络服务器。每个用户请求都会更新/查找数据库。同时数据库连接的最大数量应小于等于N.第N+1个并发请求应该退出并执行其他逻辑,而不是连接到数据库。我能想到的做法是使用原子整数,在连接到数据库时,该整数将根据每个请求递增/递减。
我的问题是,除了原子整数之外,java 中是否还有其他可用的同步辅助工具?我认为我不能为此使用 CountDownLatch 或循环屏障。
I am running a web server. Each user request will update/lookup the database. the max no of simultaneous db connections should be < N. The N+1 th concurrent request should back out and perform other logic instead of connecting to db. What i can think of to do this is to use Atomic integer which will be incremented/decremented by each request while connecting to db.
My Question is, is there any other synchronization aid available in java for this other than Atomic Integer? I dont think i can use CountDownLatch or Cyclic barrier for this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
信号量
是最适合这种情况的同步原语:Semaphore
is the most suitable synchronization primitive for this case:您可以尝试 ArrayBlockingQueue连接数。用 N 初始化队列。
但我强烈建议使用现有的解决方案,例如 proxool 。
You can try an ArrayBlockingQueue of connections. Initialize the queue with N.
But I will urge to use existing solutions like proxool for this.
或者,您可以使用连接池,例如 Apache Commons DBCP,它将为您处理连接,并且可以等待对于没有连接或将抛出您可以处理的异常的连接。
Alternately you could use a connection pool such as Apache Commons DBCP that will handle the connections for you and can either wait for a connection when there isn't one or will throw and exception which you can handle.
添加到suraj的答案中,我认为您的问题更多是生产者消费者,我更喜欢LinkedBlockingQueue以获得更高的吞吐量。
Adding to the suraj's answer , I think your problem is more of
producer consumer
, i preferLinkedBlockingQueue
for more throughput.