Example usage for org.apache.commons.pool2 KeyedObjectPool returnObject

List of usage examples for org.apache.commons.pool2 KeyedObjectPool returnObject

Introduction

In this page you can find the example usage for org.apache.commons.pool2 KeyedObjectPool returnObject.

Prototype

void returnObject(K key, V obj) throws Exception;

Source Link

Document

Return an instance to the pool.

Usage

From source file:org.openhab.binding.modbus.internal.SimultaneousReadWriteTestCase.java

@Test
public void testPoolBlocks() throws Exception {
    final KeyedObjectPool<ModbusSlaveEndpoint, ModbusSlaveConnection> pool = ModbusBinding
            .getReconstructedConnectionPoolForTesting();

    final ModbusTCPSlaveEndpoint endpoint = new ModbusTCPSlaveEndpoint(localAddress().getHostAddress(),
            this.tcpModbusPort);

    ModbusSlaveConnection borrowObject = pool.borrowObject(endpoint);
    Thread thread = new Thread() {
        @Override/*from ww w  .  j a  v a 2  s  .co  m*/
        public void run() {
            try {
                ModbusSlaveConnection borrowObject2 = pool.borrowObject(endpoint);
                pool.returnObject(endpoint, borrowObject2);
            } catch (Exception e) {
                e.printStackTrace(System.err);
            }
        }
    };
    thread.start();
    thread.join(500);
    if (!thread.isAlive()) {
        throw new AssertionError("Thread should still be alive -- blocking since no objects");
    } else {
        thread.interrupt();
    }

    pool.returnObject(endpoint, borrowObject);
    // Now that object has been returned, borrowing should work again
    ModbusSlaveConnection borrowObject2 = pool.borrowObject(endpoint);
    pool.returnObject(endpoint, borrowObject2);

}

From source file:org.openhab.io.transport.modbus.internal.ModbusManagerImpl.java

private void returnConnection(ModbusSlaveEndpoint endpoint, Optional<ModbusSlaveConnection> connection) {
    KeyedObjectPool<ModbusSlaveEndpoint, ModbusSlaveConnection> pool = connectionPool;
    if (pool == null) {
        return;/*from   w w w .j  a v  a 2s. c  o  m*/
    }
    long start = System.currentTimeMillis();
    connection.ifPresent(con -> {
        try {
            pool.returnObject(endpoint, con);
            logger.trace("returned connection to pool for endpoint {}", endpoint);
        } catch (Exception e) {
            logger.warn("Error returning connection to pool for endpoint {}. Error was: {} {}", endpoint,
                    e.getClass().getName(), e.getMessage(), e);
        }
    });
    logger.trace("returning connection for endpoint {} took {} ms", endpoint,
            System.currentTimeMillis() - start);
}