GenericObjectPools借款对象方法线程安全吗? [英] Is GenericObjectPools borrowObject Method thread safe?
本文介绍了GenericObjectPools借款对象方法线程安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在此问题中是GenericObjectPool< T>来自commons.apache.org线程安全?有人提到它的线程安全.
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?
这是我的代码:
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()));
}
}
推荐答案
查看全文