org.apache.commons.pool2.BasePooledObjectFactory Java Examples

The following examples show how to use org.apache.commons.pool2.BasePooledObjectFactory. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CommonsObjectPool2MetricsTest.java    From micrometer with Apache License 2.0 6 votes vote down vote up
private void createGenericObjectPool() {
    genericObjectPoolCount++;
    GenericObjectPoolConfig<Object> config = new GenericObjectPoolConfig<>();
    config.setMaxTotal(10);

    new GenericObjectPool<>(new BasePooledObjectFactory<Object>() {
        @Override
        public Object create() {
            return new Object();
        }

        @Override
        public PooledObject<Object> wrap(Object testObject) {
            return new DefaultPooledObject<>(testObject);
        }
    }, config);
}
 
Example #2
Source File: TestGenericObjectPool.java    From commons-pool with Apache License 2.0 5 votes vote down vote up
private BasePooledObjectFactory<String> createDefaultPooledObjectFactory() {
    return new BasePooledObjectFactory<String>() {
        @Override
        public String create() {
            // fake
            return null;
        }

        @Override
        public PooledObject<String> wrap(final String obj) {
            // fake
            return new DefaultPooledObject<>(obj);
        }
    };
}
 
Example #3
Source File: TestGenericObjectPool.java    From commons-pool with Apache License 2.0 5 votes vote down vote up
private BasePooledObjectFactory<String> createNullPooledObjectFactory() {
    return new BasePooledObjectFactory<String>() {
        @Override
        public String create() {
            // fake
            return null;
        }

        @Override
        public PooledObject<String> wrap(final String obj) {
            // fake
            return null;
        }
    };
}
 
Example #4
Source File: TestGenericObjectPool.java    From commons-pool with Apache License 2.0 5 votes vote down vote up
private BasePooledObjectFactory<String> createSlowObjectFactory(final long elapsedTimeMillis) {
    return new BasePooledObjectFactory<String>() {
        @Override
        public String create() throws Exception {
            Thread.sleep(elapsedTimeMillis);
            return "created";
        }

        @Override
        public PooledObject<String> wrap(final String obj) {
            // fake
            return new DefaultPooledObject<>(obj);
        }
    };
}
 
Example #5
Source File: ThriftClientPool.java    From thrift-client-pool-java with Artistic License 2.0 4 votes vote down vote up
public ThriftClientPool(List<ServiceInfo> services, Function<TTransport, T> factory,
        PoolConfig config, ThriftProtocolFactory pFactory) {
    if (services == null || services.size() == 0) {
        throw new IllegalArgumentException("services is empty!");
    }
    if (factory == null) {
        throw new IllegalArgumentException("factory is empty!");
    }
    if (config == null) {
        throw new IllegalArgumentException("config is empty!");
    }

    this.services = services;
    this.clientFactory = factory;
    this.poolConfig = config;
    // test if config change
    this.poolConfig.setTestOnReturn(true);
    this.poolConfig.setTestOnBorrow(true);
    this.pool = new GenericObjectPool<>(new BasePooledObjectFactory<ThriftClient<T>>() {

        @Override
        public ThriftClient<T> create() throws Exception {

            // get from global list first
            List<ServiceInfo> serviceList = ThriftClientPool.this.services;
            ServiceInfo serviceInfo = getRandomService(serviceList);
            TTransport transport = getTransport(serviceInfo);

            try {
                transport.open();
            } catch (TTransportException e) {
                logger.info("transport open fail service: host={}, port={}",
                        serviceInfo.getHost(), serviceInfo.getPort());
                if (poolConfig.isFailover()) {
                    while (true) {
                        try {
                            // mark current fail and try next, until none service available
                            serviceList = removeFailService(serviceList, serviceInfo);
                            serviceInfo = getRandomService(serviceList);
                            transport = getTransport(serviceInfo); // while break here
                            logger.info("failover to next service host={}, port={}",
                                    serviceInfo.getHost(), serviceInfo.getPort());
                            transport.open();
                            break;
                        } catch (TTransportException e2) {
                            logger.warn("failover fail, services left: {}", serviceList.size());
                        }
                    }
                } else {
                    throw new ConnectionFailException("host=" + serviceInfo.getHost() + ", ip="
                            + serviceInfo.getPort(), e);
                }
            }

            ThriftClient<T> client = new ThriftClient<>(clientFactory.apply(transport), pool,
                    serviceInfo);

            logger.debug("create new object for pool {}", client);
            return client;
        }

        @Override
        public PooledObject<ThriftClient<T>> wrap(ThriftClient<T> obj) {
            return new DefaultPooledObject<>(obj);
        }

        @Override
        public boolean validateObject(PooledObject<ThriftClient<T>> p) {
            ThriftClient<T> client = p.getObject();

            // check if return client in current service list if 
            if (serviceReset) {
                if (!ThriftClientPool.this.services.contains(client.getServiceInfo())) {
                    logger.warn("not return object because it's from previous config {}",
                            client);
                    client.closeClient();
                    return false;
                }
            }

            return super.validateObject(p);
        }

        @Override
        public void destroyObject(PooledObject<ThriftClient<T>> p) throws Exception {
            p.getObject().closeClient();
            super.destroyObject(p);
        }
    }, poolConfig);
}
 
Example #6
Source File: TestGenericObjectPool.java    From commons-pool with Apache License 2.0 4 votes vote down vote up
@Test(timeout = 60000)
public void testEvictionSoftMinIdle() throws Exception {
    class TimeTest extends BasePooledObjectFactory<TimeTest> {
        private final long createTime;

        public TimeTest() {
            createTime = System.currentTimeMillis();
        }

        @Override
        public TimeTest create() throws Exception {
            return new TimeTest();
        }

        public long getCreateTime() {
            return createTime;
        }

        @Override
        public PooledObject<TimeTest> wrap(final TimeTest value) {
            return new DefaultPooledObject<>(value);
        }
    }

    try (final GenericObjectPool<TimeTest> timePool = new GenericObjectPool<>(new TimeTest())) {

        timePool.setMaxIdle(5);
        timePool.setMaxTotal(5);
        timePool.setNumTestsPerEvictionRun(5);
        timePool.setMinEvictableIdleTimeMillis(3000L);
        timePool.setSoftMinEvictableIdleTimeMillis(1000L);
        timePool.setMinIdle(2);

        final TimeTest[] active = new TimeTest[5];
        final Long[] creationTime = new Long[5];
        for (int i = 0; i < 5; i++) {
            active[i] = timePool.borrowObject();
            creationTime[i] = Long.valueOf((active[i]).getCreateTime());
        }

        for (int i = 0; i < 5; i++) {
            timePool.returnObject(active[i]);
        }

        // Soft evict all but minIdle(2)
        Thread.sleep(1500L);
        timePool.evict();
        assertEquals("Idle count different than expected.", 2, timePool.getNumIdle());

        // Hard evict the rest.
        Thread.sleep(2000L);
        timePool.evict();
        assertEquals("Idle count different than expected.", 0, timePool.getNumIdle());
    }
}
 
Example #7
Source File: TestEvictionTimer.java    From commons-pool with Apache License 2.0 4 votes vote down vote up
@Test
public void testStartStopEvictionTimer() throws Exception {

    try (final GenericObjectPool<String> pool = new GenericObjectPool<>(new BasePooledObjectFactory<String>() {

        @Override
        public String create() throws Exception {
            return null;
        }

        @Override
        public PooledObject<String> wrap(final String obj) {
            return new DefaultPooledObject<>(obj);
        }
    })) {

        // Start evictor #1
        final BaseGenericObjectPool<String>.Evictor evictor1 = pool.new Evictor();
        EvictionTimer.schedule(evictor1, 60000, 60000);

        // Assert that eviction objects are correctly allocated
        // 1 - the evictor timer task is created
        final Field evictorTaskFutureField =
                evictor1.getClass().getDeclaredField("scheduledFuture");
        evictorTaskFutureField.setAccessible(true);
        ScheduledFuture<?> sf = (ScheduledFuture<?>) evictorTaskFutureField.get(evictor1);
        assertFalse(sf.isCancelled());
        // 2- and, the eviction action is added to executor thread pool
        final Field evictorExecutorField = EvictionTimer.class.getDeclaredField("executor");
        evictorExecutorField.setAccessible(true);
        final ThreadPoolExecutor evictionExecutor = (ThreadPoolExecutor) evictorExecutorField.get(null);
        assertEquals(1, evictionExecutor.getQueue().size());

        // Start evictor #2
        final BaseGenericObjectPool<String>.Evictor evictor2 = pool.new Evictor();
        EvictionTimer.schedule(evictor2, 60000, 60000);

        // Assert that eviction objects are correctly allocated
        // 1 - the evictor timer task is created
        sf = (ScheduledFuture<?>) evictorTaskFutureField.get(evictor2);
        assertFalse(sf.isCancelled());
        // 2- and, the eviction action is added to executor thread pool
        assertEquals(2, evictionExecutor.getQueue().size());

        // Stop evictor #1
        EvictionTimer.cancel(evictor1, BaseObjectPoolConfig.DEFAULT_EVICTOR_SHUTDOWN_TIMEOUT_MILLIS,
                TimeUnit.MILLISECONDS);

        // Assert that eviction objects are correctly cleaned
        // 1 - the evictor timer task is cancelled
        sf = (ScheduledFuture<?>) evictorTaskFutureField.get(evictor1);
        assertTrue(sf.isCancelled());
        // 2- and, the eviction action is removed from executor thread pool
        final ThreadPoolExecutor evictionExecutorOnStop = (ThreadPoolExecutor) evictorExecutorField.get(null);
        assertEquals(1, evictionExecutorOnStop.getQueue().size());

        // Stop evictor #2
        EvictionTimer.cancel(evictor2, BaseObjectPoolConfig.DEFAULT_EVICTOR_SHUTDOWN_TIMEOUT_MILLIS,
                TimeUnit.MILLISECONDS);

        // Assert that eviction objects are correctly cleaned
        // 1 - the evictor timer task is cancelled
        sf = (ScheduledFuture<?>) evictorTaskFutureField.get(evictor2);
        assertTrue(sf.isCancelled());
        // 2- and, the eviction thread pool executor is freed
        assertNull(evictorExecutorField.get(null));
    }
}