Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tips for using commons-pool in production

Tags:

java

sockets

pool

Based on an answer I got here, I started to give commons-pool a serious look. My last experience of using it was around 2003, probably version 1.1 or 1.2. Its main user, DBCP, is considered by many as flawed and to be avoided.

Does anyone uses commons pool in production to write pool of your own? What is the best pool type to use? I plan to store client TCP sockets in it.

Is there another generic pool that replaces it?

like image 354
David Rabinowitz Avatar asked Jun 02 '09 14:06

David Rabinowitz


1 Answers

Does anyone uses commons pool in production to write pool of your own?

Yes, I do and the pool holds TCP connections, like you intend it to. It's wired up via Spring, so assuming you understand Spring configuration:

<bean class="com.company.ConnectionSupplier">
<constructor-arg>
  <!-- The ConnectionSupplier wraps an object pool -->
  <bean class="org.apache.commons.pool.impl.GenericObjectPool">
    <constructor-arg>
       <!-- The ObjectPool uses a ConnectionFactory to build new connections -->
       <bean class="com.company.ConnectionFactory">
         <constructor-arg value="server" />
         <constructor-arg value="3000" />  
       </bean>  
    </constructor-arg>
    <property name="maxActive" value="20" />
    <property name="testOnBorrow" value="true" />
  </bean>
</constructor-arg>
</bean>  

The ConnectionFactory extends BasePoolableObjectFactory and is a small wrapper around a SocketFactory.

@First comment: The ConnectionFactory constructor takes a server and a port. In the overriden makeObject(), it creates sockets that connect to that server and port. It returns 'Connection' objects that wrap the created socket with some convenience methods for communicating through the socket.

The connection is tested using a sort of 'ping' or 'echo' provided by the protocol used to communicate over the socket. Should that not have been available, validation/testing of the connection is not really possible, except for asking the socket whether it has been closed. In that case, a Connection in the pool would have been invalidated if it threw an exception and every method using Connections should be prepared for that kind of failure and attempt the same operation with another connection.

like image 63
Confusion Avatar answered Sep 28 '22 01:09

Confusion