3

在这个问题中来自 commons.apache.org 的 GenericObjectPool<T> 线程安全吗?提到它的线程安全。

编辑:但是我在我的多线程应用程序中遇到了两个线程同时从池中获取相同对象的情况。-这个语句是错误的。

我移动了 borrowObject 来同步块,它解决了我的问题。

有没有人之前遇到过这个问题?

这是我的代码:

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()));


}

}

4

1 回答 1

2

PoolableObjectFactory的文档指出:

PoolableObjectFactory 必须是线程安全的。

查看您的代码,唯一可能是线程不安全的是对obj.release();. 这可能是您的问题所在。

除此之外一切看起来都还可以...

于 2013-08-08T18:57:07.910 回答