I have the following code in Scala that uses the Apache pool2 library. The object to pool is OlapConnection (an olap4j class, similar to an SQL connection).
Problem is that I can't make the pool close the connections automatically when the number of pooled objects exceeds the maximum.
If I return an object to the pool (with pool.returnObject) that triggers passivateObject. If I close the connection in passivateObject, I would close it every time I return an object, and that's not what I want - I need the open connections to be cached. If I don't close the connection in passivateObject, then it will never be closed.
How to make this work?
Scala code:
class OlapConnectionUtil (val pool: ObjectPool[OlapConnection]) {
def connect = {
pool.borrowObject
}
def close(olapConnection: OlapConnection) = {
pool.returnObject(olapConnection)
}
}
class OlapConnectionFactory extends BasePooledObjectFactory[OlapConnection] {
override def create = {
val connectionString = "jdbc:mondrian:Jdbc=jdbc:mysql://localhost:3306/foodmart?" +
"user=x&password=x;Catalog=FoodMart.xml;JdbcDrivers=com.mysql.jdbc.Driver"
val connection = DriverManager.getConnection(connectionString)
connection.unwrap(classOf[OlapConnection])
}
override def wrap(olapConnection: OlapConnection) =
new DefaultPooledObject(olapConnection)
override def passivateObject(pooledObject: PooledObject[OlapConnection] ) {
println("passivateObject WAS CALLED")
pooledObject.getObject.close
}
}
class Test {
val olapConnectionFactory = new OlapConnectionFactory
def test = {
val config = new GenericObjectPoolConfig
config.setMaxIdle(5)
config.setMaxTotal(10)
val util = new OlapConnectionUtil(
new GenericObjectPool[OlapConnection](olapConnectionFactory,config))
val olapConnection = util.connect
// do stuff with olapConnection
util.close(olapConnection)
If you open the JavaDocs for
PooledObjectFactoryyou may see thatIn other words you should put your resource de-allocation logic into the
destroyObject. Here is a modified test of yours with a fakeOlapConnectionimplementationThe output produced by this code is:
As you can see in this output
closeis being called sinceOlapConnection(6)as one would expect given the pool configuration.