genericobjectpools方法是线程安全的吗?

nhhxz33t  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(292)

我读了GenericObjectObject方法是线程安全的吗?。我和他有同样的问题,我的问题代码是:

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

}

正如他所说的构造函数是非线程安全的,据我所知,方法是在线程安全的堆栈中调用的,但是为什么他说domo中的构造函数是不安全的呢?
我面临的问题是,当借用对象得到相同的 Connection 这是我的密码:

@Component
public class HsmConnectionManager {

    private static final Logger logger = LoggerFactory.getLogger(HsmConnectionManager.class);

    @Resource
    private GenericKeyedObjectPool<ThriftConfigDto, TProtocol> keyedObjectPool;
      public ConnectionDto getConnection(ThriftConfigDto dto) throws BusinessException {
            if (dto == null) {
                throw new BusinessException(EnumErrorCode.SYS_HSM_CONNECTION_ERR);
            }
            Assert.notNull(dto.getIp(), "Thrift ip can not be null.");
            Assert.notNull(dto.getPort(), "Thrift port can not be null.");

            try {
                TProtocol protocol = keyedObjectPool.borrowObject(dto);
                CVService.Iface client = new CVService.Client(protocol);
                return new ConnectionDto(dto, protocol, client);
            } catch (Exception e) {
                logger.error(e.getMessage());
                logger.error("com.safevast.hsm.factory -> getConnection::ThriftConfigDto = [{}]", dto);
                throw new BusinessException(EnumErrorCode.SYS_HSM_CONNECTION_ERR, e);
            }
        }
}
@Component
public class HsmProtocolFactory implements KeyedPooledObjectFactory<ThriftConfigDto, TProtocol> {
    @Override
    public PooledObject<TProtocol> makeObject(ThriftConfigDto key) throws Exception {

        TSocket socket = new TSocket(key.getIp(), key.getPort(), key.getMaxWait().intValue());
        socket.open();
        TProtocol protocol = new TBinaryProtocol(socket);

        logger.debug("com.safevast.hsm.factory -> makeObject::IP = [{}], PORT = [{}]", key.getIp(), key.getPort());
        return new DefaultPooledObject<>(protocol);
    }
...
}
az31mfrm

az31mfrm1#

我自己找到了答案,keyedpooleobjectfactory是绝对线程安全的

相关问题