Tuesday, December 15, 2009

java.util.concurrent.Semaphore

java.util.concurrent.Semaphore

If we wants to make programmatically Connection management, connection may be Database or TCP Socket or JMS or other. Instead of establishing connection every time for every SQL command, we can cache the connection for future use. Once the usage of connection usage is completed then we can take connection back to pool. For instance, We have established 20 connections, but 50 SQL commands has to be run in the given point of time. These 20 connections has to be alotted to first 20 SQL commands to run and whenever SQL command is completed then connection will be used for rest of SQL commands.



We have to maintain a mark for each connection that whether that connection is get used or not. Two methods has to be used to acquire and release the resource. Everything perfect, who will take care of filtering and ordering the thread entry, how thread state managed. For these questions Semaphore is the right answer, here is the code snippet




class ConnectionPool {
private static final int MAX_AVAILABLE = 100;
private final Semaphore available = new Semaphore(MAX_AVAILABLE, true);

public Object getConnection() throws InterruptedException {
available.acquire();
return getNextAvailableItem();
}

public void releaseConnection(Object x) {
if (markAsUnused(x))
available.release();
}

protected Object[] connections = ... whatever kinds of connections being managed
protected boolean[] used = new boolean[MAX_AVAILABLE];

protected synchronized Object getNextAvailableItem() {
for (int i = 0; i < MAX_AVAILABLE; ++i) {
if (!used[i]) {
used[i] = true;
return connections[i];
}
}
return null; // not reached
}

protected synchronized boolean markAsUnused(Object item) {
for (int i = 0; i < MAX_AVAILABLE; ++i) {
if (item == connections[i]) {
if (used[i]) {
used[i] = false;
return true;
} else
return false;
}
}
return false;
}

}

Reactions:

0 comments:

Post a Comment

Recent Posts

Unix Commands | List all My Posts

Texts

This blog intended to share the knowledge and contribute to JAVA Community such a way that by providing samples and pointing right documents/webpages. We try to give our knowledege level best and no guarantee can be claimed on truth. Copyright and Terms of Policy refer blogspot.com

Share

Twitter Delicious Facebook Digg Stumbleupon Favorites More