org.apache.commons.pool2.PooledObject Java Examples
The following examples show how to use
org.apache.commons.pool2.PooledObject.
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: DirContextPooledObjectFactoryTest.java From spring-ldap with Apache License 2.0 | 6 votes |
@Test public void testValidateObject() throws Exception { when(dirContextValidatorMock .validateDirContext(DirContextType.READ_ONLY, dirContextMock)) .thenReturn(true); final DirContextPooledObjectFactory objectFactory = new DirContextPooledObjectFactory(); objectFactory.setDirContextValidator(dirContextValidatorMock); PooledObject pooledObject = new DefaultPooledObject(dirContextMock); final boolean valid = objectFactory.validateObject(DirContextType.READ_ONLY, pooledObject); assertThat(valid).isTrue(); //Check exception in validator DirContextValidator secondDirContextValidatorMock = mock(DirContextValidator.class); when(secondDirContextValidatorMock.validateDirContext(DirContextType.READ_ONLY, dirContextMock)) .thenThrow(new RuntimeException("Failed to validate")); objectFactory.setDirContextValidator(secondDirContextValidatorMock); final boolean valid2 = objectFactory.validateObject(DirContextType.READ_ONLY, pooledObject); assertThat(valid2).isFalse(); }
Example #2
Source File: AbstractPoolableLdapConnectionFactory.java From directory-ldap-api with Apache License 2.0 | 6 votes |
/** * {@inheritDoc} * * There is nothing to do to activate a connection. */ @Override public void activateObject( PooledObject<LdapConnection> connection ) throws LdapException { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.msg( I18n.MSG_04146_ACTIVATING, connection ) ); } if ( !connection.getObject().isConnected() || !connection.getObject().isAuthenticated() ) { if ( LOG.isDebugEnabled() ) { LOG.debug( I18n.msg( I18n.MSG_04147_REBIND_CONNECTION_DROPPED, connection ) ); } connectionFactory.bindConnection( connection.getObject() ); } }
Example #3
Source File: GenericKeyedObjectPool.java From commons-pool with Apache License 2.0 | 6 votes |
/** * Clears the specified sub-pool, removing all pooled instances * corresponding to the given {@code key}. Exceptions encountered * destroying idle instances are swallowed but notified via a * {@link SwallowedExceptionListener}. * * @param key the key to clear */ @Override public void clear(final K key) { final ObjectDeque<T> objectDeque = register(key); try { final LinkedBlockingDeque<PooledObject<T>> idleObjects = objectDeque.getIdleObjects(); PooledObject<T> p = idleObjects.poll(); while (p != null) { try { destroy(key, p, true); } catch (final Exception e) { swallowException(e); } p = idleObjects.poll(); } } finally { deregister(key); } }
Example #4
Source File: TestGenericKeyedObjectPool.java From commons-pool with Apache License 2.0 | 6 votes |
@Override public PooledObject<String> makeObject(final K key) throws Exception { if (exceptionOnCreate) { throw new Exception(); } doWait(makeLatency); String out = null; synchronized(this) { activeCount++; if (activeCount > maxTotalPerKey) { throw new IllegalStateException( "Too many active instances: " + activeCount); } out = String.valueOf(key) + String.valueOf(counter++); } return new DefaultPooledObject<>(out); }
Example #5
Source File: ModbusSlaveConnectionFactoryImpl.java From openhab1-addons with Eclipse Public License 2.0 | 6 votes |
@Override public void activateObject(ModbusSlaveEndpoint endpoint, PooledObject<ModbusSlaveConnection> obj) throws Exception { if (obj.getObject() == null) { return; } try { ModbusSlaveConnection connection = obj.getObject(); EndpointPoolConfiguration config = endpointPoolConfigs.get(endpoint); if (connection.isConnected()) { if (config != null) { long waited = waitAtleast(lastPassivateMillis.get(endpoint), config.getPassivateBorrowMinMillis()); logger.trace( "Waited {}ms (passivateBorrowMinMillis {}ms) before giving returning connection {} for endpoint {}, to ensure delay between transactions.", waited, config.getPassivateBorrowMinMillis(), obj.getObject(), endpoint); } } else { // invariant: !connection.isConnected() tryConnect(endpoint, obj, connection, config); } } catch (Exception e) { logger.error("Error connecting connection {} for endpoint {}: {}", obj.getObject(), endpoint, e.getMessage()); } }
Example #6
Source File: DirContextPoolableObjectFactory.java From spring-ldap with Apache License 2.0 | 6 votes |
/** * @see BaseKeyedPooledObjectFactory#validateObject(Object, PooledObject) * * */ @Override public boolean validateObject(Object key, PooledObject<Object> pooledObject) { Assert.notNull(this.dirContextValidator, "DirContextValidator may not be null"); Assert.isTrue(key instanceof DirContextType, "key must be a DirContextType"); Assert.notNull(pooledObject, "The Object to validate must not be null"); Assert.isTrue(pooledObject.getObject() instanceof DirContext, "The Object to validate must be of type '" + DirContext.class + "'"); try { final DirContextType contextType = (DirContextType) key; final DirContext dirContext = (DirContext) pooledObject.getObject(); return this.dirContextValidator.validateDirContext(contextType, dirContext); } catch (Exception e) { this.logger.warn("Failed to validate '" + pooledObject.getObject() + "' due to an unexpected exception.", e); return false; } }
Example #7
Source File: GenericObjectPool.java From commons-pool with Apache License 2.0 | 6 votes |
/** * Tries to ensure that {@code idleCount} idle instances exist in the pool. * <p> * Creates and adds idle instances until either {@link #getNumIdle()} reaches {@code idleCount} * or the total number of objects (idle, checked out, or being created) reaches * {@link #getMaxTotal()}. If {@code always} is false, no instances are created unless * there are threads waiting to check out instances from the pool. * </p> * * @param idleCount the number of idle instances desired * @param always true means create instances even if the pool has no threads waiting * @throws Exception if the factory's makeObject throws */ private void ensureIdle(final int idleCount, final boolean always) throws Exception { if (idleCount < 1 || isClosed() || (!always && !idleObjects.hasTakeWaiters())) { return; } while (idleObjects.size() < idleCount) { final PooledObject<T> p = create(); if (p == null) { // Can't create objects, no reason to think another call to // create will work. Give up. break; } if (getLifo()) { idleObjects.addFirst(p); } else { idleObjects.addLast(p); } } if (isClosed()) { // Pool closed while object was being added to idle objects. // Make sure the returned object is destroyed rather than left // in the idle object pool (which would effectively be a leak) clear(); } }
Example #8
Source File: JedisFactory.java From feeyo-redisproxy with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Override public PooledObject<JedisConnection> makeObject() throws Exception { final HostAndPort hostAndPort = this.hostAndPort.get(); final JedisConnection jedis = new JedisConnection(hostAndPort.getHost(), hostAndPort.getPort(), connectionTimeout, soTimeout); try { jedis.connect(); if (password != null) { jedis.sendCommand(RedisCommand.AUTH, password); jedis.getStatusCodeReply(); } } catch (JedisException je) { jedis.close(); throw je; } return new DefaultPooledObject<JedisConnection>(jedis); }
Example #9
Source File: JedisFactory.java From cachecloud with Apache License 2.0 | 6 votes |
@Override public boolean validateObject(PooledObject<Jedis> pooledJedis) { final BinaryJedis jedis = pooledJedis.getObject(); try { HostAndPort hostAndPort = this.hostAndPort.get(); String connectionHost = jedis.getClient().getHost(); int connectionPort = jedis.getClient().getPort(); return hostAndPort.getHost().equals(connectionHost) && hostAndPort.getPort() == connectionPort && jedis.isConnected() && jedis.ping().equals("PONG"); } catch (final Exception e) { return false; } }
Example #10
Source File: PooledConnectionFactory.java From seppb with MIT License | 5 votes |
@Override public void destroyObject(PooledObject<TrackerServer> pooledObject) throws IOException { TrackerServer trackerServer = pooledObject.getObject(); if (trackerServer != null) { trackerServer.close(); } }
Example #11
Source File: ElasticsearchClientFactory.java From super-cloudops with Apache License 2.0 | 5 votes |
@Override public PooledObject<RestHighLevelClient> makeObject() throws Exception { Set<String> hostSet = new HashSet<String>( this.elasticsearchClientConfigure.getHosts().length + this.elasticsearchClientConfigure.getHosts().length / 3); for (String h : this.elasticsearchClientConfigure.getHosts()) { hostSet.add(h); } HttpHost[] httpHosts = hostSet.stream() .map(host -> new HttpHost(host, elasticsearchClientConfigure.getPort(), elasticsearchClientConfigure.getSchema())) .toArray(len -> new HttpHost[len]); RestClientBuilder clientBuilder = RestClient.builder(httpHosts); RestHighLevelClient client = new RestHighLevelClient(clientBuilder); return new DefaultPooledObject<RestHighLevelClient>(client); }
Example #12
Source File: SleepingObjectFactory.java From commons-pool with Apache License 2.0 | 5 votes |
@Override public PooledObject<Integer> makeObject() throws Exception { // Deliberate choice to create a new object in case future unit tests // check for a specific object. final Integer obj = new Integer(counter++); debug("makeObject", obj); sleep(500); return new DefaultPooledObject<>(obj); }
Example #13
Source File: BaseGenericObjectPool.java From commons-pool with Apache License 2.0 | 5 votes |
/** * Create an EvictionIterator for the provided idle instance deque. * @param idleObjects underlying deque */ EvictionIterator(final Deque<PooledObject<T>> idleObjects) { this.idleObjects = idleObjects; if (getLifo()) { idleObjectIterator = idleObjects.descendingIterator(); } else { idleObjectIterator = idleObjects.iterator(); } }
Example #14
Source File: DirContextPooledObjectFactoryTest.java From spring-ldap with Apache License 2.0 | 5 votes |
@Test public void testMakeObjectReadWrite() throws Exception { final DirContextPooledObjectFactory objectFactory = new DirContextPooledObjectFactory(); DirContext readWriteContextMock = mock(DirContext.class); when(contextSourceMock.getReadWriteContext()).thenReturn(readWriteContextMock); objectFactory.setContextSource(contextSourceMock); final PooledObject createdDirContext = objectFactory.makeObject(DirContextType.READ_WRITE); InvocationHandler invocationHandler = Proxy.getInvocationHandler(createdDirContext.getObject()); assertThat(readWriteContextMock).isEqualTo(Whitebox.getInternalState(invocationHandler, "target")); }
Example #15
Source File: KeyedCPDSConnectionFactory.java From commons-dbcp with Apache License 2.0 | 5 votes |
private void validateLifetime(final PooledObject<PooledConnectionAndInfo> p) throws Exception { if (maxConnLifetimeMillis > 0) { final long lifetime = System.currentTimeMillis() - p.getCreateTime(); if (lifetime > maxConnLifetimeMillis) { throw new Exception(Utils.getMessage("connectionFactory.lifetimeExceeded", Long.valueOf(lifetime), Long.valueOf(maxConnLifetimeMillis))); } } }
Example #16
Source File: GenericKeyedObjectPool.java From commons-pool with Apache License 2.0 | 5 votes |
/** * Whether there is at least one thread waiting on this deque, add an pool object. * @param key pool key. * @param idleObjects list of idle pool objects. */ private void whenWaitersAddObject(final K key, final LinkedBlockingDeque<PooledObject<T>> idleObjects) { if (idleObjects.hasTakeWaiters()) { try { addObject(key); } catch (final Exception e) { swallowException(e); } } }
Example #17
Source File: ThriftConnectionFactory.java From ThriftJ with Apache License 2.0 | 5 votes |
@Override public PooledObject<TTransport> makeObject(ThriftServer thriftServer) throws Exception { TSocket tsocket = new TSocket(thriftServer.getHost(), thriftServer.getPort()); tsocket.setTimeout(timeout); TFramedTransport transport = new TFramedTransport(tsocket); transport.open(); DefaultPooledObject<TTransport> result = new DefaultPooledObject<TTransport>(transport); logger.trace("Make new thrift connection: {}:{}", thriftServer.getHost(), thriftServer.getPort()); return result; }
Example #18
Source File: GenericObjectPool.java From commons-pool with Apache License 2.0 | 5 votes |
/** * Creates an object, and place it into the pool. addObject() is useful for * "pre-loading" a pool with idle objects. * <p> * If there is no capacity available to add to the pool, this is a no-op * (no exception, no impact to the pool). </p> */ @Override public void addObject() throws Exception { assertOpen(); if (factory == null) { throw new IllegalStateException( "Cannot add objects without a factory."); } final PooledObject<T> p = create(); addIdleObject(p); }
Example #19
Source File: ThriftConnectionFactory.java From ThriftJ with Apache License 2.0 | 5 votes |
@Override public void destroyObject(ThriftServer thriftServer, PooledObject<TTransport> pooledObject) throws Exception { TTransport transport = pooledObject.getObject(); if (transport != null) { transport.close(); logger.trace("Close thrift connection: {}:{}", thriftServer.getHost(), thriftServer.getPort()); } }
Example #20
Source File: GenericObjectPool.java From commons-pool with Apache License 2.0 | 5 votes |
/** * Adds the provided wrapped pooled object to the set of idle objects for * this pool. The object must already be part of the pool. If {@code p} * is null, this is a no-op (no exception, but no impact on the pool). * * @param p The object to make idle * * @throws Exception If the factory fails to passivate the object */ private void addIdleObject(final PooledObject<T> p) throws Exception { if (p != null) { factory.passivateObject(p); if (getLifo()) { idleObjects.addFirst(p); } else { idleObjects.addLast(p); } } }
Example #21
Source File: TestBatch.java From phoenix-omid with Apache License 2.0 | 5 votes |
@Test(timeOut = 10_000) public void testBatchFactoryFunctionality() throws Exception { // Component to test Batch.BatchFactory factory = new Batch.BatchFactory(BATCH_SIZE); // Check the factory creates a new batch properly... Batch batch = factory.create(); assertTrue(batch.isEmpty(), "Batch should be empty"); assertFalse(batch.isFull(), "Batch shouldn't be full"); assertEquals(batch.getNumEvents(), 0, "Num events should be 0"); // ...and is wrapped in to a pooled object PooledObject<Batch> pooledBatch = factory.wrap(batch); assertEquals(pooledBatch.getObject(), batch); // Put some elements in the batch... batch.addTimestamp(ANY_ST, channel, monCtx); batch.addCommit(ANY_ST, ANY_CT, channel, monCtx, Optional.<Long>absent()); batch.addCommitRetry(ANY_ST, channel, monCtx); batch.addAbort(ANY_ST, channel, monCtx); assertFalse(batch.isEmpty(), "Batch should contain elements"); assertFalse(batch.isFull(), "Batch should NOT be full"); assertEquals(batch.getNumEvents(), 4, "Num events should be 4"); // ... and passivate the object through the factory. It should reset the state of the batch factory.passivateObject(pooledBatch); assertTrue(batch.isEmpty(), "Batch should NOT contain elements"); assertFalse(batch.isFull(), "Batch should NOT be full"); assertEquals(batch.getNumEvents(), 0, "Num events should be 0"); }
Example #22
Source File: PooledSessionFactory.java From cyberduck with GNU General Public License v3.0 | 5 votes |
@Override public void passivateObject(final PooledObject<Session> p) { final Session session = p.getObject(); if(log.isDebugEnabled()) { log.debug(String.format("Pause session %s", session)); } }
Example #23
Source File: HdfsFactory.java From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International | 5 votes |
@Override public void destroyObject(PooledObject<FileSystem> pooledObject) throws IOException { if (pooledObject == null) { return; } FileSystem fileSystem = pooledObject.getObject(); try { fileSystem.close(); } finally { fileSystem = null; } }
Example #24
Source File: TestGenericObjectPool.java From commons-pool with Apache License 2.0 | 5 votes |
@Override public void passivateObject(final PooledObject<String> obj) throws Exception { final boolean hurl; synchronized(this) { hurl = exceptionOnPassivate; } if (hurl) { throw new Exception(); } }
Example #25
Source File: ElasticsearchClientFactory.java From super-cloudops with Apache License 2.0 | 5 votes |
@Override public void activateObject(PooledObject<RestHighLevelClient> p) throws Exception { boolean result = false; try { result = p.getObject().ping(); } catch (IOException e) { log.debug("http pool active client ,ping result :{}", result); } }
Example #26
Source File: TestAbandonedObjectPool.java From commons-pool with Apache License 2.0 | 5 votes |
@Override public boolean validateObject(final PooledObject<PooledTestObject> obj) { try { Thread.sleep(validateLatency); } catch (final Exception ex) { // ignore } return true; }
Example #27
Source File: TestSoftRefOutOfMemory.java From commons-pool with Apache License 2.0 | 4 votes |
@Override public PooledObject<String> wrap(final String value) { return new DefaultPooledObject<>(value); }
Example #28
Source File: CommonsPool2TargetSource.java From lams with GNU General Public License v2.0 | 4 votes |
@Override public boolean validateObject(PooledObject<Object> p) { return true; }
Example #29
Source File: DummyEvictionPolicy.java From spring-ldap with Apache License 2.0 | 4 votes |
/** * @see EvictionPolicy#evict(EvictionConfig, PooledObject, int) * * */ @Override public boolean evict(EvictionConfig config, PooledObject underTest, int idleCount) { return false; }
Example #30
Source File: RabbitMQClient.java From jweb-cms with GNU Affero General Public License v3.0 | 4 votes |
@Override public void activateObject(PooledObject<Channel> p) throws Exception { }