pool.returnObject("x",obj);
}
}
public void testBorrowReturnWithSometimesInvalidObjects() throws Exception {
KeyedObjectPool pool = new StackKeyedObjectPool(
new KeyedPoolableObjectFactory() {
int counter = 0;
public Object makeObject(Object key) { return new Integer(counter++); }
public void destroyObject(Object key, Object obj) { }
public boolean validateObject(Object key, Object obj) {
if(obj instanceof Integer) {
return ((((Integer)obj).intValue() % 2) == 1);
} else {
return false;
}
}
public void activateObject(Object key, Object obj) { }
public void passivateObject(Object key, Object obj) {
if(obj instanceof Integer) {
if((((Integer)obj).intValue() % 3) == 0) {
throw new RuntimeException("Couldn't passivate");
}
} else {
throw new RuntimeException("Couldn't passivate");
}
}
}
);
Object[] obj = new Object[10];
for(int i=0;i<10;i++) {
Object object = null;
int k = 0;
while (object == null && k < 100) { // bound not really needed
try {
k++;
object = pool.borrowObject("key");
obj[i] = object;
} catch (NoSuchElementException ex) {
// Expected for evens, which fail validation
}
}
assertEquals("Each time we borrow, get one more active.", i+1, pool.getNumActive());
}
// 1,3,5,...,19 pass validation, get checked out
for(int i=0;i<10;i++) {
pool.returnObject("key",obj[i]);
assertEquals("Each time we borrow, get one less active.", 9-i, pool.getNumActive());
}
// 3, 9, 15 fail passivation.
assertEquals(7,pool.getNumIdle());
assertEquals(new Integer(19), pool.borrowObject("key"));
assertEquals(new Integer(17), pool.borrowObject("key"));
assertEquals(new Integer(13), pool.borrowObject("key"));
assertEquals(new Integer(11), pool.borrowObject("key"));
assertEquals(new Integer(7), pool.borrowObject("key"));
assertEquals(new Integer(5), pool.borrowObject("key"));
assertEquals(new Integer(1), pool.borrowObject("key"));
}