开发者

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.

  1. Initialize the queue with N
  2. Fill the N connections.
  3. Whenever someone needs a connection, first do q.poll()
  4. If q.poll() returns null, then doe your "perform other logic"
  5. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜