Synchronization aid in java
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 connect开发者_StackOverflow社区ing 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.
Semaphore
is the most suitable synchronization primitive for this case:
private Semaphore s = new Semaphore(N);
public void doRequest() {
if (s.tryAquire()) {
try {
...
} finally {
s.release();
}
} else {
// other logic
}
}
You can try an ArrayBlockingQueue of connections. Initialize the queue with N.
- Initialize the queue with N
- Fill the N connections.
- Whenever someone needs a connection, first do q.poll()
- If q.poll() returns null, then doe your "perform other logic"
- After usage put back the connection to pool.
But I will urge to use existing solutions like proxool for this.
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.
Adding to the suraj's answer , I think your problem is more of producer consumer
, i prefer LinkedBlockingQueue
for more throughput.
精彩评论