In this question Is GenericObjectPool<T> from commons.apache.org thread safe? It is mentioned that its thread safe .
Edited:But im having a situation in my multithreaded application that two threads are getting the same object from the pool at the same time.-This statement was wrong.
I moved the borrowObject to synchronize block and it solved my issue.
Has anyone faced this issue earlier?
Here is my code:
public static GenericObjectPool<IDocBuilderPool> documentBuilderPool = new GenericObjectPool(new DocumentPool());
static {
documentBuilderPool.setMaxActive(1000);
documentBuilderPool.setMaxWait(30000);
documentBuilderPool.setMaxIdle(-1);
}
//method that returns document pool called by multiple threads .
public static IDocBuilderPool getDocumentPool() {
return documentBuilderPool.borrowObject();
}
//The pool factory class
public class DocumentPool extends BasePoolableObjectFactory<ICollabrrDocument> {
public DomDocumentPool() {
}
@Override
public DomDocument makeObject() throws Exception {
// TODO Auto-generated method stub
return new DomDocument();
}
@Override
public void activateObject(IDocBuilderPool obj) throws Exception {
// TODO Auto-generated method stub
super.activateObject(obj);
}
@Override
public void destroyObject(IDocBuilderPool obj) throws Exception {
// TODO Auto-generated method stub
super.destroyObject(obj);
}
@Override
public void passivateObject(IDocBuilderPool obj) throws Exception {
// TODO Auto-generated method stub
obj.release();
super.passivateObject(obj);
}
@Override
public boolean validateObject(IDocBuilderPool obj) {
// TODO Auto-generated method stub
return super.validateObject(obj);
}
}
public class DomDocument implements IDocBuilderPool {
private Document domDocument;
private DocumentBuilder documentBuilder;
private DocumentBuilderFactory documentBuilderFactory;
public HashMap<org.w3c.dom.Node, DOMElement> elementMap = new HashMap<org.w3c.dom.Node, DOMElement>();
public long threadID;
public DomDocument() {
setDomDocument();
this.threadID = Thread.currentThread().getId();
}
public void setDomDocument() throws
this.documentBuilderFactory = DocumentBuilderFactory.newInstance();
this.documentBuilderFactory.setNamespaceAware(true);
this.documentBuilder = this.documentBuilderFactory.newDocumentBuilder();
this.domDocument = this.documentBuilder.parse(new ByteArrayInputStream("<Root/>".getBytes()));
}
}
The documentation of PoolableObjectFactory states:
Looking at your code, the only thing that could be thread unsafe is the call to
obj.release();
. This is possibly where your problem is.Apart from that all looks ok...