index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
0
Create_ds/commons-pool/src/test/java/org/apache/commons
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/TestTrackedUse.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3; import static org.junit.jupiter.api.Assertions.assertEquals; import java.time.Instant; import org.junit.jupiter.api.Test; public class TestTrackedUse { final class DefaultTrackedUse implements TrackedUse { @Override public Instant getLastUsedInstant() { return Instant.ofEpochMilli(1); } } @Test public void testDefaultGetLastUsedInstant() { assertEquals(Instant.ofEpochMilli(1), new DefaultTrackedUse().getLastUsedInstant()); } }
5,200
0
Create_ds/commons-pool/src/test/java/org/apache/commons
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/TestBaseKeyedPooledObjectFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3; import static org.junit.jupiter.api.Assertions.assertTrue; import org.apache.commons.pool3.impl.DefaultPooledObject; import org.junit.jupiter.api.Test; /** */ public class TestBaseKeyedPooledObjectFactory { private static final class TestFactory extends BaseKeyedPooledObjectFactory<Object, Object, RuntimeException> { @Override public Object create(final Object key) { return null; } @Override public PooledObject<Object> wrap(final Object value) { return new DefaultPooledObject<>(value); } } @Test public void testDefaultMethods() { final KeyedPooledObjectFactory<Object, Object, RuntimeException> factory = new TestFactory(); factory.activateObject("key",null); // a no-op factory.passivateObject("key",null); // a no-op factory.destroyObject("key",null); // a no-op assertTrue(factory.validateObject("key",null)); // constant true } }
5,201
0
Create_ds/commons-pool/src/test/java/org/apache/commons
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/MethodCallPoolableObjectFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3; import java.util.ArrayList; import java.util.List; import org.apache.commons.pool3.impl.DefaultPooledObject; /** * A poolable object factory that tracks how {@link MethodCall methods are called}. * * @see MethodCall */ public class MethodCallPoolableObjectFactory implements PooledObjectFactory<Object, PrivateException> { private final List<MethodCall> methodCalls = new ArrayList<>(); private int count; private boolean valid = true; private boolean makeObjectFail; private boolean activateObjectFail; private boolean validateObjectFail; private boolean passivateObjectFail; private boolean destroyObjectFail; @Override public void activateObject(final PooledObject<Object> obj) { methodCalls.add(new MethodCall("activateObject", obj.getObject())); if (activateObjectFail) { throw new PrivateException("activateObject"); } } @Override public void destroyObject(final PooledObject<Object> obj) { methodCalls.add(new MethodCall("destroyObject", obj.getObject())); if (destroyObjectFail) { throw new PrivateException("destroyObject"); } } public int getCurrentCount() { return count; } public List<MethodCall> getMethodCalls() { return methodCalls; } public boolean isActivateObjectFail() { return activateObjectFail; } public boolean isDestroyObjectFail() { return destroyObjectFail; } public boolean isMakeObjectFail() { return makeObjectFail; } public boolean isPassivateObjectFail() { return passivateObjectFail; } public boolean isValid() { return valid; } public boolean isValidateObjectFail() { return validateObjectFail; } @Override public PooledObject<Object> makeObject() { final MethodCall call = new MethodCall("makeObject"); methodCalls.add(call); final int originalCount = this.count++; if (makeObjectFail) { throw new PrivateException("makeObject"); } // Generate new object, don't use cache via Integer.valueOf(...) final Integer obj = Integer.valueOf(originalCount); call.setReturned(obj); return new DefaultPooledObject<>(obj); } @Override public void passivateObject(final PooledObject<Object> obj) { methodCalls.add(new MethodCall("passivateObject", obj.getObject())); if (passivateObjectFail) { throw new PrivateException("passivateObject"); } } public void reset() { count = 0; getMethodCalls().clear(); setMakeObjectFail(false); setActivateObjectFail(false); setValid(true); setValidateObjectFail(false); setPassivateObjectFail(false); setDestroyObjectFail(false); } public void setActivateObjectFail(final boolean activateObjectFail) { this.activateObjectFail = activateObjectFail; } public void setCurrentCount(final int count) { this.count = count; } public void setDestroyObjectFail(final boolean destroyObjectFail) { this.destroyObjectFail = destroyObjectFail; } public void setMakeObjectFail(final boolean makeObjectFail) { this.makeObjectFail = makeObjectFail; } public void setPassivateObjectFail(final boolean passivateObjectFail) { this.passivateObjectFail = passivateObjectFail; } public void setValid(final boolean valid) { this.valid = valid; } public void setValidateObjectFail(final boolean validateObjectFail) { this.validateObjectFail = validateObjectFail; } @Override public boolean validateObject(final PooledObject<Object> obj) { final MethodCall call = new MethodCall("validateObject", obj.getObject()); methodCalls.add(call); if (validateObjectFail) { throw new PrivateException("validateObject"); } final boolean r = valid; call.returned(Boolean.valueOf(r)); return r; } }
5,202
0
Create_ds/commons-pool/src/test/java/org/apache/commons
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/MethodCall.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Objects; /** * Holds method names, parameters, and return values for tracing method calls. */ public class MethodCall { private final String name; private final List<Object> params; private Object returned; public MethodCall(final String name) { this(name, null); } public MethodCall(final String name, final List<Object> params) { if (name == null) { throw new IllegalArgumentException("name must not be null."); } this.name = name; if (params != null) { this.params = params; } else { this.params = Collections.emptyList(); } } public MethodCall(final String name, final Object param) { this(name, Collections.singletonList(param)); } public MethodCall(final String name, final Object param1, final Object param2) { this(name, Arrays.asList(param1, param2)); } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final MethodCall that = (MethodCall)o; if (!Objects.equals(name, that.name)) { return false; } if (!Objects.equals(params, that.params)) { return false; } return Objects.equals(returned, that.returned); } public String getName() { return name; } public List<Object> getParams() { return params; } public Object getReturned() { return returned; } @Override public int hashCode() { int result; result = name != null ? name.hashCode() : 0; result = 29 * result + (params != null ? params.hashCode() : 0); result = 29 * result + (returned != null ? returned.hashCode() : 0); return result; } public MethodCall returned(final Object obj) { setReturned(obj); return this; } public void setReturned(final Object returned) { this.returned = returned; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("MethodCall"); sb.append("{name='").append(name).append('\''); if (!params.isEmpty()) { sb.append(", params=").append(params); } if (returned != null) { sb.append(", returned=").append(returned); } sb.append('}'); return sb.toString(); } }
5,203
0
Create_ds/commons-pool/src/test/java/org/apache/commons
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/TestBasePoolableObjectFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.concurrent.atomic.AtomicInteger; import org.apache.commons.pool3.impl.DefaultPooledObject; import org.junit.jupiter.api.Test; /** */ public class TestBasePoolableObjectFactory { private static final class TestFactory extends BasePooledObjectFactory<AtomicInteger, RuntimeException> { @Override public AtomicInteger create() { return new AtomicInteger(0); } @Override public void destroyObject(final PooledObject<AtomicInteger> p, final DestroyMode destroyMode){ if (destroyMode.equals(DestroyMode.ABANDONED)) { p.getObject().incrementAndGet(); } } @Override public PooledObject<AtomicInteger> wrap(final AtomicInteger value) { return new DefaultPooledObject<>(value); } } @Test public void testDefaultMethods() { final PooledObjectFactory<AtomicInteger, RuntimeException> factory = new TestFactory(); factory.activateObject(null); // a no-op factory.passivateObject(null); // a no-op factory.destroyObject(null); // a no-op assertTrue(factory.validateObject(null)); // constant true } /** * Default destroy does nothing to underlying AtomicInt, ABANDONED mode * increments the value. Verify that destroy with no mode does default, * destroy with ABANDONED mode increments. * * @throws RuntimeException May occur in some failure modes */ @Test public void testDestroyModes() { final PooledObjectFactory<AtomicInteger, RuntimeException> factory = new TestFactory(); final PooledObject<AtomicInteger> pooledObj = factory.makeObject(); final AtomicInteger obj = pooledObj.getObject(); factory.destroyObject(pooledObj); assertEquals(0, obj.get()); factory.destroyObject(pooledObj, DestroyMode.ABANDONED); assertEquals(1, obj.get()); } }
5,204
0
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/impl/TestGenericKeyedObjectPool.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.impl; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotSame; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import java.lang.management.ManagementFactory; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.NoSuchElementException; import java.util.Objects; import java.util.Random; import java.util.Set; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.Semaphore; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import javax.management.MBeanServer; import javax.management.ObjectName; import org.apache.commons.lang3.exception.ExceptionUtils; import org.apache.commons.pool3.AbstractTestKeyedObjectPool; import org.apache.commons.pool3.BaseKeyedPooledObjectFactory; import org.apache.commons.pool3.DestroyMode; import org.apache.commons.pool3.KeyedObjectPool; import org.apache.commons.pool3.KeyedPooledObjectFactory; import org.apache.commons.pool3.PooledObject; import org.apache.commons.pool3.TestException; import org.apache.commons.pool3.VisitTracker; import org.apache.commons.pool3.VisitTrackerFactory; import org.apache.commons.pool3.Waiter; import org.apache.commons.pool3.WaiterFactory; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; /** */ public class TestGenericKeyedObjectPool extends AbstractTestKeyedObjectPool { private static final class DaemonThreadFactory implements ThreadFactory { @Override public Thread newThread(final Runnable r) { final Thread t = new Thread(r); t.setDaemon(true); return t; } } private static final class DummyFactory extends BaseKeyedPooledObjectFactory<Object, Object, RuntimeException> { @Override public Object create(final Object key) { return null; } @Override public PooledObject<Object> wrap(final Object value) { return new DefaultPooledObject<>(value); } } /** * Factory that creates HashSets. Note that this means * 0) All instances are initially equal (not discernible by equals) * 1) Instances are mutable and mutation can cause change in identity / hash code. */ private static final class HashSetFactory extends BaseKeyedPooledObjectFactory<String, HashSet<String>, RuntimeException> { @Override public HashSet<String> create(final String key) { return new HashSet<>(); } @Override public PooledObject<HashSet<String>> wrap(final HashSet<String> value) { return new DefaultPooledObject<>(value); } } /** * Attempts to invalidate an object, swallowing IllegalStateException. */ static class InvalidateThread implements Runnable { private final String obj; private final KeyedObjectPool<String, String, ? extends Exception> pool; private final String key; private boolean done; public InvalidateThread(final KeyedObjectPool<String, String, ? extends Exception> pool, final String key, final String obj) { this.obj = obj; this.pool = pool; this.key = key; } public boolean complete() { return done; } @Override public void run() { try { pool.invalidateObject(key, obj); } catch (final IllegalStateException ex) { // Ignore } catch (final Exception ex) { fail("Unexpected exception " + ex.toString()); } finally { done = true; } } } private static final class ObjectFactory extends BaseKeyedPooledObjectFactory<Integer, Object, RuntimeException> { @Override public Object create(final Integer key) { return new Object(); } @Override public PooledObject<Object> wrap(final Object value) { return new DefaultPooledObject<>(value); } } public static class SimpleFactory<K> implements KeyedPooledObjectFactory<K, String, TestException> { volatile int counter; final boolean valid; int activeCount; int validateCounter; boolean evenValid = true; boolean oddValid = true; boolean enableValidation; long destroyLatency; long makeLatency; long validateLatency; volatile int maxTotalPerKey = Integer.MAX_VALUE; boolean exceptionOnPassivate; boolean exceptionOnActivate; boolean exceptionOnDestroy; boolean exceptionOnValidate; boolean exceptionOnCreate; public SimpleFactory() { this(true); } public SimpleFactory(final boolean valid) { this.valid = valid; } @Override public void activateObject(final K key, final PooledObject<String> obj) throws TestException { if (exceptionOnActivate && !(validateCounter++ % 2 == 0 ? evenValid : oddValid)) { throw new TestException(); } } @Override public void destroyObject(final K key, final PooledObject<String> obj) throws TestException { doWait(destroyLatency); synchronized(this) { activeCount--; } if (exceptionOnDestroy) { throw new TestException(); } } private void doWait(final long latency) { Waiter.sleepQuietly(latency); } @Override public PooledObject<String> makeObject(final K key) throws TestException { if (exceptionOnCreate) { throw new TestException(); } 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); } @Override public void passivateObject(final K key, final PooledObject<String> obj) throws TestException { if (exceptionOnPassivate) { throw new TestException(); } } public void setDestroyLatency(final long destroyLatency) { this.destroyLatency = destroyLatency; } void setEvenValid(final boolean valid) { evenValid = valid; } public void setMakeLatency(final long makeLatency) { this.makeLatency = makeLatency; } public void setMaxTotalPerKey(final int maxTotalPerKey) { this.maxTotalPerKey = maxTotalPerKey; } public void setThrowExceptionOnActivate(final boolean b) { exceptionOnActivate = b; } public void setThrowExceptionOnDestroy(final boolean b) { exceptionOnDestroy = b; } public void setThrowExceptionOnPassivate(final boolean b) { exceptionOnPassivate = b; } public void setThrowExceptionOnValidate(final boolean b) { exceptionOnValidate = b; } void setValid(final boolean valid) { evenValid = valid; oddValid = valid; } public void setValidateLatency(final long validateLatency) { this.validateLatency = validateLatency; } public void setValidationEnabled(final boolean b) { enableValidation = b; } @Override public boolean validateObject(final K key, final PooledObject<String> obj) { doWait(validateLatency); if (exceptionOnValidate) { throw new RuntimeException("validation failed"); } if (enableValidation) { return validateCounter++ % 2 == 0 ? evenValid : oddValid; } return valid; } } private static final class SimplePerKeyFactory extends BaseKeyedPooledObjectFactory<Object, Object, RuntimeException> { final ConcurrentHashMap<Object, AtomicInteger> map = new ConcurrentHashMap<>(); @Override public Object create(final Object key) { int counter = map.computeIfAbsent(key, k -> new AtomicInteger(-1)).incrementAndGet(); return String.valueOf(key) + String.valueOf(counter); } @Override public PooledObject<Object> wrap(final Object value) { return new DefaultPooledObject<>(value); } } /** * Very simple test thread that just tries to borrow an object from * the provided pool with the specified key and returns it */ static class SimpleTestThread<T, E extends Exception> implements Runnable { private final KeyedObjectPool<String, T, E> pool; private final String key; public SimpleTestThread(final KeyedObjectPool<String, T, E> pool, final String key) { this.pool = pool; this.key = key; } @Override public void run() { try { pool.returnObject(key, pool.borrowObject(key)); } catch (final Exception e) { // Ignore } } } /** * DefaultEvictionPolicy modified to add latency */ private static final class SlowEvictionPolicy<T> extends DefaultEvictionPolicy<T> { private final long delay; /** * Constructs SlowEvictionPolicy with the given delay in ms * * @param delay number of ms of latency to inject in evict */ public SlowEvictionPolicy(final long delay) { this.delay = delay; } @Override public boolean evict(final EvictionConfig config, final PooledObject<T> underTest, final int idleCount) { Waiter.sleepQuietly(delay); return super.evict(config, underTest, idleCount); } } static class TestThread<T, E extends Exception> implements Runnable { private final java.util.Random random = new java.util.Random(); /** GKOP to hit */ private final KeyedObjectPool<String, T, E> pool; /** number of borrow/return iterations */ private final int iter; /** delay before borrow */ private final int startDelay; /** delay before return */ private final int holdTime; /** whether or not delays are random (with max = configured values) */ private final boolean randomDelay; /** expected object */ private final T expectedObject; /** key used in borrow / return sequence - null means random */ private final String key; private volatile boolean complete; private volatile boolean failed; private volatile Exception exception; public TestThread(final KeyedObjectPool<String, T, E> pool) { this(pool, 100, 50, 50, true, null, null); } public TestThread(final KeyedObjectPool<String, T, E> pool, final int iter) { this(pool, iter, 50, 50, true, null, null); } public TestThread(final KeyedObjectPool<String, T, E> pool, final int iter, final int delay) { this(pool, iter, delay, delay, true, null, null); } public TestThread(final KeyedObjectPool<String, T, E> pool, final int iter, final int startDelay, final int holdTime, final boolean randomDelay, final T expectedObject, final String key) { this.pool = pool; this.iter = iter; this.startDelay = startDelay; this.holdTime = holdTime; this.randomDelay = randomDelay; this.expectedObject = expectedObject; this.key = key; } public boolean complete() { return complete; } public boolean failed() { return failed; } @Override public void run() { for (int i = 0; i < iter; i++) { final String actualKey = key == null ? String.valueOf(random.nextInt(3)) : key; Waiter.sleepQuietly(randomDelay ? random.nextInt(startDelay) : startDelay); T obj = null; try { obj = pool.borrowObject(actualKey); } catch (final Exception e) { exception = e; failed = true; complete = true; break; } if (expectedObject != null && !expectedObject.equals(obj)) { exception = new Exception("Expected: " + expectedObject + " found: " + obj); failed = true; complete = true; break; } Waiter.sleepQuietly(randomDelay ? random.nextInt(holdTime) : holdTime); try { pool.returnObject(actualKey, obj); } catch (final Exception e) { exception = e; failed = true; complete = true; break; } } complete = true; } } /* * Very simple test thread that just tries to borrow an object from * the provided pool with the specified key and returns it after a wait */ static class WaitingTestThread<E extends Exception> extends Thread { private final KeyedObjectPool<String, String, E> pool; private final String key; private final long pause; private Throwable thrown; private long preBorrowMillis; // just before borrow private long postBorrowMillis; // borrow returned private long postReturnMillis; // after object was returned private long endedMillis; private String objectId; public WaitingTestThread(final KeyedObjectPool<String, String, E> pool, final String key, final long pause) { this.pool = pool; this.key = key; this.pause = pause; this.thrown = null; } @Override public void run() { try { preBorrowMillis = System.currentTimeMillis(); final String obj = pool.borrowObject(key); objectId = obj; postBorrowMillis = System.currentTimeMillis(); Thread.sleep(pause); pool.returnObject(key, obj); postReturnMillis = System.currentTimeMillis(); } catch (final Exception e) { thrown = e; } finally{ endedMillis = System.currentTimeMillis(); } } } private static final Integer KEY_ZERO = Integer.valueOf(0); private static final Integer KEY_ONE = Integer.valueOf(1); private static final Integer KEY_TWO = Integer.valueOf(2); private static final boolean DISPLAY_THREAD_DETAILS= Boolean.getBoolean("TestGenericKeyedObjectPool.display.thread.details"); // To pass this to a Maven test, use: // mvn test -DargLine="-DTestGenericKeyedObjectPool.display.thread.details=true" // @see https://issues.apache.org/jira/browse/SUREFIRE-121 /** setUp(): {@code new GenericKeyedObjectPool<String,String>(factory)} */ private GenericKeyedObjectPool<String, String, TestException> gkoPool; /** setUp(): {@code new SimpleFactory<String>()} */ private SimpleFactory<String> simpleFactory; private void checkEvictionOrder(final boolean lifo) throws InterruptedException, TestException { final SimpleFactory<Integer> intFactory = new SimpleFactory<>(); try (final GenericKeyedObjectPool<Integer, String, TestException> intPool = new GenericKeyedObjectPool<>(intFactory)) { intPool.setNumTestsPerEvictionRun(2); intPool.setMinEvictableIdleDuration(Duration.ofMillis(100)); intPool.setLifo(lifo); for (int i = 0; i < 3; i++) { final Integer key = Integer.valueOf(i); for (int j = 0; j < 5; j++) { intPool.addObject(key); } } // Make all evictable Thread.sleep(200); /* * Initial state (Key, Object) pairs in order of age: * * (0,0), (0,1), (0,2), (0,3), (0,4) (1,5), (1,6), (1,7), (1,8), (1,9) (2,10), (2,11), (2,12), (2,13), * (2,14) */ intPool.evict(); // Kill (0,0),(0,1) assertEquals(3, intPool.getNumIdle(KEY_ZERO)); final String objZeroA = intPool.borrowObject(KEY_ZERO); assertTrue(lifo ? objZeroA.equals("04") : objZeroA.equals("02")); assertEquals(2, intPool.getNumIdle(KEY_ZERO)); final String objZeroB = intPool.borrowObject(KEY_ZERO); assertEquals("03", objZeroB); assertEquals(1, intPool.getNumIdle(KEY_ZERO)); intPool.evict(); // Kill remaining 0 survivor and (1,5) assertEquals(0, intPool.getNumIdle(KEY_ZERO)); assertEquals(4, intPool.getNumIdle(KEY_ONE)); final String objOneA = intPool.borrowObject(KEY_ONE); assertTrue(lifo ? objOneA.equals("19") : objOneA.equals("16")); assertEquals(3, intPool.getNumIdle(KEY_ONE)); final String objOneB = intPool.borrowObject(KEY_ONE); assertTrue(lifo ? objOneB.equals("18") : objOneB.equals("17")); assertEquals(2, intPool.getNumIdle(KEY_ONE)); intPool.evict(); // Kill remaining 1 survivors assertEquals(0, intPool.getNumIdle(KEY_ONE)); intPool.evict(); // Kill (2,10), (2,11) assertEquals(3, intPool.getNumIdle(KEY_TWO)); final String objTwoA = intPool.borrowObject(KEY_TWO); assertTrue(lifo ? objTwoA.equals("214") : objTwoA.equals("212")); assertEquals(2, intPool.getNumIdle(KEY_TWO)); intPool.evict(); // All dead now assertEquals(0, intPool.getNumIdle(KEY_TWO)); intPool.evict(); // Should do nothing - make sure no exception // Currently 2 zero, 2 one and 1 two active. Return them intPool.returnObject(KEY_ZERO, objZeroA); intPool.returnObject(KEY_ZERO, objZeroB); intPool.returnObject(KEY_ONE, objOneA); intPool.returnObject(KEY_ONE, objOneB); intPool.returnObject(KEY_TWO, objTwoA); // Remove all idle objects intPool.clear(); // Reload intPool.setMinEvictableIdleDuration(Duration.ofMillis(500)); intFactory.counter = 0; // Reset counter for (int i = 0; i < 3; i++) { final Integer key = Integer.valueOf(i); for (int j = 0; j < 5; j++) { intPool.addObject(key); } Thread.sleep(200); } // 0's are evictable, others not intPool.evict(); // Kill (0,0),(0,1) assertEquals(3, intPool.getNumIdle(KEY_ZERO)); intPool.evict(); // Kill (0,2),(0,3) assertEquals(1, intPool.getNumIdle(KEY_ZERO)); intPool.evict(); // Kill (0,4), leave (1,5) assertEquals(0, intPool.getNumIdle(KEY_ZERO)); assertEquals(5, intPool.getNumIdle(KEY_ONE)); assertEquals(5, intPool.getNumIdle(KEY_TWO)); intPool.evict(); // (1,6), (1,7) assertEquals(5, intPool.getNumIdle(KEY_ONE)); assertEquals(5, intPool.getNumIdle(KEY_TWO)); intPool.evict(); // (1,8), (1,9) assertEquals(5, intPool.getNumIdle(KEY_ONE)); assertEquals(5, intPool.getNumIdle(KEY_TWO)); intPool.evict(); // (2,10), (2,11) assertEquals(5, intPool.getNumIdle(KEY_ONE)); assertEquals(5, intPool.getNumIdle(KEY_TWO)); intPool.evict(); // (2,12), (2,13) assertEquals(5, intPool.getNumIdle(KEY_ONE)); assertEquals(5, intPool.getNumIdle(KEY_TWO)); intPool.evict(); // (2,14), (1,5) assertEquals(5, intPool.getNumIdle(KEY_ONE)); assertEquals(5, intPool.getNumIdle(KEY_TWO)); Thread.sleep(200); // Ones now timed out intPool.evict(); // kill (1,6), (1,7) - (1,5) missed assertEquals(3, intPool.getNumIdle(KEY_ONE)); assertEquals(5, intPool.getNumIdle(KEY_TWO)); final String obj = intPool.borrowObject(KEY_ONE); if (lifo) { assertEquals("19", obj); } else { assertEquals("15", obj); } } } private void checkEvictorVisiting(final boolean lifo) throws Exception { VisitTrackerFactory<Integer> trackerFactory = new VisitTrackerFactory<>(); try (GenericKeyedObjectPool<Integer, VisitTracker<Integer>, RuntimeException> intPool = new GenericKeyedObjectPool<>( trackerFactory)) { intPool.setNumTestsPerEvictionRun(2); intPool.setMinEvictableIdleDuration(Duration.ofMillis(-1)); intPool.setTestWhileIdle(true); intPool.setLifo(lifo); intPool.setTestOnReturn(false); intPool.setTestOnBorrow(false); for (int i = 0; i < 3; i++) { trackerFactory.resetId(); final Integer key = Integer.valueOf(i); for (int j = 0; j < 8; j++) { intPool.addObject(key); } } intPool.evict(); // Visit oldest 2 - 00 and 01 VisitTracker<Integer> obj = intPool.borrowObject(KEY_ZERO); intPool.returnObject(KEY_ZERO, obj); obj = intPool.borrowObject(KEY_ZERO); intPool.returnObject(KEY_ZERO, obj); // borrow, return, borrow, return // FIFO will move 0 and 1 to end - 2,3,4,5,6,7,0,1 // LIFO, 7 out, then in, then out, then in - 7,6,5,4,3,2,1,0 intPool.evict(); // Should visit 02 and 03 in either case for (int i = 0; i < 8; i++) { final VisitTracker<Integer> tracker = intPool.borrowObject(KEY_ZERO); if (tracker.getId() >= 4) { assertEquals( 0, tracker.getValidateCount(),"Unexpected instance visited " + tracker.getId()); } else { assertEquals( 1, tracker.getValidateCount(),"Instance " + tracker.getId() + " visited wrong number of times."); } } // 0's are all out intPool.setNumTestsPerEvictionRun(3); intPool.evict(); // 10, 11, 12 intPool.evict(); // 13, 14, 15 obj = intPool.borrowObject(KEY_ONE); intPool.returnObject(KEY_ONE, obj); obj = intPool.borrowObject(KEY_ONE); intPool.returnObject(KEY_ONE, obj); obj = intPool.borrowObject(KEY_ONE); intPool.returnObject(KEY_ONE, obj); // borrow, return, borrow, return // FIFO 3,4,5,^,6,7,0,1,2 // LIFO 7,6,^,5,4,3,2,1,0 // In either case, pointer should be at 6 intPool.evict(); // LIFO - 16, 17, 20 // FIFO - 16, 17, 10 intPool.evict(); // LIFO - 21, 22, 23 // FIFO - 11, 12, 20 intPool.evict(); // LIFO - 24, 25, 26 // FIFO - 21, 22, 23 intPool.evict(); // LIFO - 27, 10, 11 // FIFO - 24, 25, 26 for (int i = 0; i < 8; i++) { final VisitTracker<Integer> tracker = intPool.borrowObject(KEY_ONE); if (lifo && tracker.getId() > 1 || !lifo && tracker.getId() > 2) { assertEquals( 1, tracker.getValidateCount(),"Instance " + tracker.getId() + " visited wrong number of times."); } else { assertEquals( 2, tracker.getValidateCount(),"Instance " + tracker.getId() + " visited wrong number of times."); } } } // Randomly generate some pools with random numTests // and make sure evictor cycles through elements appropriately final int[] smallPrimes = { 2, 3, 5, 7 }; final Random random = new Random(); random.setSeed(System.currentTimeMillis()); for (int i = 0; i < smallPrimes.length; i++) { for (int j = 0; j < 5; j++) {// Try the tests a few times // Can't use clear as some objects are still active so create // a new pool trackerFactory = new VisitTrackerFactory<>(); try (GenericKeyedObjectPool<Integer, VisitTracker<Integer>, RuntimeException> intPool = new GenericKeyedObjectPool<>( trackerFactory)) { intPool.setMaxIdlePerKey(-1); intPool.setMaxTotalPerKey(-1); intPool.setNumTestsPerEvictionRun(smallPrimes[i]); intPool.setMinEvictableIdleDuration(Duration.ofMillis(-1)); intPool.setTestWhileIdle(true); intPool.setLifo(lifo); intPool.setTestOnReturn(false); intPool.setTestOnBorrow(false); final int zeroLength = 10 + random.nextInt(20); for (int k = 0; k < zeroLength; k++) { intPool.addObject(KEY_ZERO); } final int oneLength = 10 + random.nextInt(20); for (int k = 0; k < oneLength; k++) { intPool.addObject(KEY_ONE); } final int twoLength = 10 + random.nextInt(20); for (int k = 0; k < twoLength; k++) { intPool.addObject(KEY_TWO); } // Choose a random number of evictor runs final int runs = 10 + random.nextInt(50); for (int k = 0; k < runs; k++) { intPool.evict(); } // Total instances in pool final int totalInstances = zeroLength + oneLength + twoLength; // Number of times evictor should have cycled through pools final int cycleCount = runs * intPool.getNumTestsPerEvictionRun() / totalInstances; // Look at elements and make sure they are visited cycleCount // or cycleCount + 1 times VisitTracker<Integer> tracker = null; int visitCount = 0; for (int k = 0; k < zeroLength; k++) { tracker = intPool.borrowObject(KEY_ZERO); visitCount = tracker.getValidateCount(); if (visitCount < cycleCount || visitCount > cycleCount + 1) { fail(formatSettings("ZERO", "runs", runs, "lifo", lifo, "i", i, "j", j, "k", k, "visitCount", visitCount, "cycleCount", cycleCount, "totalInstances", totalInstances, zeroLength, oneLength, twoLength)); } } for (int k = 0; k < oneLength; k++) { tracker = intPool.borrowObject(KEY_ONE); visitCount = tracker.getValidateCount(); if (visitCount < cycleCount || visitCount > cycleCount + 1) { fail(formatSettings("ONE", "runs", runs, "lifo", lifo, "i", i, "j", j, "k", k, "visitCount", visitCount, "cycleCount", cycleCount, "totalInstances", totalInstances, zeroLength, oneLength, twoLength)); } } final int[] visits = new int[twoLength]; for (int k = 0; k < twoLength; k++) { tracker = intPool.borrowObject(KEY_TWO); visitCount = tracker.getValidateCount(); visits[k] = visitCount; if (visitCount < cycleCount || visitCount > cycleCount + 1) { final StringBuilder sb = new StringBuilder("Visits:"); for (int l = 0; l <= k; l++) { sb.append(visits[l]).append(' '); } fail(formatSettings("TWO " + sb.toString(), "runs", runs, "lifo", lifo, "i", i, "j", j, "k", k, "visitCount", visitCount, "cycleCount", cycleCount, "totalInstances", totalInstances, zeroLength, oneLength, twoLength)); } } } } } } private String formatSettings(final String title, final String s, final int i, final String s0, final boolean b0, final String s1, final int i1, final String s2, final int i2, final String s3, final int i3, final String s4, final int i4, final String s5, final int i5, final String s6, final int i6, final int zeroLength, final int oneLength, final int twoLength){ final StringBuilder sb = new StringBuilder(80); sb.append(title).append(' '); sb.append(s).append('=').append(i).append(' '); sb.append(s0).append('=').append(b0).append(' '); sb.append(s1).append('=').append(i1).append(' '); sb.append(s2).append('=').append(i2).append(' '); sb.append(s3).append('=').append(i3).append(' '); sb.append(s4).append('=').append(i4).append(' '); sb.append(s5).append('=').append(i5).append(' '); sb.append(s6).append('=').append(i6).append(' '); sb.append("Lengths=").append(zeroLength).append(',').append(oneLength).append(',').append(twoLength).append(' '); return sb.toString(); } @Override protected Object getNthObject(final Object key, final int n) { return String.valueOf(key) + String.valueOf(n); } @Override protected boolean isFifo() { return false; } @Override protected boolean isLifo() { return true; } @SuppressWarnings("unchecked") @Override protected <E extends Exception> KeyedObjectPool<Object, Object, E> makeEmptyPool(final int minCapacity) { final KeyedPooledObjectFactory<Object, Object, RuntimeException> perKeyFactory = new SimplePerKeyFactory(); final GenericKeyedObjectPool<Object, Object, RuntimeException> perKeyPool = new GenericKeyedObjectPool<>(perKeyFactory); perKeyPool.setMaxTotalPerKey(minCapacity); perKeyPool.setMaxIdlePerKey(minCapacity); return (KeyedObjectPool<Object, Object, E>) perKeyPool; } @Override protected <E extends Exception> KeyedObjectPool<Object, Object, E> makeEmptyPool(final KeyedPooledObjectFactory<Object, Object, E> fac) { return new GenericKeyedObjectPool<>(fac); } @Override protected Object makeKey(final int n) { return String.valueOf(n); } /** * Kicks off {@code numThreads} test threads, each of which will go * through {@code iterations} borrow-return cycles with random delay * times &lt;= delay in between. * * @param <T> Type of object in pool * @param numThreads Number of test threads * @param iterations Number of iterations for each thread * @param delay Maximum delay between iterations * @param gkopPool The keyed object pool to use */ public <T, E extends Exception> void runTestThreads(final int numThreads, final int iterations, final int delay, final GenericKeyedObjectPool<String, T, E> gkopPool) { final ArrayList<TestThread<T, E>> threads = new ArrayList<>(); for (int i = 0; i < numThreads; i++) { final TestThread<T, E> testThread = new TestThread<>(gkopPool, iterations, delay); threads.add(testThread); final Thread t = new Thread(testThread); t.start(); } for (final TestThread<T, E> testThread : threads) { while (!testThread.complete()) { Waiter.sleepQuietly(500L); } if (testThread.failed()) { fail("Thread failed: " + threads.indexOf(testThread) + "\n" + ExceptionUtils.getStackTrace(testThread.exception)); } } } @BeforeEach public void setUp() { simpleFactory = new SimpleFactory<>(); gkoPool = new GenericKeyedObjectPool<>(simpleFactory); } @AfterEach public void tearDownJmx() throws Exception { super.tearDown(); final ObjectName jmxName = gkoPool.getJmxName(); final String poolName = Objects.toString(jmxName, null); gkoPool.clear(); gkoPool.close(); gkoPool = null; simpleFactory = null; final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); final Set<ObjectName> result = mbs.queryNames(new ObjectName( "org.apache.commoms.pool3:type=GenericKeyedObjectPool,*"), null); // There should be no registered pools at this point final int registeredPoolCount = result.size(); final StringBuilder msg = new StringBuilder("Current pool is: "); msg.append(poolName); msg.append(" Still open pools are: "); for (final ObjectName name : result) { // Clean these up ready for the next test msg.append(name.toString()); msg.append(" created via\n"); msg.append(mbs.getAttribute(name, "CreationStackTrace")); msg.append('\n'); mbs.unregisterMBean(name); } assertEquals( 0, registeredPoolCount, msg.toString()); } @Test public void testAppendStats() { assertFalse(gkoPool.getMessageStatistics()); assertEquals("foo", gkoPool.appendStats("foo")); try (final GenericKeyedObjectPool<?, ?, TestException> pool = new GenericKeyedObjectPool<>(new SimpleFactory<>())) { pool.setMessagesStatistics(true); assertNotEquals("foo", pool.appendStats("foo")); pool.setMessagesStatistics(false); assertEquals("foo", pool.appendStats("foo")); } } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testBlockedKeyDoesNotBlockPool() throws Exception { gkoPool.setBlockWhenExhausted(true); gkoPool.setMaxWait(Duration.ofMillis(5000)); gkoPool.setMaxTotalPerKey(1); gkoPool.setMaxTotal(-1); gkoPool.borrowObject("one"); final long startMillis = System.currentTimeMillis(); // Needs to be in a separate thread as this will block final Runnable simple = new SimpleTestThread<>(gkoPool, "one"); new Thread(simple).start(); // This should be almost instant. If it isn't it means this thread got // stuck behind the thread created above which is bad. // Give other thread a chance to start Thread.sleep(1000); gkoPool.borrowObject("two"); final long endMillis = System.currentTimeMillis(); // If it fails it will be more than 4000ms (5000 less the 1000 sleep) // If it passes it should be almost instant // Use 3000ms as the threshold - should avoid timing issues on most // (all? platforms) assertTrue(endMillis - startMillis < 4000, "Elapsed time: " + (endMillis - startMillis) + " should be less than 4000"); } /* * Note: This test relies on timing for correct execution. There *should* be * enough margin for this to work correctly on most (all?) systems but be * aware of this if you see a failure of this test. */ @SuppressWarnings("rawtypes") @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testBorrowObjectFairness() throws Exception { final int numThreads = 40; final int maxTotal = 40; final GenericKeyedObjectPoolConfig<String> config = new GenericKeyedObjectPoolConfig<>(); config.setMaxTotalPerKey(maxTotal); config.setFairness(true); config.setLifo(false); config.setMaxIdlePerKey(maxTotal); gkoPool = new GenericKeyedObjectPool<>(simpleFactory, config); // Exhaust the pool final String[] objects = new String[maxTotal]; for (int i = 0; i < maxTotal; i++) { objects[i] = gkoPool.borrowObject("0"); } // Start and park threads waiting to borrow objects final TestThread[] threads = new TestThread[numThreads]; for (int i = 0; i < numThreads; i++) { threads[i] = new TestThread<>(gkoPool, 1, 0, 2000, false, "0" + String.valueOf(i % maxTotal), "0"); final Thread t = new Thread(threads[i]); t.start(); // Short delay to ensure threads start in correct order Thread.sleep(10); } // Return objects, other threads should get served in order for (int i = 0; i < maxTotal; i++) { gkoPool.returnObject("0", objects[i]); } // Wait for threads to finish for (int i = 0; i < numThreads; i++) { while (!threads[i].complete()) { Waiter.sleepQuietly(500L); } if (threads[i].failed()) { fail("Thread " + i + " failed: " + ExceptionUtils.getStackTrace(threads[i].exception)); } } } /** * POOL-192 * Verify that clear(key) does not leak capacity. * * @throws Exception May occur in some failure modes */ @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testClear() throws Exception { gkoPool.setMaxTotal(2); gkoPool.setMaxTotalPerKey(2); gkoPool.setBlockWhenExhausted(false); gkoPool.addObject("one"); gkoPool.addObject("one"); assertEquals(2, gkoPool.getNumIdle()); gkoPool.clear("one"); assertEquals(0, gkoPool.getNumIdle()); assertEquals(0, gkoPool.getNumIdle("one")); final String obj1 = gkoPool.borrowObject("one"); final String obj2 = gkoPool.borrowObject("one"); gkoPool.returnObject("one", obj1); gkoPool.returnObject("one", obj2); gkoPool.clear(); assertEquals(0, gkoPool.getNumIdle()); assertEquals(0, gkoPool.getNumIdle("one")); gkoPool.borrowObject("one"); gkoPool.borrowObject("one"); gkoPool.close(); } /** * Test to make sure that clearOldest does not destroy instances that have been checked out. * * @throws Exception May occur in some failure modes */ @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testClearOldest() throws Exception { // Make destroy have some latency so clearOldest takes some time final WaiterFactory<String> waiterFactory = new WaiterFactory<>(0, 20, 0, 0, 0, 0, 50, 5, 0); try (final GenericKeyedObjectPool<String, Waiter, RuntimeException> waiterPool = new GenericKeyedObjectPool<>(waiterFactory)) { waiterPool.setMaxTotalPerKey(5); waiterPool.setMaxTotal(50); waiterPool.setLifo(false); // Load the pool with idle instances - 5 each for 10 keys for (int i = 0; i < 10; i++) { final String key = Integer.toString(i); for (int j = 0; j < 5; j++) { waiterPool.addObject(key); } // Make sure order is maintained Thread.sleep(20); } // Now set up a race - one thread wants a new instance, triggering clearOldest // Other goes after an element on death row // See if we end up with dead man walking final SimpleTestThread<Waiter, RuntimeException> t2 = new SimpleTestThread<>(waiterPool, "51"); final Thread thread2 = new Thread(t2); thread2.start(); // Triggers clearOldest, killing all of the 0's and the 2 oldest 1's Thread.sleep(50); // Wait for clearOldest to kick off, but not long enough to reach the 1's final Waiter waiter = waiterPool.borrowObject("1"); Thread.sleep(200); // Wait for execution to happen waiterPool.returnObject("1", waiter); // Will throw IllegalStateException if dead } } /** * POOL-391 Verify that when clear(key) is called with reuseCapacity true, * capacity freed is reused and allocated to most loaded pools. * * @throws Exception May occur in some failure modes */ @Test public void testClearReuseCapacity() throws Exception { gkoPool.setMaxTotalPerKey(6); gkoPool.setMaxTotal(6); gkoPool.setMaxWait(Duration.ofSeconds(5)); // Create one thread to wait on "one", two on "two", three on "three" final ArrayList<Thread> testThreads = new ArrayList<>(); testThreads.add(new Thread(new SimpleTestThread<>(gkoPool, "one"))); testThreads.add(new Thread(new SimpleTestThread<>(gkoPool, "two"))); testThreads.add(new Thread(new SimpleTestThread<>(gkoPool, "two"))); testThreads.add(new Thread(new SimpleTestThread<>(gkoPool, "three"))); testThreads.add(new Thread(new SimpleTestThread<>(gkoPool, "three"))); testThreads.add(new Thread(new SimpleTestThread<>(gkoPool, "three"))); // Borrow two each from "four", "five", "six" - using all capacity final String four = gkoPool.borrowObject("four"); final String four2 = gkoPool.borrowObject("four"); final String five = gkoPool.borrowObject("five"); final String five2 = gkoPool.borrowObject("five"); final String six = gkoPool.borrowObject("six"); final String six2 = gkoPool.borrowObject("six"); Thread.sleep(100); // Launch the waiters - all will be blocked waiting for (final Thread t : testThreads) { t.start(); } Thread.sleep(100); // Return and clear the fours - at least one "three" should get served // Other should be a two or a three (three was most loaded) gkoPool.returnObject("four", four); gkoPool.returnObject("four", four2); gkoPool.clear("four"); Thread.sleep(20); assertTrue(!testThreads.get(3).isAlive() || !testThreads.get(4).isAlive() || !testThreads.get(5).isAlive()); // Now clear the fives gkoPool.returnObject("five", five); gkoPool.returnObject("five", five2); gkoPool.clear("five"); Thread.sleep(20); // Clear the sixes gkoPool.returnObject("six", six); gkoPool.returnObject("six", six2); gkoPool.clear("six"); Thread.sleep(20); for (final Thread t : testThreads) { assertFalse(t.isAlive()); } } /** * POOL-391 Adapted from code in the JIRA ticket. */ @Test @Timeout(value = 10000, unit = TimeUnit.MILLISECONDS) public void testClearUnblocksWaiters() throws Exception { final GenericKeyedObjectPoolConfig<Integer> config = new GenericKeyedObjectPoolConfig<>(); config.setMaxTotalPerKey(1); config.setMaxTotal(1); config.setMaxWait(Duration.ofMillis(500)); final GenericKeyedObjectPool<Integer, Integer, InterruptedException> testPool = new GenericKeyedObjectPool<>( new KeyedPooledObjectFactory<Integer, Integer, InterruptedException>() { @Override public void activateObject(final Integer key, final PooledObject<Integer> p) { // do nothing } @Override public void destroyObject(final Integer key, final PooledObject<Integer> p) throws InterruptedException { Thread.sleep(10); } @Override public PooledObject<Integer> makeObject(final Integer key) { return new DefaultPooledObject<>(10); } @Override public void passivateObject(final Integer key, final PooledObject<Integer> p) { // do nothing } @Override public boolean validateObject(final Integer key, final PooledObject<Integer> p) { return true; } }, config); final Integer borrowKey = 10; final int iterations = 100; final ExecutorService executor = Executors.newFixedThreadPool(2); final Thread t = new Thread(() -> { try { for (int i = 0; i < iterations; i++) { final Integer integer = testPool.borrowObject(borrowKey); testPool.returnObject(borrowKey, integer); Thread.sleep(10); } } catch (final Exception e) { fail(e); } }); final Thread t2 = new Thread(() -> { try { for (int i = 0; i < iterations; i++) { testPool.clear(borrowKey); Thread.sleep(10); } } catch (final Exception e) { fail(e); } }); final Future<?> f1 = executor.submit(t); final Future<?> f2 = executor.submit(t2); f2.get(); f1.get(); } // POOL-259 @Test public void testClientWaitStats() throws TestException { final SimpleFactory<String> factory = new SimpleFactory<>(); // Give makeObject a little latency factory.setMakeLatency(200); try (final GenericKeyedObjectPool<String, String, TestException> pool = new GenericKeyedObjectPool<>(factory, new GenericKeyedObjectPoolConfig<>())) { final String s = pool.borrowObject("one"); // First borrow waits on create, so wait time should be at least 200 ms // Allow 100ms error in clock times assertTrue(pool.getMaxBorrowWaitTimeMillis() >= 100); assertTrue(pool.getMeanBorrowWaitTimeMillis() >= 100); pool.returnObject("one", s); pool.borrowObject("one"); // Second borrow does not have to wait on create, average should be about 100 assertTrue(pool.getMaxBorrowWaitTimeMillis() > 100); assertTrue(pool.getMeanBorrowWaitTimeMillis() < 200); assertTrue(pool.getMeanBorrowWaitTimeMillis() > 20); } } /** * Tests POOL-411, or least tries to reproduce the NPE, but does not. * * @throws TestException a test failure. */ @Test public void testConcurrentBorrowAndClear() throws TestException { final int threadCount = 64; final int taskCount = 64; final int addCount = 1; final int borrowCycles = 1024; final int clearCycles = 1024; final boolean useYield = true; testConcurrentBorrowAndClear(threadCount, taskCount, addCount, borrowCycles, clearCycles, useYield); } /** * Tests POOL-411, or least tries to reproduce the NPE, but does not. * * @throws TestException a test failure. */ private void testConcurrentBorrowAndClear(final int threadCount, final int taskCount, final int addCount, final int borrowCycles, final int clearCycles, final boolean useYield) throws TestException { final GenericKeyedObjectPoolConfig<String> config = new GenericKeyedObjectPoolConfig<>(); final int maxTotalPerKey = borrowCycles + 1; config.setMaxTotalPerKey(threadCount); config.setMaxIdlePerKey(threadCount); config.setMaxTotal(maxTotalPerKey * threadCount); config.setBlockWhenExhausted(false); // pool exhausted indicates a bug in the test gkoPool = new GenericKeyedObjectPool<>(simpleFactory, config); final String key = "0"; gkoPool.addObjects(Arrays.asList(key), threadCount); // all objects in the pool are now idle. final ExecutorService threadPool = Executors.newFixedThreadPool(threadCount); final List<Future<?>> futures = new ArrayList<>(); try { for (int t = 0; t < taskCount; t++) { futures.add(threadPool.submit(() -> { for (int i = 0; i < clearCycles; i++) { if (useYield) { Thread.yield(); } gkoPool.clear(key, true); try { gkoPool.addObjects(Arrays.asList(key), addCount); } catch (IllegalArgumentException | TestException e) { fail(e); } } })); futures.add(threadPool.submit(() -> { try { for (int i = 0; i < borrowCycles; i++) { if (useYield) { Thread.yield(); } final String pooled = gkoPool.borrowObject(key); gkoPool.returnObject(key, pooled); } } catch (TestException e) { fail(e); } })); } futures.forEach(f -> { try { f.get(); } catch (InterruptedException | ExecutionException e) { fail(e); } }); } finally { threadPool.shutdownNow(); } } /** * See https://issues.apache.org/jira/browse/POOL-411?focusedCommentId=17741156&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#comment-17741156 * * @throws TestException a test failure. */ @Test public void testConcurrentBorrowAndClear_JiraComment17741156() throws TestException { final int threadCount = 2; final int taskCount = 2; final int addCount = 1; final int borrowCycles = 5_000; final int clearCycles = 5_000; final boolean useYield = false; testConcurrentBorrowAndClear(threadCount, taskCount, addCount, borrowCycles, clearCycles, useYield); } /** * POOL-231 - verify that concurrent invalidates of the same object do not * corrupt pool destroyCount. * * @throws Exception May occur in some failure modes */ @Test public void testConcurrentInvalidate() throws Exception { // Get allObjects and idleObjects loaded with some instances final int nObjects = 1000; final String key = "one"; gkoPool.setMaxTotal(nObjects); gkoPool.setMaxTotalPerKey(nObjects); gkoPool.setMaxIdlePerKey(nObjects); final String [] obj = new String[nObjects]; for (int i = 0; i < nObjects; i++) { obj[i] = gkoPool.borrowObject(key); } for (int i = 0; i < nObjects; i++) { if (i % 2 == 0) { gkoPool.returnObject(key, obj[i]); } } final int nThreads = 20; final int nIterations = 60; final InvalidateThread[] threads = new InvalidateThread[nThreads]; // Randomly generated list of distinct invalidation targets final ArrayList<Integer> targets = new ArrayList<>(); final Random random = new Random(); for (int j = 0; j < nIterations; j++) { // Get a random invalidation target Integer targ = Integer.valueOf(random.nextInt(nObjects)); while (targets.contains(targ)) { targ = Integer.valueOf(random.nextInt(nObjects)); } targets.add(targ); // Launch nThreads threads all trying to invalidate the target for (int i = 0; i < nThreads; i++) { threads[i] = new InvalidateThread(gkoPool, key, obj[targ.intValue()]); } for (int i = 0; i < nThreads; i++) { new Thread(threads[i]).start(); } boolean done = false; while (!done) { done = true; for (int i = 0; i < nThreads; i++) { done = done && threads[i].complete(); } Thread.sleep(100); } } assertEquals(nIterations, gkoPool.getDestroyedCount()); } @Test public void testConstructorNullFactory() { // add dummy assert (won't be invoked because of IAE) to avoid "unused" warning assertThrows(IllegalArgumentException.class, () -> new GenericKeyedObjectPool<>(null)); } @SuppressWarnings("deprecation") @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testConstructors() { // Make constructor arguments all different from defaults final int maxTotalPerKey = 1; final int minIdle = 2; final Duration maxWaitDuration = Duration.ofMillis(3); final long maxWaitMillis = maxWaitDuration.toMillis(); final int maxIdle = 4; final int maxTotal = 5; final long minEvictableIdleTimeMillis = 6; final int numTestsPerEvictionRun = 7; final boolean testOnBorrow = true; final boolean testOnReturn = true; final boolean testWhileIdle = true; final long timeBetweenEvictionRunsMillis = 8; final boolean blockWhenExhausted = false; final boolean lifo = false; final KeyedPooledObjectFactory<Object, Object, RuntimeException> dummyFactory = new DummyFactory(); try (GenericKeyedObjectPool<Object, Object, RuntimeException> objPool = new GenericKeyedObjectPool<>(dummyFactory)) { assertEquals(GenericKeyedObjectPoolConfig.DEFAULT_MAX_TOTAL_PER_KEY, objPool.getMaxTotalPerKey()); assertEquals(GenericKeyedObjectPoolConfig.DEFAULT_MAX_IDLE_PER_KEY, objPool.getMaxIdlePerKey()); assertEquals(BaseObjectPoolConfig.DEFAULT_MAX_WAIT, objPool.getMaxWaitDuration()); assertEquals(GenericKeyedObjectPoolConfig.DEFAULT_MIN_IDLE_PER_KEY, objPool.getMinIdlePerKey()); assertEquals(GenericKeyedObjectPoolConfig.DEFAULT_MAX_TOTAL, objPool.getMaxTotal()); // assertEquals(BaseObjectPoolConfig.DEFAULT_MIN_EVICTABLE_IDLE_DURATION, objPool.getMinEvictableIdleDuration()); // assertEquals(BaseObjectPoolConfig.DEFAULT_NUM_TESTS_PER_EVICTION_RUN, objPool.getNumTestsPerEvictionRun()); assertEquals(Boolean.valueOf(BaseObjectPoolConfig.DEFAULT_TEST_ON_BORROW), Boolean.valueOf(objPool.getTestOnBorrow())); assertEquals(Boolean.valueOf(BaseObjectPoolConfig.DEFAULT_TEST_ON_RETURN), Boolean.valueOf(objPool.getTestOnReturn())); assertEquals(Boolean.valueOf(BaseObjectPoolConfig.DEFAULT_TEST_WHILE_IDLE), Boolean.valueOf(objPool.getTestWhileIdle())); // assertEquals(BaseObjectPoolConfig.DEFAULT_DURATION_BETWEEN_EVICTION_RUNS, objPool.getDurationBetweenEvictionRuns()); // assertEquals(Boolean.valueOf(BaseObjectPoolConfig.DEFAULT_BLOCK_WHEN_EXHAUSTED), Boolean.valueOf(objPool.getBlockWhenExhausted())); assertEquals(Boolean.valueOf(BaseObjectPoolConfig.DEFAULT_LIFO), Boolean.valueOf(objPool.getLifo())); } final GenericKeyedObjectPoolConfig<Object> config = new GenericKeyedObjectPoolConfig<>(); config.setLifo(lifo); config.setMaxTotalPerKey(maxTotalPerKey); config.setMaxIdlePerKey(maxIdle); config.setMinIdlePerKey(minIdle); config.setMaxTotal(maxTotal); config.setMaxWait(maxWaitDuration); config.setMinEvictableIdleDuration(Duration.ofMillis(minEvictableIdleTimeMillis)); config.setNumTestsPerEvictionRun(numTestsPerEvictionRun); config.setTestOnBorrow(testOnBorrow); config.setTestOnReturn(testOnReturn); config.setTestWhileIdle(testWhileIdle); config.setDurationBetweenEvictionRuns(Duration.ofMillis(timeBetweenEvictionRunsMillis)); config.setBlockWhenExhausted(blockWhenExhausted); try (GenericKeyedObjectPool<Object, Object, RuntimeException> objPool = new GenericKeyedObjectPool<>(dummyFactory, config)) { assertEquals(maxTotalPerKey, objPool.getMaxTotalPerKey()); assertEquals(maxIdle, objPool.getMaxIdlePerKey()); assertEquals(maxWaitDuration, objPool.getMaxWaitDuration()); assertEquals(minIdle, objPool.getMinIdlePerKey()); assertEquals(maxTotal, objPool.getMaxTotal()); assertEquals(minEvictableIdleTimeMillis, objPool.getMinEvictableIdleDuration().toMillis()); assertEquals(numTestsPerEvictionRun, objPool.getNumTestsPerEvictionRun()); assertEquals(Boolean.valueOf(testOnBorrow), Boolean.valueOf(objPool.getTestOnBorrow())); assertEquals(Boolean.valueOf(testOnReturn), Boolean.valueOf(objPool.getTestOnReturn())); assertEquals(Boolean.valueOf(testWhileIdle), Boolean.valueOf(objPool.getTestWhileIdle())); assertEquals(timeBetweenEvictionRunsMillis, objPool.getDurationBetweenEvictionRuns().toMillis()); assertEquals(Boolean.valueOf(blockWhenExhausted), Boolean.valueOf(objPool.getBlockWhenExhausted())); assertEquals(Boolean.valueOf(lifo), Boolean.valueOf(objPool.getLifo())); } } /** * JIRA: POOL-270 - make sure constructor correctly sets run * frequency of evictor timer. */ @Test public void testContructorEvictionConfig() throws TestException { final GenericKeyedObjectPoolConfig<String> config = new GenericKeyedObjectPoolConfig<>(); config.setDurationBetweenEvictionRuns(Duration.ofMillis(500)); config.setMinEvictableIdleDuration(Duration.ofMillis(50)); config.setNumTestsPerEvictionRun(5); try (final GenericKeyedObjectPool<String, String, TestException> p = new GenericKeyedObjectPool<>(simpleFactory, config)) { for (int i = 0; i < 5; i++) { p.addObject("one"); } Waiter.sleepQuietly(100); assertEquals(5, p.getNumIdle("one")); Waiter.sleepQuietly(500); assertEquals(0, p.getNumIdle("one")); } } /** * Verifies that when a factory's makeObject produces instances that are not * discernible by equals, the pool can handle them. * * JIRA: POOL-283 */ @Test public void testEqualsIndiscernible() throws Exception { final HashSetFactory factory = new HashSetFactory(); try (final GenericKeyedObjectPool<String, HashSet<String>, RuntimeException> pool = new GenericKeyedObjectPool<>(factory, new GenericKeyedObjectPoolConfig<>())) { final HashSet<String> s1 = pool.borrowObject("a"); final HashSet<String> s2 = pool.borrowObject("a"); pool.returnObject("a", s1); pool.returnObject("a", s2); } } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testEviction() throws Exception { gkoPool.setMaxIdlePerKey(500); gkoPool.setMaxTotalPerKey(500); gkoPool.setNumTestsPerEvictionRun(100); gkoPool.setMinEvictableIdleDuration(Duration.ofMillis(250)); gkoPool.setDurationBetweenEvictionRuns(Duration.ofMillis(500)); final String[] active = new String[500]; for(int i=0;i<500;i++) { active[i] = gkoPool.borrowObject(""); } for(int i=0;i<500;i++) { gkoPool.returnObject("",active[i]); } Waiter.sleepQuietly(1000L); assertTrue(gkoPool.getNumIdle("") < 500, "Should be less than 500 idle, found " + gkoPool.getNumIdle("")); Waiter.sleepQuietly(600L); assertTrue(gkoPool.getNumIdle("") < 400, "Should be less than 400 idle, found " + gkoPool.getNumIdle("")); Waiter.sleepQuietly(600L); assertTrue(gkoPool.getNumIdle("") < 300,"Should be less than 300 idle, found " + gkoPool.getNumIdle("")); Waiter.sleepQuietly(600L); assertTrue(gkoPool.getNumIdle("") < 200, "Should be less than 200 idle, found " + gkoPool.getNumIdle("")); Waiter.sleepQuietly(600L); assertTrue(gkoPool.getNumIdle("") < 100 , "Should be less than 100 idle, found " + gkoPool.getNumIdle("")); Waiter.sleepQuietly(600L); assertEquals(0,gkoPool.getNumIdle(""),"Should be zero idle, found " + gkoPool.getNumIdle("")); for(int i=0;i<500;i++) { active[i] = gkoPool.borrowObject(""); } for(int i=0;i<500;i++) { gkoPool.returnObject("",active[i]); } Waiter.sleepQuietly(1000L); assertTrue(gkoPool.getNumIdle("") < 500,"Should be less than 500 idle, found " + gkoPool.getNumIdle("")); Waiter.sleepQuietly(600L); assertTrue(gkoPool.getNumIdle("") < 400,"Should be less than 400 idle, found " + gkoPool.getNumIdle("")); Waiter.sleepQuietly(600L); assertTrue(gkoPool.getNumIdle("") < 300,"Should be less than 300 idle, found " + gkoPool.getNumIdle("")); Waiter.sleepQuietly(600L); assertTrue(gkoPool.getNumIdle("") < 200,"Should be less than 200 idle, found " + gkoPool.getNumIdle("")); Waiter.sleepQuietly(600L); assertTrue(gkoPool.getNumIdle("") < 100,"Should be less than 100 idle, found " + gkoPool.getNumIdle("")); Waiter.sleepQuietly(600L); assertEquals(0,gkoPool.getNumIdle(""),"Should be zero idle, found " + gkoPool.getNumIdle("")); } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testEviction2() throws Exception { gkoPool.setMaxIdlePerKey(500); gkoPool.setMaxTotalPerKey(500); gkoPool.setNumTestsPerEvictionRun(100); gkoPool.setMinEvictableIdleDuration(Duration.ofMillis(500)); gkoPool.setDurationBetweenEvictionRuns(Duration.ofMillis(500)); final String[] active = new String[500]; final String[] active2 = new String[500]; for (int i = 0; i < 500; i++) { active[i] = gkoPool.borrowObject(""); active2[i] = gkoPool.borrowObject("2"); } for (int i = 0; i < 500; i++) { gkoPool.returnObject("", active[i]); gkoPool.returnObject("2", active2[i]); } Waiter.sleepQuietly(1100L); assertTrue(gkoPool.getNumIdle() < 1000, "Should be less than 1000 idle, found " + gkoPool.getNumIdle()); final long sleepMillisPart2 = 600L; Waiter.sleepQuietly(sleepMillisPart2); assertTrue(gkoPool.getNumIdle() < 900, "Should be less than 900 idle, found " + gkoPool.getNumIdle()); Waiter.sleepQuietly(sleepMillisPart2); assertTrue(gkoPool.getNumIdle() < 800, "Should be less than 800 idle, found " + gkoPool.getNumIdle()); Waiter.sleepQuietly(sleepMillisPart2); assertTrue(gkoPool.getNumIdle() < 700, "Should be less than 700 idle, found " + gkoPool.getNumIdle()); Waiter.sleepQuietly(sleepMillisPart2); assertTrue(gkoPool.getNumIdle() < 600, "Should be less than 600 idle, found " + gkoPool.getNumIdle()); Waiter.sleepQuietly(sleepMillisPart2); assertTrue(gkoPool.getNumIdle() < 500, "Should be less than 500 idle, found " + gkoPool.getNumIdle()); Waiter.sleepQuietly(sleepMillisPart2); assertTrue(gkoPool.getNumIdle() < 400, "Should be less than 400 idle, found " + gkoPool.getNumIdle()); Waiter.sleepQuietly(sleepMillisPart2); assertTrue(gkoPool.getNumIdle() < 300, "Should be less than 300 idle, found " + gkoPool.getNumIdle()); Waiter.sleepQuietly(sleepMillisPart2); assertTrue(gkoPool.getNumIdle() < 200, "Should be less than 200 idle, found " + gkoPool.getNumIdle()); Waiter.sleepQuietly(sleepMillisPart2); assertTrue(gkoPool.getNumIdle() < 100, "Should be less than 100 idle, found " + gkoPool.getNumIdle()); Waiter.sleepQuietly(sleepMillisPart2); assertEquals(0, gkoPool.getNumIdle(), "Should be zero idle, found " + gkoPool.getNumIdle()); } /** * Test to make sure evictor visits least recently used objects first, * regardless of FIFO/LIFO * * JIRA: POOL-86 * * @throws Exception May occur in some failure modes */ @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testEvictionOrder() throws Exception { checkEvictionOrder(false); checkEvictionOrder(true); } // POOL-326 @Test public void testEvictorClearOldestRace() throws Exception { gkoPool.setMinEvictableIdleDuration(Duration.ofMillis(100)); gkoPool.setNumTestsPerEvictionRun(1); // Introduce latency between when evictor starts looking at an instance and when // it decides to destroy it gkoPool.setEvictionPolicy(new SlowEvictionPolicy<>(1000)); // Borrow an instance final String val = gkoPool.borrowObject("foo"); // Add another idle one gkoPool.addObject("foo"); // Sleep long enough so idle one is eligible for eviction Thread.sleep(1000); // Start evictor and race with clearOldest gkoPool.setDurationBetweenEvictionRuns(Duration.ofMillis(10)); // Wait for evictor to start Thread.sleep(100); gkoPool.clearOldest(); // Wait for slow evictor to complete Thread.sleep(1500); // See if we get NPE on return (POOL-326) gkoPool.returnObject("foo", val); } /** * Verifies that the evictor visits objects in expected order * and frequency. * * @throws Exception May occur in some failure modes */ @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testEvictorVisiting() throws Exception { checkEvictorVisiting(true); checkEvictorVisiting(false); } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testExceptionInValidationDuringEviction() throws Exception { gkoPool.setMaxIdlePerKey(1); gkoPool.setMinEvictableIdleDuration(Duration.ZERO); gkoPool.setTestWhileIdle(true); final String obj = gkoPool.borrowObject("one"); gkoPool.returnObject("one", obj); simpleFactory.setThrowExceptionOnValidate(true); assertThrows(RuntimeException.class, gkoPool::evict); assertEquals(0, gkoPool.getNumActive()); assertEquals(0, gkoPool.getNumIdle()); } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testExceptionOnActivateDuringBorrow() throws Exception { final String obj1 = gkoPool.borrowObject("one"); final String obj2 = gkoPool.borrowObject("one"); gkoPool.returnObject("one", obj1); gkoPool.returnObject("one", obj2); simpleFactory.setThrowExceptionOnActivate(true); simpleFactory.setEvenValid(false); // Activation will now throw every other time // First attempt throws, but loop continues and second succeeds final String obj = gkoPool.borrowObject("one"); assertEquals(1, gkoPool.getNumActive("one")); assertEquals(0, gkoPool.getNumIdle("one")); assertEquals(1, gkoPool.getNumActive()); assertEquals(0, gkoPool.getNumIdle()); gkoPool.returnObject("one", obj); simpleFactory.setValid(false); // Validation will now fail on activation when borrowObject returns // an idle instance, and then when attempting to create a new instance assertThrows(NoSuchElementException.class, () -> gkoPool.borrowObject("one")); assertEquals(0, gkoPool.getNumActive("one")); assertEquals(0, gkoPool.getNumIdle("one")); assertEquals(0, gkoPool.getNumActive()); assertEquals(0, gkoPool.getNumIdle()); } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testExceptionOnDestroyDuringBorrow() throws Exception { simpleFactory.setThrowExceptionOnDestroy(true); simpleFactory.setValidationEnabled(true); gkoPool.setTestOnBorrow(true); gkoPool.borrowObject("one"); simpleFactory.setValid(false); // Make validation fail on next borrow attempt assertThrows(NoSuchElementException.class, () -> gkoPool.borrowObject("one")); assertEquals(1, gkoPool.getNumActive("one")); assertEquals(0, gkoPool.getNumIdle("one")); assertEquals(1, gkoPool.getNumActive()); assertEquals(0, gkoPool.getNumIdle()); } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testExceptionOnDestroyDuringReturn() throws Exception { simpleFactory.setThrowExceptionOnDestroy(true); simpleFactory.setValidationEnabled(true); gkoPool.setTestOnReturn(true); final String obj1 = gkoPool.borrowObject("one"); gkoPool.borrowObject("one"); simpleFactory.setValid(false); // Make validation fail gkoPool.returnObject("one", obj1); assertEquals(1, gkoPool.getNumActive("one")); assertEquals(0, gkoPool.getNumIdle("one")); assertEquals(1, gkoPool.getNumActive()); assertEquals(0, gkoPool.getNumIdle()); } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testExceptionOnPassivateDuringReturn() throws Exception { final String obj = gkoPool.borrowObject("one"); simpleFactory.setThrowExceptionOnPassivate(true); gkoPool.returnObject("one", obj); assertEquals(0,gkoPool.getNumIdle()); gkoPool.close(); } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testFIFO() throws Exception { gkoPool.setLifo(false); final String key = "key"; gkoPool.addObject(key); // "key0" gkoPool.addObject(key); // "key1" gkoPool.addObject(key); // "key2" assertEquals( "key0", gkoPool.borrowObject(key),"Oldest"); assertEquals( "key1", gkoPool.borrowObject(key),"Middle"); assertEquals( "key2", gkoPool.borrowObject(key),"Youngest"); final String s = gkoPool.borrowObject(key); assertEquals( "key3", s,"new-3"); gkoPool.returnObject(key, s); assertEquals( s, gkoPool.borrowObject(key),"returned"); assertEquals( "key4", gkoPool.borrowObject(key),"new-4"); } @Test @Timeout(value = 60, unit = TimeUnit.SECONDS) public void testGetKeys() throws Exception { gkoPool.addObject("one"); assertEquals(1, gkoPool.getKeys().size()); gkoPool.addObject("two"); assertEquals(2, gkoPool.getKeys().size()); gkoPool.clear("one"); assertEquals(1, gkoPool.getKeys().size()); assertEquals("two", gkoPool.getKeys().get(0)); gkoPool.clear(); } @Test public void testGetStatsString() { assertNotNull(gkoPool.getStatsString()); } /** * Verify that threads waiting on a depleted pool get served when a checked out object is * invalidated. * * JIRA: POOL-240 * @throws InterruptedException Custom exception * @throws Exception May occur in some failure modes */ @Test public void testInvalidateFreesCapacity() throws TestException, InterruptedException { final SimpleFactory<String> factory = new SimpleFactory<>(); try (final GenericKeyedObjectPool<String, String, TestException> pool = new GenericKeyedObjectPool<>(factory)) { pool.setMaxTotalPerKey(2); pool.setMaxWait(Duration.ofMillis(500)); // Borrow an instance and hold if for 5 seconds final WaitingTestThread<TestException> thread1 = new WaitingTestThread<>(pool, "one", 5000); thread1.start(); // Borrow another instance final String obj = pool.borrowObject("one"); // Launch another thread - will block, but fail in 500 ms final WaitingTestThread<TestException> thread2 = new WaitingTestThread<>(pool, "one", 100); thread2.start(); // Invalidate the object borrowed by this thread - should allow thread2 to create Thread.sleep(20); pool.invalidateObject("one", obj); Thread.sleep(600); // Wait for thread2 to timeout if (thread2.thrown != null) { fail(thread2.thrown.toString()); } } } @Test public void testInvalidateFreesCapacityForOtherKeys() throws Exception { gkoPool.setMaxTotal(1); gkoPool.setMaxWait(Duration.ofMillis(500)); final Thread borrower = new Thread(new SimpleTestThread<>(gkoPool, "two")); final String obj = gkoPool.borrowObject("one"); borrower.start(); // Will block Thread.sleep(100); // Make sure borrower has started gkoPool.invalidateObject("one", obj); // Should free capacity to serve the other key Thread.sleep(20); // Should have been served by now assertFalse(borrower.isAlive()); } @Test public void testInvalidateMissingKey() throws Exception { assertThrows(IllegalStateException.class, () -> gkoPool.invalidateObject("UnknownKey", "Ignored")); } @ParameterizedTest @EnumSource(DestroyMode.class) public void testInvalidateMissingKeyForDestroyMode(final DestroyMode destroyMode) throws Exception { assertThrows(IllegalStateException.class, () -> gkoPool.invalidateObject("UnknownKey", "Ignored", destroyMode)); } /** * Verify that threads blocked waiting on a depleted pool get served when a checked out instance * is invalidated. * * JIRA: POOL-240 * * @throws Exception May occur in some failure modes */ @Test public void testInvalidateWaiting() throws Exception { final GenericKeyedObjectPoolConfig<Object> config = new GenericKeyedObjectPoolConfig<>(); config.setMaxTotal(2); config.setBlockWhenExhausted(true); config.setMinIdlePerKey(0); config.setMaxWait(Duration.ofMillis(-1)); config.setNumTestsPerEvictionRun(Integer.MAX_VALUE); // always test all idle objects config.setTestOnBorrow(true); config.setTestOnReturn(false); config.setTestWhileIdle(true); config.setDurationBetweenEvictionRuns(Duration.ofMillis(-1)); try (final GenericKeyedObjectPool<Integer, Object, RuntimeException> pool = new GenericKeyedObjectPool<>(new ObjectFactory(), config)) { // Allocate both objects with this thread pool.borrowObject(Integer.valueOf(1)); // object1 final Object object2 = pool.borrowObject(Integer.valueOf(1)); // Cause a thread to block waiting for an object final ExecutorService executorService = Executors.newSingleThreadExecutor(new DaemonThreadFactory()); final Semaphore signal = new Semaphore(0); final Future<Exception> result = executorService.submit(() -> { try { signal.release(); final Object object3 = pool.borrowObject(Integer.valueOf(1)); pool.returnObject(Integer.valueOf(1), object3); signal.release(); } catch (final Exception e1) { return e1; } catch (final Throwable e2) { return new Exception(e2); } return null; }); // Wait for the thread to start assertTrue(signal.tryAcquire(5, TimeUnit.SECONDS)); // Attempt to ensure that test thread is blocked waiting for an object Thread.sleep(500); pool.invalidateObject(Integer.valueOf(1), object2); assertTrue(signal.tryAcquire(2, TimeUnit.SECONDS),"Call to invalidateObject did not unblock pool waiters."); if (result.get() != null) { throw new AssertionError(result.get()); } } } /** * Ensure the pool is registered. */ @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testJmxRegistration() { final ObjectName oname = gkoPool.getJmxName(); final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); final Set<ObjectName> result = mbs.queryNames(oname, null); assertEquals(1, result.size()); } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testLIFO() throws Exception { gkoPool.setLifo(true); final String key = "key"; gkoPool.addObject(key); // "key0" gkoPool.addObject(key); // "key1" gkoPool.addObject(key); // "key2" assertEquals( "key2", gkoPool.borrowObject(key),"Youngest"); assertEquals( "key1", gkoPool.borrowObject(key),"Middle"); assertEquals( "key0", gkoPool.borrowObject(key),"Oldest"); final String s = gkoPool.borrowObject(key); assertEquals( "key3", s,"new-3"); gkoPool.returnObject(key, s); assertEquals( s, gkoPool.borrowObject(key),"returned"); assertEquals( "key4", gkoPool.borrowObject(key),"new-4"); } /** * Verifies that threads that get parked waiting for keys not in use * when the pool is at maxTotal eventually get served. * * @throws Exception May occur in some failure modes */ @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testLivenessPerKey() throws Exception { gkoPool.setMaxIdlePerKey(3); gkoPool.setMaxTotal(3); gkoPool.setMaxTotalPerKey(3); gkoPool.setMaxWait(Duration.ofMillis(3000)); // Really a timeout for the test // Check out and briefly hold 3 "1"s final WaitingTestThread<TestException> t1 = new WaitingTestThread<>(gkoPool, "1", 100); final WaitingTestThread<TestException> t2 = new WaitingTestThread<>(gkoPool, "1", 100); final WaitingTestThread<TestException> t3 = new WaitingTestThread<>(gkoPool, "1", 100); t1.start(); t2.start(); t3.start(); // Try to get a "2" while all capacity is in use. // Thread will park waiting on empty queue. Verify it gets served. gkoPool.borrowObject("2"); } /** * Verify that factory exceptions creating objects do not corrupt per key create count. * * JIRA: POOL-243 * * @throws Exception May occur in some failure modes */ @Test public void testMakeObjectException() throws Exception { final SimpleFactory<String> factory = new SimpleFactory<>(); try (final GenericKeyedObjectPool<String, String, TestException> pool = new GenericKeyedObjectPool<>(factory)) { pool.setMaxTotalPerKey(1); pool.setBlockWhenExhausted(false); factory.exceptionOnCreate = true; assertThrows(Exception.class, () -> pool.borrowObject("One")); factory.exceptionOnCreate = false; pool.borrowObject("One"); } } /** * Test case for POOL-180. */ @Test @Timeout(value = 200000, unit = TimeUnit.MILLISECONDS) public void testMaxActivePerKeyExceeded() { final WaiterFactory<String> waiterFactory = new WaiterFactory<>(0, 20, 0, 0, 0, 0, 8, 5, 0); // TODO Fix this. Can't use local pool since runTestThreads uses the // protected pool field try (final GenericKeyedObjectPool<String, Waiter, RuntimeException> waiterPool = new GenericKeyedObjectPool<>(waiterFactory)) { waiterPool.setMaxTotalPerKey(5); waiterPool.setMaxTotal(8); waiterPool.setTestOnBorrow(true); waiterPool.setMaxIdlePerKey(5); waiterPool.setMaxWait(Duration.ofMillis(-1)); runTestThreads(20, 300, 250, waiterPool); } } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testMaxIdle() throws Exception { gkoPool.setMaxTotalPerKey(100); gkoPool.setMaxIdlePerKey(8); final String[] active = new String[100]; for(int i=0;i<100;i++) { active[i] = gkoPool.borrowObject(""); } assertEquals(100,gkoPool.getNumActive("")); assertEquals(0,gkoPool.getNumIdle("")); for(int i=0;i<100;i++) { gkoPool.returnObject("",active[i]); assertEquals(99 - i,gkoPool.getNumActive("")); assertEquals(i < 8 ? i+1 : 8,gkoPool.getNumIdle("")); } for(int i=0;i<100;i++) { active[i] = gkoPool.borrowObject("a"); } assertEquals(100,gkoPool.getNumActive("a")); assertEquals(0,gkoPool.getNumIdle("a")); for(int i=0;i<100;i++) { gkoPool.returnObject("a",active[i]); assertEquals(99 - i,gkoPool.getNumActive("a")); assertEquals(i < 8 ? i+1 : 8,gkoPool.getNumIdle("a")); } // total number of idle instances is twice maxIdle assertEquals(16, gkoPool.getNumIdle()); // Each pool is at the sup assertEquals(8, gkoPool.getNumIdle("")); assertEquals(8, gkoPool.getNumIdle("a")); } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testMaxTotal() throws Exception { gkoPool.setMaxTotalPerKey(2); gkoPool.setMaxTotal(3); gkoPool.setBlockWhenExhausted(false); final String o1 = gkoPool.borrowObject("a"); assertNotNull(o1); final String o2 = gkoPool.borrowObject("a"); assertNotNull(o2); final String o3 = gkoPool.borrowObject("b"); assertNotNull(o3); assertThrows(NoSuchElementException.class, () -> gkoPool.borrowObject("c")); assertEquals(0, gkoPool.getNumIdle()); gkoPool.returnObject("b", o3); assertEquals(1, gkoPool.getNumIdle()); assertEquals(1, gkoPool.getNumIdle("b")); final Object o4 = gkoPool.borrowObject("b"); assertNotNull(o4); assertEquals(0, gkoPool.getNumIdle()); assertEquals(0, gkoPool.getNumIdle("b")); gkoPool.setMaxTotal(4); final Object o5 = gkoPool.borrowObject("b"); assertNotNull(o5); assertEquals(2, gkoPool.getNumActive("a")); assertEquals(2, gkoPool.getNumActive("b")); assertEquals(gkoPool.getMaxTotal(), gkoPool.getNumActive("b") + gkoPool.getNumActive("b")); assertEquals(gkoPool.getNumActive(), gkoPool.getMaxTotal()); } /** * Verifies that maxTotal is not exceeded when factory destroyObject * has high latency, testOnReturn is set and there is high incidence of * validation failures. */ @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testMaxTotalInvariant() { final int maxTotal = 15; simpleFactory.setEvenValid(false); // Every other validation fails simpleFactory.setDestroyLatency(100); // Destroy takes 100 ms simpleFactory.setMaxTotalPerKey(maxTotal); // (makes - destroys) bound simpleFactory.setValidationEnabled(true); gkoPool.setMaxTotal(maxTotal); gkoPool.setMaxIdlePerKey(-1); gkoPool.setTestOnReturn(true); gkoPool.setMaxWait(Duration.ofSeconds(10)); runTestThreads(5, 10, 50, gkoPool); } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testMaxTotalLRU() throws Exception { gkoPool.setMaxTotalPerKey(2); gkoPool.setMaxTotal(3); final String o1 = gkoPool.borrowObject("a"); assertNotNull(o1); gkoPool.returnObject("a", o1); Thread.sleep(25); final String o2 = gkoPool.borrowObject("b"); assertNotNull(o2); gkoPool.returnObject("b", o2); Thread.sleep(25); final String o3 = gkoPool.borrowObject("c"); assertNotNull(o3); gkoPool.returnObject("c", o3); Thread.sleep(25); final String o4 = gkoPool.borrowObject("a"); assertNotNull(o4); gkoPool.returnObject("a", o4); Thread.sleep(25); assertSame(o1, o4); // this should cause b to be bumped out of the pool final String o5 = gkoPool.borrowObject("d"); assertNotNull(o5); gkoPool.returnObject("d", o5); Thread.sleep(25); // now re-request b, we should get a different object because it should // have been expelled from pool (was oldest because a was requested after b) final String o6 = gkoPool.borrowObject("b"); assertNotNull(o6); gkoPool.returnObject("b", o6); assertNotSame(o1, o6); assertNotSame(o2, o6); // second a is still in there final String o7 = gkoPool.borrowObject("a"); assertNotNull(o7); gkoPool.returnObject("a", o7); assertSame(o4, o7); } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testMaxTotalPerKey() throws Exception { gkoPool.setMaxTotalPerKey(3); gkoPool.setBlockWhenExhausted(false); gkoPool.borrowObject(""); gkoPool.borrowObject(""); gkoPool.borrowObject(""); assertThrows(NoSuchElementException.class, () -> gkoPool.borrowObject("")); } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testMaxTotalPerKeyZero() { gkoPool.setMaxTotalPerKey(0); gkoPool.setBlockWhenExhausted(false); assertThrows(NoSuchElementException.class, () -> gkoPool.borrowObject("a")); } /** * Verifies that if a borrow of a new key is blocked because maxTotal has * been reached, that borrow continues once another object is returned. * * JIRA: POOL-310 */ @Test public void testMaxTotalWithThreads() throws Exception { gkoPool.setMaxTotalPerKey(2); gkoPool.setMaxTotal(1); final int holdTime = 2000; final TestThread<String, TestException> testA = new TestThread<>(gkoPool, 1, 0, holdTime, false, null, "a"); final TestThread<String, TestException> testB = new TestThread<>(gkoPool, 1, 0, holdTime, false, null, "b"); final Thread threadA = new Thread(testA); final Thread threadB = new Thread(testB); threadA.start(); threadB.start(); Thread.sleep(holdTime * 2); // Both threads should be complete now. boolean threadRunning = true; int count = 0; while (threadRunning && count < 15) { threadRunning = threadA.isAlive(); threadRunning = threadB.isAlive(); Thread.sleep(200); count++; } assertFalse(threadA.isAlive()); assertFalse(threadB.isAlive()); assertFalse(testA.failed); assertFalse(testB.failed); } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testMaxTotalZero() { gkoPool.setMaxTotal(0); gkoPool.setBlockWhenExhausted(false); assertThrows(NoSuchElementException.class, () -> gkoPool.borrowObject("a")); } /* * Test multi-threaded pool access. * Multiple keys, multiple threads, but maxActive only allows half the threads to succeed. * * This test was prompted by Continuum build failures in the Commons DBCP test case: * TestSharedPoolDataSource.testMultipleThreads2() * Let's see if the this fails on Continuum too! */ @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testMaxWaitMultiThreaded() throws Exception { final long maxWait = 500; // wait for connection final long holdTime = 4 * maxWait; // how long to hold connection final int keyCount = 4; // number of different keys final int threadsPerKey = 5; // number of threads to grab the key initially gkoPool.setBlockWhenExhausted(true); gkoPool.setMaxWait(Duration.ofMillis(maxWait)); gkoPool.setMaxTotalPerKey(threadsPerKey); // Create enough threads so half the threads will have to wait final WaitingTestThread<TestException>[] wtt = new WaitingTestThread[keyCount * threadsPerKey * 2]; for (int i = 0; i < wtt.length; i++) { wtt[i] = new WaitingTestThread<>(gkoPool, Integer.toString(i % keyCount), holdTime); } final long originMillis = System.currentTimeMillis() - 1000; for (final WaitingTestThread<TestException> element : wtt) { element.start(); } int failed = 0; for (final WaitingTestThread<TestException> element : wtt) { element.join(); if (element.thrown != null){ failed++; } } if (DISPLAY_THREAD_DETAILS || wtt.length/2 != failed){ System.out.println( "MaxWait: " + maxWait + " HoldTime: " + holdTime + " KeyCount: " + keyCount + " MaxActive: " + threadsPerKey + " Threads: " + wtt.length + " Failed: " + failed ); for (final WaitingTestThread<TestException> wt : wtt) { System.out.println( "Preborrow: " + (wt.preBorrowMillis - originMillis) + " Postborrow: " + (wt.postBorrowMillis != 0 ? wt.postBorrowMillis - originMillis : -1) + " BorrowTime: " + (wt.postBorrowMillis != 0 ? wt.postBorrowMillis - wt.preBorrowMillis : -1) + " PostReturn: " + (wt.postReturnMillis != 0 ? wt.postReturnMillis - originMillis : -1) + " Ended: " + (wt.endedMillis - originMillis) + " Key: " + wt.key + " ObjId: " + wt.objectId ); } } assertEquals(wtt.length/2,failed,"Expected half the threads to fail"); } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testMinIdle() throws Exception { gkoPool.setMaxIdlePerKey(500); gkoPool.setMinIdlePerKey(5); gkoPool.setMaxTotalPerKey(10); gkoPool.setNumTestsPerEvictionRun(0); gkoPool.setMinEvictableIdleDuration(Duration.ofMillis(50)); gkoPool.setDurationBetweenEvictionRuns(Duration.ofMillis(100)); gkoPool.setTestWhileIdle(true); // Generate a random key final String key = "A"; gkoPool.preparePool(key); Waiter.sleepQuietly(150L); assertEquals(5, gkoPool.getNumIdle(), "Should be 5 idle, found " + gkoPool.getNumIdle()); final String[] active = new String[5]; active[0] = gkoPool.borrowObject(key); Waiter.sleepQuietly(150L); assertEquals(5, gkoPool.getNumIdle(), "Should be 5 idle, found " + gkoPool.getNumIdle()); for (int i = 1; i < 5; i++) { active[i] = gkoPool.borrowObject(key); } Waiter.sleepQuietly(150L); assertEquals(5, gkoPool.getNumIdle(), "Should be 5 idle, found " + gkoPool.getNumIdle()); for (int i = 0; i < 5; i++) { gkoPool.returnObject(key, active[i]); } Waiter.sleepQuietly(150L); assertEquals(10, gkoPool.getNumIdle(), "Should be 10 idle, found " + gkoPool.getNumIdle()); } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testMinIdleMaxTotalPerKey() throws Exception { gkoPool.setMaxIdlePerKey(500); gkoPool.setMinIdlePerKey(5); gkoPool.setMaxTotalPerKey(10); gkoPool.setNumTestsPerEvictionRun(0); gkoPool.setMinEvictableIdleDuration(Duration.ofMillis(50)); gkoPool.setDurationBetweenEvictionRuns(Duration.ofMillis(100)); gkoPool.setTestWhileIdle(true); final String key = "A"; gkoPool.preparePool(key); assertEquals(5, gkoPool.getNumIdle(), "Should be 5 idle, found " + gkoPool.getNumIdle()); Waiter.sleepQuietly(150L); assertEquals(5, gkoPool.getNumIdle(), "Should be 5 idle, found " + gkoPool.getNumIdle()); final String[] active = new String[10]; Waiter.sleepQuietly(150L); assertEquals(5, gkoPool.getNumIdle(), "Should be 5 idle, found " + gkoPool.getNumIdle()); for(int i=0 ; i<5 ; i++) { active[i] = gkoPool.borrowObject(key); } Waiter.sleepQuietly(150L); assertEquals(5, gkoPool.getNumIdle(), "Should be 5 idle, found " + gkoPool.getNumIdle()); for(int i=0 ; i<5 ; i++) { gkoPool.returnObject(key, active[i]); } Waiter.sleepQuietly(150L); assertEquals(10, gkoPool.getNumIdle(), "Should be 10 idle, found " + gkoPool.getNumIdle()); for(int i=0 ; i<10 ; i++) { active[i] = gkoPool.borrowObject(key); } Waiter.sleepQuietly(150L); assertEquals(0, gkoPool.getNumIdle(), "Should be 0 idle, found " + gkoPool.getNumIdle()); for(int i=0 ; i<10 ; i++) { gkoPool.returnObject(key, active[i]); } Waiter.sleepQuietly(150L); assertEquals(10, gkoPool.getNumIdle(), "Should be 10 idle, found " + gkoPool.getNumIdle()); } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testMinIdleNoPreparePool() throws Exception { gkoPool.setMaxIdlePerKey(500); gkoPool.setMinIdlePerKey(5); gkoPool.setMaxTotalPerKey(10); gkoPool.setNumTestsPerEvictionRun(0); gkoPool.setMinEvictableIdleDuration(Duration.ofMillis(50)); gkoPool.setDurationBetweenEvictionRuns(Duration.ofMillis(100)); gkoPool.setTestWhileIdle(true); //Generate a random key final String key = "A"; Waiter.sleepQuietly(150L); assertEquals(0, gkoPool.getNumIdle(), "Should be 0 idle, found " + gkoPool.getNumIdle()); final Object active = gkoPool.borrowObject(key); assertNotNull(active); Waiter.sleepQuietly(150L); assertEquals(5, gkoPool.getNumIdle(), "Should be 5 idle, found " + gkoPool.getNumIdle()); } /** * Verifies that returning an object twice (without borrow in between) causes ISE * but does not re-validate or re-passivate the instance. * * JIRA: POOL-285 */ @Test public void testMultipleReturn() throws Exception { final WaiterFactory<String> factory = new WaiterFactory<>(0, 0, 0, 0, 0, 0); try (final GenericKeyedObjectPool<String, Waiter, RuntimeException> pool = new GenericKeyedObjectPool<>(factory)) { pool.setTestOnReturn(true); final Waiter waiter = pool.borrowObject("a"); pool.returnObject("a", waiter); assertEquals(1, waiter.getValidationCount()); assertEquals(1, waiter.getPassivationCount()); try { pool.returnObject("a", waiter); fail("Expecting IllegalStateException from multiple return"); } catch (final IllegalStateException ex) { // Exception is expected, now check no repeat validation/passivation assertEquals(1, waiter.getValidationCount()); assertEquals(1, waiter.getPassivationCount()); } } } /** * Verifies that when a borrowed object is mutated in a way that does not * preserve equality and hash code, the pool can recognized it on return. * * JIRA: POOL-284 */ @Test public void testMutable() throws Exception { final HashSetFactory factory = new HashSetFactory(); try (final GenericKeyedObjectPool<String, HashSet<String>, RuntimeException> pool = new GenericKeyedObjectPool<>(factory, new GenericKeyedObjectPoolConfig<>())) { final HashSet<String> s1 = pool.borrowObject("a"); final HashSet<String> s2 = pool.borrowObject("a"); s1.add("One"); s2.add("One"); pool.returnObject("a", s1); pool.returnObject("a", s2); } } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testNegativeMaxTotalPerKey() throws Exception { gkoPool.setMaxTotalPerKey(-1); gkoPool.setBlockWhenExhausted(false); final String obj = gkoPool.borrowObject(""); assertEquals("0",obj); gkoPool.returnObject("",obj); } /** * Verify that when a factory returns a null object, pool methods throw NPE. */ @Test @Timeout(value = 1000, unit = TimeUnit.MILLISECONDS) public void testNPEOnFactoryNull() { // @formatter:off final DisconnectingWaiterFactory<String> factory = new DisconnectingWaiterFactory<>( () -> null, // Override default to always return null from makeObject DisconnectingWaiterFactory.DEFAULT_DISCONNECTED_LIFECYCLE_ACTION, DisconnectingWaiterFactory.DEFAULT_DISCONNECTED_VALIDATION_ACTION ); // @formatter:on try (final GenericKeyedObjectPool<String, Waiter, RuntimeException> pool = new GenericKeyedObjectPool<>(factory)) { final String key = "one"; pool.setTestOnBorrow(true); pool.setMaxTotal(-1); pool.setMinIdlePerKey(1); // Disconnect the factory - will always return null in this state factory.disconnect(); assertThrows(NullPointerException.class, () -> pool.borrowObject(key)); assertThrows(NullPointerException.class, () -> pool.addObject(key)); assertThrows(NullPointerException.class, pool::ensureMinIdle); } } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testNumActiveNumIdle2() throws Exception { assertEquals(0,gkoPool.getNumActive()); assertEquals(0,gkoPool.getNumIdle()); assertEquals(0,gkoPool.getNumActive("A")); assertEquals(0,gkoPool.getNumIdle("A")); assertEquals(0,gkoPool.getNumActive("B")); assertEquals(0,gkoPool.getNumIdle("B")); final String objA0 = gkoPool.borrowObject("A"); final String objB0 = gkoPool.borrowObject("B"); assertEquals(2,gkoPool.getNumActive()); assertEquals(0,gkoPool.getNumIdle()); assertEquals(1,gkoPool.getNumActive("A")); assertEquals(0,gkoPool.getNumIdle("A")); assertEquals(1,gkoPool.getNumActive("B")); assertEquals(0,gkoPool.getNumIdle("B")); final String objA1 = gkoPool.borrowObject("A"); final String objB1 = gkoPool.borrowObject("B"); assertEquals(4,gkoPool.getNumActive()); assertEquals(0,gkoPool.getNumIdle()); assertEquals(2,gkoPool.getNumActive("A")); assertEquals(0,gkoPool.getNumIdle("A")); assertEquals(2,gkoPool.getNumActive("B")); assertEquals(0,gkoPool.getNumIdle("B")); gkoPool.returnObject("A",objA0); gkoPool.returnObject("B",objB0); assertEquals(2,gkoPool.getNumActive()); assertEquals(2,gkoPool.getNumIdle()); assertEquals(1,gkoPool.getNumActive("A")); assertEquals(1,gkoPool.getNumIdle("A")); assertEquals(1,gkoPool.getNumActive("B")); assertEquals(1,gkoPool.getNumIdle("B")); gkoPool.returnObject("A",objA1); gkoPool.returnObject("B",objB1); assertEquals(0,gkoPool.getNumActive()); assertEquals(4,gkoPool.getNumIdle()); assertEquals(0,gkoPool.getNumActive("A")); assertEquals(2,gkoPool.getNumIdle("A")); assertEquals(0,gkoPool.getNumActive("B")); assertEquals(2,gkoPool.getNumIdle("B")); } @Test public void testReturnObjectThrowsIllegalStateException() { try (final GenericKeyedObjectPool<String, String, TestException> pool = new GenericKeyedObjectPool<>(new SimpleFactory<>())) { assertThrows(IllegalStateException.class, () -> pool.returnObject("Foo", "Bar")); } } @Test public void testReturnObjectWithBlockWhenExhausted() throws Exception { gkoPool.setBlockWhenExhausted(true); gkoPool.setMaxTotal(1); // Test return object with no take waiters final String obj = gkoPool.borrowObject("0"); gkoPool.returnObject("0", obj); // Test return object with a take waiter final TestThread<String, TestException> testA = new TestThread<>(gkoPool, 1, 0, 500, false, null, "0"); final TestThread<String, TestException> testB = new TestThread<>(gkoPool, 1, 0, 0, false, null, "1"); final Thread threadA = new Thread(testA); final Thread threadB = new Thread(testB); threadA.start(); threadB.start(); threadA.join(); threadB.join(); } @Test public void testReturnObjectWithoutBlockWhenExhausted() throws Exception { gkoPool.setBlockWhenExhausted(false); // Test return object with no take waiters final String obj = gkoPool.borrowObject("0"); gkoPool.returnObject("0", obj); } /** * JIRA: POOL-287 * * Verify that when an attempt is made to borrow an instance from the pool * while the evictor is visiting it, there is no capacity leak. * * Test creates the scenario described in POOL-287. */ @Test public void testReturnToHead() throws Exception { final SimpleFactory<String> factory = new SimpleFactory<>(); factory.setValidateLatency(100); factory.setValid(true); // Validation always succeeds try (final GenericKeyedObjectPool<String, String, TestException> pool = new GenericKeyedObjectPool<>(factory)) { pool.setMaxWait(Duration.ofMillis(1000)); pool.setTestWhileIdle(true); pool.setMaxTotalPerKey(2); pool.setNumTestsPerEvictionRun(1); pool.setDurationBetweenEvictionRuns(Duration.ofMillis(500)); // Load pool with two objects pool.addObject("one"); // call this o1 pool.addObject("one"); // call this o2 // Default is LIFO, so "one" pool is now [o2, o1] in offer order. // Evictor will visit in oldest-to-youngest order, so o1 then o2 Thread.sleep(800); // Wait for first eviction run to complete // At this point, one eviction run should have completed, visiting o1 // and eviction cursor should be pointed at o2, which is the next offered instance Thread.sleep(250); // Wait for evictor to start final String o1 = pool.borrowObject("one"); // o2 is under eviction, so this will return o1 final String o2 = pool.borrowObject("one"); // Once validation completes, o2 should be offered pool.returnObject("one", o1); pool.returnObject("one", o2); } } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testSettersAndGetters() { { gkoPool.setMaxTotalPerKey(123); assertEquals(123, gkoPool.getMaxTotalPerKey()); } { gkoPool.setMaxIdlePerKey(12); assertEquals(12, gkoPool.getMaxIdlePerKey()); } { gkoPool.setMaxWait(Duration.ofMillis(1234)); assertEquals(1234L, gkoPool.getMaxWaitDuration().toMillis()); } { gkoPool.setMinEvictableIdleDuration(Duration.ofMillis(12345)); assertEquals(12345L, gkoPool.getMinEvictableIdleDuration().toMillis()); } { gkoPool.setNumTestsPerEvictionRun(11); assertEquals(11, gkoPool.getNumTestsPerEvictionRun()); } { gkoPool.setTestOnBorrow(true); assertTrue(gkoPool.getTestOnBorrow()); gkoPool.setTestOnBorrow(false); assertFalse(gkoPool.getTestOnBorrow()); } { gkoPool.setTestOnReturn(true); assertTrue(gkoPool.getTestOnReturn()); gkoPool.setTestOnReturn(false); assertFalse(gkoPool.getTestOnReturn()); } { gkoPool.setTestWhileIdle(true); assertTrue(gkoPool.getTestWhileIdle()); gkoPool.setTestWhileIdle(false); assertFalse(gkoPool.getTestWhileIdle()); } { gkoPool.setDurationBetweenEvictionRuns(Duration.ofMillis(11235)); assertEquals(11235L, gkoPool.getDurationBetweenEvictionRuns().toMillis()); } { gkoPool.setBlockWhenExhausted(true); assertTrue(gkoPool.getBlockWhenExhausted()); gkoPool.setBlockWhenExhausted(false); assertFalse(gkoPool.getBlockWhenExhausted()); } } @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testThreaded1() { gkoPool.setMaxTotalPerKey(15); gkoPool.setMaxIdlePerKey(15); gkoPool.setMaxWait(Duration.ofMillis(1000)); runTestThreads(20, 100, 50, gkoPool); } // Pool-361 @Test public void testValidateOnCreate() throws Exception { gkoPool.setTestOnCreate(true); simpleFactory.setValidationEnabled(true); gkoPool.addObject("one"); assertEquals(1, simpleFactory.validateCounter); } @Test public void testValidateOnCreateFailure() throws Exception { gkoPool.setTestOnCreate(true); gkoPool.setTestOnBorrow(false); gkoPool.setMaxTotal(2); simpleFactory.setValidationEnabled(true); simpleFactory.setValid(false); // Make sure failed validations do not leak capacity gkoPool.addObject("one"); gkoPool.addObject("one"); assertEquals(0, gkoPool.getNumIdle()); assertEquals(0, gkoPool.getNumActive()); simpleFactory.setValid(true); final String obj = gkoPool.borrowObject("one"); assertNotNull(obj); gkoPool.addObject("one"); // Should have one idle, one out now assertEquals(1, gkoPool.getNumIdle()); assertEquals(1, gkoPool.getNumActive()); } /** * Verify that threads waiting on a depleted pool get served when a returning object fails * validation. * * JIRA: POOL-240 * * @throws Exception May occur in some failure modes */ @Test public void testValidationFailureOnReturnFreesCapacity() throws Exception { final SimpleFactory<String> factory = new SimpleFactory<>(); factory.setValid(false); // Validate will always fail factory.setValidationEnabled(true); try (final GenericKeyedObjectPool<String, String, TestException> pool = new GenericKeyedObjectPool<>(factory)) { pool.setMaxTotalPerKey(2); pool.setMaxWait(Duration.ofMillis(1500)); pool.setTestOnReturn(true); pool.setTestOnBorrow(false); // Borrow an instance and hold if for 5 seconds final WaitingTestThread<TestException> thread1 = new WaitingTestThread<>(pool, "one", 5000); thread1.start(); // Borrow another instance and return it after 500 ms (validation will fail) final WaitingTestThread<TestException> thread2 = new WaitingTestThread<>(pool, "one", 500); thread2.start(); Thread.sleep(50); // Try to borrow an object final String obj = pool.borrowObject("one"); pool.returnObject("one", obj); } } // POOL-276 @Test public void testValidationOnCreateOnly() throws Exception { simpleFactory.enableValidation = true; gkoPool.setMaxTotal(1); gkoPool.setTestOnCreate(true); gkoPool.setTestOnBorrow(false); gkoPool.setTestOnReturn(false); gkoPool.setTestWhileIdle(false); final String o1 = gkoPool.borrowObject("KEY"); assertEquals("KEY0", o1); final Timer t = new Timer(); t.schedule( new TimerTask() { @Override public void run() { gkoPool.returnObject("KEY", o1); } }, 3000); final String o2 = gkoPool.borrowObject("KEY"); assertEquals("KEY0", o2); assertEquals(1, simpleFactory.validateCounter); } /** * POOL-189 * * @throws Exception May occur in some failure modes */ @Test @Timeout(value = 60_000, unit = TimeUnit.MILLISECONDS) public void testWhenExhaustedBlockClosePool() throws Exception { gkoPool.setMaxTotalPerKey(1); gkoPool.setBlockWhenExhausted(true); gkoPool.setMaxWait(Duration.ofMillis(-1)); final String obj1 = gkoPool.borrowObject("a"); // Make sure an object was obtained assertNotNull(obj1); // Create a separate thread to try and borrow another object final WaitingTestThread<TestException> wtt = new WaitingTestThread<>(gkoPool, "a", 200); wtt.start(); // Give wtt time to start Thread.sleep(200); // close the pool (Bug POOL-189) gkoPool.close(); // Give interrupt time to take effect Thread.sleep(200); // Check thread was interrupted assertTrue(wtt.thrown instanceof InterruptedException); } }
5,205
0
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/impl/TestEvictionConfig.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.impl; import static org.junit.jupiter.api.Assertions.assertEquals; import java.time.Duration; import org.junit.jupiter.api.Test; /** * Tests for {@link EvictionConfig}. */ public class TestEvictionConfig { @Test public void testConstructor1s() { final EvictionConfig config = new EvictionConfig(Duration.ofMillis(1), Duration.ofMillis(1), 1); assertEquals(1, config.getIdleEvictDuration().toMillis()); assertEquals(1, config.getIdleSoftEvictDuration().toMillis()); assertEquals(1, config.getMinIdle()); } @Test public void testConstructorZerosDurations() { final EvictionConfig config = new EvictionConfig(Duration.ZERO, Duration.ZERO, 0); assertEquals(Long.MAX_VALUE, config.getIdleEvictDuration().toMillis()); assertEquals(Long.MAX_VALUE, config.getIdleSoftEvictDuration().toMillis()); assertEquals(0, config.getMinIdle()); } }
5,206
0
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/impl/DisconnectingWaiterFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.impl; import java.time.Duration; import java.time.Instant; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.function.Supplier; import org.apache.commons.pool3.PooledObject; import org.apache.commons.pool3.Waiter; import org.apache.commons.pool3.WaiterFactory; public class DisconnectingWaiterFactory<K> extends WaiterFactory<K> { private static final Duration DEFAULT_TIME_BETWEEN_CONNECTION_CHECKS = Duration.ofMillis(100); private static final Duration DEFAULT_MAX_WAIT = Duration.ofSeconds(10); /** * Default function to perform for activate, passivate, destroy in disconnected * mode - no-op */ protected static final Consumer<PooledObject<Waiter>> DEFAULT_DISCONNECTED_LIFECYCLE_ACTION = w -> { }; /** * Default supplier determining makeObject action when invoked in disconnected * mode. Default behavior is to block until reconnected for up to maxWait * duration. If maxWait is exceeded, throw ISE; if reconnect happens in time, * return a new DefaultPooledObject<Waiter>. */ protected static final Supplier<PooledObject<Waiter>> DEFAULT_DISCONNECTED_CREATE_ACTION = () -> { waitForConnection(null, DEFAULT_TIME_BETWEEN_CONNECTION_CHECKS, DEFAULT_MAX_WAIT); return new DefaultPooledObject<>(new Waiter(true, true, 0)); }; /** * Default predicate determining what validate does in disconnected state - * default is to always return false */ protected static final Predicate<PooledObject<Waiter>> DEFAULT_DISCONNECTED_VALIDATION_ACTION = w -> false; /** * Blocks until connected or maxWait is exceeded. * * @throws TimeoutException if maxWait is exceeded. */ private static void waitForConnection(final AtomicBoolean connected, final Duration timeBetweenConnectionChecks, final Duration maxWait) { final Instant start = Instant.now(); while (!connected.get()) { try { Thread.sleep(timeBetweenConnectionChecks.toMillis()); } catch (final InterruptedException e) { e.printStackTrace(); } if (Duration.between(start, Instant.now()).compareTo(maxWait) > 0) { throw new IllegalStateException(new TimeoutException("Timed out waiting for connection")); } } } /** * * A WaiterFactory that simulates a resource required by factory methods going * down (and coming back). * <p> * When connected, this factory behaves like a normal WaiterFactory. * When disconnected, factory methods are determined by functional parameters. * </p> */ private final AtomicBoolean connected = new AtomicBoolean(true); /** Time between reconnection checks */ final Duration timeBetweenConnectionChecks; /** * Maximum amount of time a factory method will wait for reconnect before * throwing TimeOutException */ final Duration maxWait; /** Function to perform when makeObject is executed in disconnected mode */ final Supplier<PooledObject<Waiter>> disconnectedCreateAction; /** * Function to perform for activate, passsivate and destroy when invoked in * disconnected mode */ final Consumer<PooledObject<Waiter>> disconnectedLifcycleAction; /** Function to perform for validate when invoked in disconnected mode */ final Predicate<PooledObject<Waiter>> disconnectedValidationAction; public DisconnectingWaiterFactory() { this(DEFAULT_DISCONNECTED_CREATE_ACTION, DEFAULT_DISCONNECTED_LIFECYCLE_ACTION, DEFAULT_DISCONNECTED_VALIDATION_ACTION); } public DisconnectingWaiterFactory(final long activateLatency, final long destroyLatency, final long makeLatency, final long passivateLatency, final long validateLatency, final long waiterLatency) { this(activateLatency, destroyLatency, makeLatency, passivateLatency, validateLatency, waiterLatency, Long.MAX_VALUE, Long.MAX_VALUE, 0); } public DisconnectingWaiterFactory(final long activateLatency, final long destroyLatency, final long makeLatency, final long passivateLatency, final long validateLatency, final long waiterLatency, final long maxActive) { this(activateLatency, destroyLatency, makeLatency, passivateLatency, validateLatency, waiterLatency, maxActive, Long.MAX_VALUE, 0); } public DisconnectingWaiterFactory(final long activateLatency, final long destroyLatency, final long makeLatency, final long passivateLatency, final long validateLatency, final long waiterLatency, final long maxActive, final long maxActivePerKey, final double passivateInvalidationProbability) { super(activateLatency, destroyLatency, makeLatency, passivateLatency, validateLatency, waiterLatency, maxActive, maxActivePerKey, passivateInvalidationProbability); this.timeBetweenConnectionChecks = DEFAULT_TIME_BETWEEN_CONNECTION_CHECKS; this.maxWait = DEFAULT_MAX_WAIT; this.disconnectedCreateAction = DEFAULT_DISCONNECTED_CREATE_ACTION; this.disconnectedLifcycleAction = DEFAULT_DISCONNECTED_LIFECYCLE_ACTION; this.disconnectedValidationAction = DEFAULT_DISCONNECTED_VALIDATION_ACTION; } public DisconnectingWaiterFactory(final Supplier<PooledObject<Waiter>> disconnectedCreateAction, final Consumer<PooledObject<Waiter>> disconnectedLifcycleAction, final Predicate<PooledObject<Waiter>> disconnectedValidationAction) { super(0, 0, 0, 0, 0, 0, Integer.MAX_VALUE, Integer.MAX_VALUE, 0); this.timeBetweenConnectionChecks = DEFAULT_TIME_BETWEEN_CONNECTION_CHECKS; this.maxWait = DEFAULT_MAX_WAIT; this.disconnectedCreateAction = disconnectedCreateAction; this.disconnectedLifcycleAction = disconnectedLifcycleAction; this.disconnectedValidationAction = disconnectedValidationAction; } private void activate(final PooledObject<Waiter> obj) { if (connected.get()) { super.activateObject(obj); } else { disconnectedLifcycleAction.accept(obj); } } @Override public void activateObject(final K key, final PooledObject<Waiter> obj) { activate(obj); } @Override public void activateObject(final PooledObject<Waiter> obj) { activate(obj); } /** * Reconnect the factory. */ public void connect() { connected.set(true); } /* * TODO: add builder to clean up constructors and make maxWait, * timeBetweenConnectionChecks configurable. */ /** * Disconnect the factory. */ public void disconnect() { connected.set(false); } private PooledObject<Waiter> make() { if (connected.get()) { return super.makeObject(); } return disconnectedCreateAction.get(); } @Override public PooledObject<Waiter> makeObject() { return make(); } @Override public PooledObject<Waiter> makeObject(final K key) { return make(); } private void passivate(final PooledObject<Waiter> obj) { if (connected.get()) { super.passivateObject(obj); } else { disconnectedLifcycleAction.accept(obj); } } @Override public void passivateObject(final K key, final PooledObject<Waiter> obj) { passivate(obj); } @Override public void passivateObject(final PooledObject<Waiter> obj) { passivate(obj); } private boolean validate(final PooledObject<Waiter> obj) { if (connected.get()) { return super.validateObject(obj); } return disconnectedValidationAction.test(obj); } @Override public boolean validateObject(final K key, final PooledObject<Waiter> obj) { return validate(obj); } @Override public boolean validateObject(final PooledObject<Waiter> obj) { return validate(obj); } }
5,207
0
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/impl/AtomicIntegerFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.impl; import java.util.concurrent.atomic.AtomicInteger; import org.apache.commons.pool3.BasePooledObjectFactory; import org.apache.commons.pool3.PooledObject; import org.apache.commons.pool3.Waiter; /** * Factory that sources PooledObjects that wrap AtomicIntegers. * {@link #create()} creates an AtomicInteger with value 0, activate increments * the value of the wrapped AtomicInteger and passivate decrements it. Latency * of factory methods is configurable. */ public class AtomicIntegerFactory extends BasePooledObjectFactory<AtomicInteger, RuntimeException> { private long activateLatency; private long passivateLatency; private long createLatency; private long destroyLatency; private long validateLatency; @Override public void activateObject(final PooledObject<AtomicInteger> p) { p.getObject().incrementAndGet(); Waiter.sleepQuietly(activateLatency); } @Override public AtomicInteger create() { Waiter.sleepQuietly(createLatency); return new AtomicInteger(0); } @Override public void destroyObject(final PooledObject<AtomicInteger> p) { Waiter.sleepQuietly(destroyLatency); } @Override public void passivateObject(final PooledObject<AtomicInteger> p) { p.getObject().decrementAndGet(); Waiter.sleepQuietly(passivateLatency); } /** * @param activateLatency the activateLatency to set */ public void setActivateLatency(final long activateLatency) { this.activateLatency = activateLatency; } /** * @param createLatency the createLatency to set */ public void setCreateLatency(final long createLatency) { this.createLatency = createLatency; } /** * @param destroyLatency the destroyLatency to set */ public void setDestroyLatency(final long destroyLatency) { this.destroyLatency = destroyLatency; } /** * @param passivateLatency the passivateLatency to set */ public void setPassivateLatency(final long passivateLatency) { this.passivateLatency = passivateLatency; } /** * @param validateLatency the validateLatency to set */ public void setValidateLatency(final long validateLatency) { this.validateLatency = validateLatency; } @Override public boolean validateObject(final PooledObject<AtomicInteger> instance) { Waiter.sleepQuietly(validateLatency); return instance.getObject().intValue() == 1; } @Override public PooledObject<AtomicInteger> wrap(final AtomicInteger integer) { return new DefaultPooledObject<>(integer); } }
5,208
0
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/impl/TestLinkedBlockingDeque.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.impl; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; /** * Tests for {@link LinkedBlockingDeque}. */ public class TestLinkedBlockingDeque { private static final Duration TIMEOUT_50_MILLIS = Duration.ofMillis(50); private static final Integer ONE = Integer.valueOf(1); private static final Integer TWO = Integer.valueOf(2); private static final Integer THREE = Integer.valueOf(3); LinkedBlockingDeque<Integer> deque; @BeforeEach public void setUp() { deque = new LinkedBlockingDeque<>(2); } @Test public void testAdd() { assertTrue(deque.add(ONE)); assertTrue(deque.add(TWO)); assertThrows(IllegalStateException.class, () -> deque.add(THREE)); assertThrows(NullPointerException.class, () -> deque.add(null)); } @Test public void testAddFirst() { deque.addFirst(ONE); deque.addFirst(TWO); assertEquals(2, deque.size()); assertThrows(IllegalStateException.class, () -> deque.add(THREE)); assertEquals(Integer.valueOf(2), deque.pop()); } @Test public void testAddLast() { deque.addLast(ONE); deque.addLast(TWO); assertEquals(2, deque.size()); assertThrows(IllegalStateException.class, () -> deque.add(THREE)); assertEquals(Integer.valueOf(1), deque.pop()); } @Test public void testClear() { deque.add(ONE); deque.add(TWO); deque.clear(); deque.add(ONE); assertEquals(1, deque.size()); } @Test public void testConstructors() { LinkedBlockingDeque<Integer> deque = new LinkedBlockingDeque<>(); assertEquals(Integer.MAX_VALUE, deque.remainingCapacity()); deque = new LinkedBlockingDeque<>(2); assertEquals(2, deque.remainingCapacity()); deque = new LinkedBlockingDeque<>(Arrays.asList(ONE, TWO)); assertEquals(2, deque.size()); assertThrows(NullPointerException.class, () -> new LinkedBlockingDeque<>(Arrays.asList(ONE, null))); } @Test public void testContains() { deque.add(ONE); assertTrue(deque.contains(ONE)); assertFalse(deque.contains(TWO)); assertFalse(deque.contains(null)); deque.add(TWO); assertTrue(deque.contains(TWO)); assertFalse(deque.contains(THREE)); } @Test public void testDescendingIterator() { assertThrows(NoSuchElementException.class, () -> deque.descendingIterator().next()); deque.add(ONE); deque.add(TWO); final Iterator<Integer> iter = deque.descendingIterator(); assertEquals(Integer.valueOf(2), iter.next()); iter.remove(); assertEquals(Integer.valueOf(1), iter.next()); } @Test public void testDrainTo() { Collection<Integer> c = new ArrayList<>(); deque.add(ONE); deque.add(TWO); assertEquals(2, deque.drainTo(c)); assertEquals(2, c.size()); c = new ArrayList<>(); deque.add(ONE); deque.add(TWO); assertEquals(1, deque.drainTo(c, 1)); assertEquals(1, deque.size()); assertEquals(1, c.size()); assertEquals(Integer.valueOf(1), c.iterator().next()); } @Test public void testElement() { assertThrows(NoSuchElementException.class, () -> deque.element()); deque.add(ONE); deque.add(TWO); assertEquals(Integer.valueOf(1), deque.element()); } @Test public void testGetFirst() { assertThrows(NoSuchElementException.class, () -> deque.getFirst()); deque.add(ONE); deque.add(TWO); assertEquals(Integer.valueOf(1), deque.getFirst()); } @Test public void testGetLast() { assertThrows(NoSuchElementException.class, () -> deque.getLast()); deque.add(ONE); deque.add(TWO); assertEquals(Integer.valueOf(2), deque.getLast()); } @Test public void testIterator() { assertThrows(NoSuchElementException.class, () -> deque.iterator().next()); deque.add(ONE); deque.add(TWO); final Iterator<Integer> iter = deque.iterator(); assertEquals(Integer.valueOf(1), iter.next()); iter.remove(); assertEquals(Integer.valueOf(2), iter.next()); } @Test public void testOffer() { assertTrue(deque.offer(ONE)); assertTrue(deque.offer(TWO)); assertFalse(deque.offer(THREE)); assertThrows(NullPointerException.class, () -> deque.offer(null)); } @Test public void testOfferFirst() { deque.offerFirst(ONE); deque.offerFirst(TWO); assertEquals(2, deque.size()); assertThrows(NullPointerException.class, () -> deque.offerFirst(null)); assertEquals(Integer.valueOf(2), deque.pop()); } @Test public void testOfferFirstWithTimeout() throws InterruptedException { assertThrows(NullPointerException.class, () -> deque.offerFirst(null, TIMEOUT_50_MILLIS)); assertTrue(deque.offerFirst(ONE, TIMEOUT_50_MILLIS)); assertTrue(deque.offerFirst(TWO, TIMEOUT_50_MILLIS)); assertFalse(deque.offerFirst(THREE, TIMEOUT_50_MILLIS)); } @Test public void testOfferLast() { deque.offerLast(ONE); deque.offerLast(TWO); assertEquals(2, deque.size()); assertThrows(NullPointerException.class, () -> deque.offerLast(null)); assertEquals(Integer.valueOf(1), deque.pop()); } @Test public void testOfferLastWithTimeout() throws InterruptedException { assertThrows(NullPointerException.class, () -> deque.offerLast(null, TIMEOUT_50_MILLIS)); assertTrue(deque.offerLast(ONE, TIMEOUT_50_MILLIS)); assertTrue(deque.offerLast(TWO, TIMEOUT_50_MILLIS)); assertFalse(deque.offerLast(THREE, TIMEOUT_50_MILLIS)); } @Test public void testOfferWithTimeout() throws InterruptedException { assertTrue(deque.offer(ONE, TIMEOUT_50_MILLIS)); assertTrue(deque.offer(TWO, TIMEOUT_50_MILLIS)); assertFalse(deque.offer(THREE, TIMEOUT_50_MILLIS)); assertThrows(NullPointerException.class, () -> deque.offer(null, TIMEOUT_50_MILLIS)); } @Test public void testPeek() { assertNull(deque.peek()); deque.add(ONE); deque.add(TWO); assertEquals(Integer.valueOf(1), deque.peek()); } @Test public void testPeekFirst() { assertNull(deque.peekFirst()); deque.add(ONE); deque.add(TWO); assertEquals(Integer.valueOf(1), deque.peekFirst()); } @Test public void testPeekLast() { assertNull(deque.peekLast()); deque.add(ONE); deque.add(TWO); assertEquals(Integer.valueOf(2), deque.peekLast()); } @Test public void testPollFirst() { assertNull(deque.pollFirst()); assertTrue(deque.offerFirst(ONE)); assertTrue(deque.offerFirst(TWO)); assertEquals(Integer.valueOf(2), deque.pollFirst()); } @Test public void testPollFirstWithTimeout() throws InterruptedException { assertNull(deque.pollFirst()); assertNull(deque.pollFirst(TIMEOUT_50_MILLIS)); } @Test public void testPollLast() { assertNull(deque.pollLast()); assertTrue(deque.offerFirst(ONE)); assertTrue(deque.offerFirst(TWO)); assertEquals(Integer.valueOf(1), deque.pollLast()); } @Test public void testPollLastWithTimeout() throws InterruptedException { assertNull(deque.pollLast()); assertNull(deque.pollLast(TIMEOUT_50_MILLIS)); } @Test public void testPollWithTimeout() throws InterruptedException { assertNull(deque.poll(TIMEOUT_50_MILLIS)); assertNull(deque.poll(TIMEOUT_50_MILLIS)); } @Test public void testPop() { assertThrows(NoSuchElementException.class, () -> deque.pop()); deque.add(ONE); deque.add(TWO); assertEquals(Integer.valueOf(1), deque.pop()); assertThrows(NoSuchElementException.class, () -> { deque.pop(); deque.pop(); }); } /* * https://issues.apache.org/jira/browse/POOL-281 * * Should complete almost instantly when the issue is fixed. */ @Test @Timeout(value = 10000, unit = TimeUnit.MILLISECONDS) public void testPossibleBug() { deque = new LinkedBlockingDeque<>(); for (int i = 0; i < 3; i++) { deque.add(Integer.valueOf(i)); } // This particular sequence of method calls() (there may be others) // creates an internal state that triggers an infinite loop in the // iterator. final Iterator<Integer> iter = deque.iterator(); iter.next(); deque.remove(Integer.valueOf(1)); deque.remove(Integer.valueOf(0)); deque.remove(Integer.valueOf(2)); iter.next(); } @Test public void testPush() { deque.push(ONE); deque.push(TWO); assertEquals(2, deque.size()); assertThrows(IllegalStateException.class, () -> deque.push(THREE)); assertEquals(Integer.valueOf(2), deque.pop()); } @Test public void testPut() throws InterruptedException { assertThrows(NullPointerException.class, () -> deque.put(null)); deque.put(ONE); deque.put(TWO); } @Test public void testPutFirst() throws InterruptedException { assertThrows(NullPointerException.class, () -> deque.putFirst(null)); deque.putFirst(ONE); deque.putFirst(TWO); assertEquals(2, deque.size()); assertEquals(Integer.valueOf(2), deque.pop()); } @Test public void testPutLast() throws InterruptedException { assertThrows(NullPointerException.class, () -> deque.putLast(null)); deque.putLast(ONE); deque.putLast(TWO); assertEquals(2, deque.size()); assertEquals(Integer.valueOf(1), deque.pop()); } @Test public void testRemove() { assertThrows(NoSuchElementException.class, deque::remove); deque.add(ONE); deque.add(TWO); assertEquals(Integer.valueOf(1), deque.remove()); } @Test public void testRemoveFirst() { assertThrows(NoSuchElementException.class, deque::removeFirst); deque.add(ONE); deque.add(TWO); assertEquals(Integer.valueOf(1), deque.removeFirst()); assertThrows(NoSuchElementException.class, () -> { deque.removeFirst(); deque.removeFirst(); }); } @Test public void testRemoveLast() { assertThrows(NoSuchElementException.class, deque::removeLast); deque.add(ONE); deque.add(TWO); assertEquals(Integer.valueOf(2), deque.removeLast()); assertThrows(NoSuchElementException.class, () -> { deque.removeLast(); deque.removeLast(); }); } @Test public void testRemoveLastOccurrence() { assertFalse(deque.removeLastOccurrence(null)); assertFalse(deque.removeLastOccurrence(ONE)); deque.add(ONE); deque.add(ONE); assertTrue(deque.removeLastOccurrence(ONE)); assertEquals(1, deque.size()); } @Test public void testTake() throws InterruptedException { assertTrue(deque.offerFirst(ONE)); assertTrue(deque.offerFirst(TWO)); assertEquals(Integer.valueOf(2), deque.take()); } @Test public void testTakeFirst() throws InterruptedException { assertTrue(deque.offerFirst(ONE)); assertTrue(deque.offerFirst(TWO)); assertEquals(Integer.valueOf(2), deque.takeFirst()); } @Test public void testTakeLast() throws InterruptedException { assertTrue(deque.offerFirst(ONE)); assertTrue(deque.offerFirst(TWO)); assertEquals(Integer.valueOf(1), deque.takeLast()); } @Test public void testToArray() { deque.add(ONE); deque.add(TWO); Object[] arr = deque.toArray(); assertEquals(Integer.valueOf(1), arr[0]); assertEquals(Integer.valueOf(2), arr[1]); arr = deque.toArray(new Integer[0]); assertEquals(Integer.valueOf(1), arr[0]); assertEquals(Integer.valueOf(2), arr[1]); arr = deque.toArray(new Integer[0]); assertEquals(Integer.valueOf(1), arr[0]); assertEquals(Integer.valueOf(2), arr[1]); } }
5,209
0
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/impl/NoOpCallStackTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.impl; import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.PrintWriter; import java.io.StringWriter; import org.junit.jupiter.api.Test; public class NoOpCallStackTest { @Test public void testPrintStackTraceIsNoOp() { final CallStack stack = NoOpCallStack.INSTANCE; stack.fillInStackTrace(); final StringWriter writer = new StringWriter(); stack.printStackTrace(new PrintWriter(writer)); assertEquals("", writer.toString()); } }
5,210
0
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/impl/TestConstants.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.impl; import java.time.Duration; /** * Constants used in tests. */ public class TestConstants { /** * A duration of one second. */ public static final Duration ONE_SECOND_DURATION = Duration.ofSeconds(1); /** * A duration of one minute. */ public static final Duration ONE_MINUTE_DURATION = Duration.ofMinutes(1); /** * A duration of one millisecond. */ public static final Duration ONE_MILLISECOND_DURATION = Duration.ofMillis(1); }
5,211
0
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/impl/TestAbandonedObjectPool.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.impl; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.PrintWriter; import java.lang.management.ManagementFactory; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; import java.util.Objects; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import javax.management.MBeanServer; import javax.management.ObjectName; import org.apache.commons.pool3.DestroyMode; import org.apache.commons.pool3.PooledObject; import org.apache.commons.pool3.PooledObjectFactory; import org.apache.commons.pool3.TrackedUse; import org.apache.commons.pool3.Waiter; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; final class PooledTestObject implements TrackedUse { private static final AtomicInteger ATOMIC_HASH = new AtomicInteger(); private static final Instant INSTANT_0 = Instant.ofEpochMilli(0); private static final Instant INSTANT_1 = Instant.ofEpochMilli(1); private boolean active; private boolean destroyed; private final int hash; private boolean abandoned; private boolean detached; // destroy-abandoned "detaches" public PooledTestObject() { this.hash = ATOMIC_HASH.incrementAndGet(); } public void destroy(final DestroyMode mode) { destroyed = true; if (mode.equals(DestroyMode.ABANDONED)) { detached = true; } } @Override public boolean equals(final Object obj) { if (!(obj instanceof PooledTestObject)) { return false; } return obj.hashCode() == hashCode(); } @Override public Instant getLastUsedInstant() { if (abandoned) { // Abandoned object sweep will occur no matter what the value of removeAbandonedTimeout, // because this indicates that this object was last used decades ago return INSTANT_1; } // Abandoned object sweep won't clean up this object return INSTANT_0; } @Override public int hashCode() { return hash; } public synchronized boolean isActive() { return active; } public boolean isDestroyed() { return destroyed; } public boolean isDetached() { return detached; } public void setAbandoned(final boolean b) { abandoned = b; } public synchronized void setActive(final boolean b) { active = b; } } /** * TestCase for AbandonedObjectPool */ public class TestAbandonedObjectPool { final class ConcurrentBorrower extends Thread { private final ArrayList<PooledTestObject> borrowed; public ConcurrentBorrower(final ArrayList<PooledTestObject> borrowed) { this.borrowed = borrowed; } @Override public void run() { try { borrowed.add(pool.borrowObject()); } catch (final Exception e) { // expected in most cases } } } final class ConcurrentReturner extends Thread { private final PooledTestObject returned; public ConcurrentReturner(final PooledTestObject obj) { returned = obj; } @Override public void run() { try { sleep(20); pool.returnObject(returned); } catch (final Exception e) { // ignore } } } private static final class SimpleFactory implements PooledObjectFactory<PooledTestObject, InterruptedException> { private final long destroyLatency; private final long validateLatency; public SimpleFactory() { destroyLatency = 0; validateLatency = 0; } public SimpleFactory(final long destroyLatency, final long validateLatency) { this.destroyLatency = destroyLatency; this.validateLatency = validateLatency; } @Override public void activateObject(final PooledObject<PooledTestObject> obj) { obj.getObject().setActive(true); } @Override public void destroyObject(final PooledObject<PooledTestObject> obj) throws InterruptedException { destroyObject(obj, DestroyMode.NORMAL); } @Override public void destroyObject(final PooledObject<PooledTestObject> obj, final DestroyMode destroyMode) throws InterruptedException { obj.getObject().setActive(false); // while destroying instances, yield control to other threads // helps simulate threading errors Thread.yield(); if (destroyLatency != 0) { Thread.sleep(destroyLatency); } obj.getObject().destroy(destroyMode); } @Override public PooledObject<PooledTestObject> makeObject() { return new DefaultPooledObject<>(new PooledTestObject()); } @Override public void passivateObject(final PooledObject<PooledTestObject> obj) { obj.getObject().setActive(false); } @Override public boolean validateObject(final PooledObject<PooledTestObject> obj) { Waiter.sleepQuietly(validateLatency); return true; } } private GenericObjectPool<PooledTestObject, InterruptedException> pool; private AbandonedConfig abandonedConfig; @SuppressWarnings("deprecation") @BeforeEach public void setUp() { abandonedConfig = new AbandonedConfig(); // Uncomment the following line to enable logging: // abandonedConfig.setLogAbandoned(true); abandonedConfig.setRemoveAbandonedOnBorrow(true); // One second Duration. abandonedConfig.setRemoveAbandonedTimeout(TestConstants.ONE_SECOND_DURATION); assertEquals(TestConstants.ONE_SECOND_DURATION, abandonedConfig.getRemoveAbandonedTimeoutDuration()); pool = new GenericObjectPool<>( new SimpleFactory(), new GenericObjectPoolConfig<>(), abandonedConfig); } @AfterEach public void tearDown() throws Exception { final ObjectName jmxName = pool.getJmxName(); final String poolName = Objects.toString(jmxName, null); pool.clear(); pool.close(); pool = null; final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); final Set<ObjectName> result = mbs.queryNames(new ObjectName( "org.apache.commoms.pool3:type=GenericObjectPool,*"), null); // There should be no registered pools at this point final int registeredPoolCount = result.size(); final StringBuilder msg = new StringBuilder("Current pool is: "); msg.append(poolName); msg.append(" Still open pools are: "); for (final ObjectName name : result) { // Clean these up ready for the next test msg.append(name.toString()); msg.append(" created via\n"); msg.append(mbs.getAttribute(name, "CreationStackTrace")); msg.append('\n'); mbs.unregisterMBean(name); } assertEquals( 0, registeredPoolCount,msg.toString()); } /** * Verify that an object that gets flagged as abandoned and is subsequently * invalidated is only destroyed (and pool counter decremented) once. * * @throws Exception May occur in some failure modes */ @Test public void testAbandonedInvalidate() throws Exception { abandonedConfig = new AbandonedConfig(); abandonedConfig.setRemoveAbandonedOnMaintenance(true); abandonedConfig.setRemoveAbandonedTimeout(TestConstants.ONE_SECOND_DURATION); pool.close(); // Unregister pool created by setup pool = new GenericObjectPool<>( // destroys take 200 ms new SimpleFactory(200, 0), new GenericObjectPoolConfig<>(), abandonedConfig); final int n = 10; pool.setMaxTotal(n); pool.setBlockWhenExhausted(false); pool.setDurationBetweenEvictionRuns(Duration.ofMillis(500)); PooledTestObject obj = null; for (int i = 0; i < 5; i++) { obj = pool.borrowObject(); } Thread.sleep(1000); // abandon checked out instances and let evictor start pool.invalidateObject(obj); // Should not trigger another destroy / decrement Thread.sleep(2000); // give evictor time to finish destroys assertEquals(0, pool.getNumActive()); assertEquals(5, pool.getDestroyedCount()); } /** * Verify that an object that gets flagged as abandoned and is subsequently returned * is destroyed instead of being returned to the pool (and possibly later destroyed * inappropriately). * * @throws Exception May occur in some failure modes */ @Test public void testAbandonedReturn() throws Exception { abandonedConfig = new AbandonedConfig(); abandonedConfig.setRemoveAbandonedOnBorrow(true); abandonedConfig.setRemoveAbandonedTimeout(TestConstants.ONE_SECOND_DURATION); pool.close(); // Unregister pool created by setup pool = new GenericObjectPool<>( new SimpleFactory(200, 0), new GenericObjectPoolConfig<>(), abandonedConfig); final int n = 10; pool.setMaxTotal(n); pool.setBlockWhenExhausted(false); PooledTestObject obj = null; for (int i = 0; i < n - 2; i++) { obj = pool.borrowObject(); } Objects.requireNonNull(obj, "Unable to borrow object from pool"); final int deadMansHash = obj.hashCode(); final ConcurrentReturner returner = new ConcurrentReturner(obj); Thread.sleep(2000); // abandon checked out instances // Now start a race - returner waits until borrowObject has kicked // off removeAbandoned and then returns an instance that borrowObject // will deem abandoned. Make sure it is not returned to the borrower. returner.start(); // short delay, then return instance assertTrue(pool.borrowObject().hashCode() != deadMansHash); assertEquals(0, pool.getNumIdle()); assertEquals(1, pool.getNumActive()); } /** * Tests fix for Bug 28579, a bug in AbandonedObjectPool that causes numActive to go negative * in GenericObjectPool * * @throws Exception May occur in some failure modes */ @Test public void testConcurrentInvalidation() throws Exception { final int POOL_SIZE = 30; pool.setMaxTotal(POOL_SIZE); pool.setMaxIdle(POOL_SIZE); pool.setBlockWhenExhausted(false); // Exhaust the connection pool final ArrayList<PooledTestObject> vec = new ArrayList<>(); for (int i = 0; i < POOL_SIZE; i++) { vec.add(pool.borrowObject()); } // Abandon all borrowed objects for (final PooledTestObject element : vec) { element.setAbandoned(true); } // Try launching a bunch of borrows concurrently. Abandoned sweep will be triggered for each. final int CONCURRENT_BORROWS = 5; final Thread[] threads = new Thread[CONCURRENT_BORROWS]; for (int i = 0; i < CONCURRENT_BORROWS; i++) { threads[i] = new ConcurrentBorrower(vec); threads[i].start(); } // Wait for all the threads to finish for (int i = 0; i < CONCURRENT_BORROWS; i++) { threads[i].join(); } // Return all objects that have not been destroyed for (final PooledTestObject pto : vec) { if (pto.isActive()) { pool.returnObject(pto); } } // Now, the number of active instances should be 0 assertEquals(0, pool.getNumActive(), "numActive should have been 0, was " + pool.getNumActive()); } public void testDestroyModeAbandoned() throws Exception { abandonedConfig = new AbandonedConfig(); abandonedConfig.setRemoveAbandonedOnMaintenance(true); abandonedConfig.setRemoveAbandonedTimeout(TestConstants.ONE_SECOND_DURATION); pool.close(); // Unregister pool created by setup pool = new GenericObjectPool<>( // validate takes 1 second new SimpleFactory(0, 0), new GenericObjectPoolConfig<>(), abandonedConfig); pool.setDurationBetweenEvictionRuns(Duration.ofMillis(50)); // Borrow an object, wait long enough for it to be abandoned final PooledTestObject obj = pool.borrowObject(); Thread.sleep(100); assertTrue(obj.isDetached()); } public void testDestroyModeNormal() throws Exception { abandonedConfig = new AbandonedConfig(); pool.close(); // Unregister pool created by setup pool = new GenericObjectPool<>(new SimpleFactory(0, 0)); pool.setMaxIdle(0); final PooledTestObject obj = pool.borrowObject(); pool.returnObject(obj); assertTrue(obj.isDestroyed()); assertFalse(obj.isDetached()); } /** * Verify that an object that the evictor identifies as abandoned while it * is in process of being returned to the pool is not destroyed. * * @throws Exception May occur in some failure modes */ @Test public void testRemoveAbandonedWhileReturning() throws Exception { abandonedConfig = new AbandonedConfig(); abandonedConfig.setRemoveAbandonedOnMaintenance(true); abandonedConfig.setRemoveAbandonedTimeout(TestConstants.ONE_SECOND_DURATION); pool.close(); // Unregister pool created by setup pool = new GenericObjectPool<>( // validate takes 1 second new SimpleFactory(0, 1000), new GenericObjectPoolConfig<>(), abandonedConfig); final int n = 10; pool.setMaxTotal(n); pool.setBlockWhenExhausted(false); pool.setDurationBetweenEvictionRuns(Duration.ofMillis(500)); pool.setTestOnReturn(true); // Borrow an object, wait long enough for it to be abandoned // then arrange for evictor to run while it is being returned // validation takes a second, evictor runs every 500 ms final PooledTestObject obj = pool.borrowObject(); Thread.sleep(50); // abandon obj pool.returnObject(obj); // evictor will run during validation final PooledTestObject obj2 = pool.borrowObject(); assertEquals(obj, obj2); // should get original back assertFalse(obj2.isDestroyed()); // and not destroyed } /** * JIRA: POOL-300 */ @Test public void testStackTrace() throws Exception { abandonedConfig.setRemoveAbandonedOnMaintenance(true); abandonedConfig.setLogAbandoned(true); abandonedConfig.setRemoveAbandonedTimeout(TestConstants.ONE_SECOND_DURATION); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final BufferedOutputStream bos = new BufferedOutputStream(baos); final PrintWriter pw = new PrintWriter(bos); abandonedConfig.setLogWriter(pw); pool.setAbandonedConfig(abandonedConfig); pool.setDurationBetweenEvictionRuns(Duration.ofMillis(100)); final PooledTestObject o1 = pool.borrowObject(); Thread.sleep(2000); assertTrue(o1.isDestroyed()); bos.flush(); assertTrue(baos.toString().indexOf("Pooled object") >= 0); } /** * Test case for https://issues.apache.org/jira/browse/DBCP-260. * Borrow and abandon all the available objects then attempt to borrow one * further object which should block until the abandoned objects are * removed. We don't want the test to block indefinitely when it fails so * use maxWait be check we don't actually have to wait that long. * * @throws Exception May occur in some failure modes */ @Test public void testWhenExhaustedBlock() throws Exception { abandonedConfig.setRemoveAbandonedOnMaintenance(true); pool.setAbandonedConfig(abandonedConfig); pool.setDurationBetweenEvictionRuns(Duration.ofMillis(500)); pool.setMaxTotal(1); @SuppressWarnings("unused") // This is going to be abandoned final PooledTestObject o1 = pool.borrowObject(); final long startMillis = System.currentTimeMillis(); final PooledTestObject o2 = pool.borrowObject(5000); final long endMillis = System.currentTimeMillis(); pool.returnObject(o2); assertTrue(endMillis - startMillis < 5000); } }
5,212
0
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/impl/TestGenericObjectPoolClassLoaders.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.impl; import static org.junit.jupiter.api.Assertions.assertEquals; import java.net.URL; import java.net.URLClassLoader; import java.time.Duration; import org.apache.commons.pool3.BasePooledObjectFactory; import org.apache.commons.pool3.PooledObject; import org.junit.jupiter.api.Test; public class TestGenericObjectPoolClassLoaders { private static final class CustomClassLoader extends URLClassLoader { private final int n; CustomClassLoader(final int n) { super(new URL[] { BASE_URL }); this.n = n; } @Override public URL findResource(final String name) { if (!name.endsWith(String.valueOf(n))) { return null; } return super.findResource(name); } } private static final class CustomClassLoaderObjectFactory extends BasePooledObjectFactory<URL, IllegalStateException> { private final int n; CustomClassLoaderObjectFactory(final int n) { this.n = n; } @Override public URL create() { final URL url = Thread.currentThread().getContextClassLoader() .getResource("test" + n); if (url == null) { throw new IllegalStateException("Object should not be null"); } return url; } @Override public PooledObject<URL> wrap(final URL value) { return new DefaultPooledObject<>(value); } } private static final URL BASE_URL = TestGenericObjectPoolClassLoaders.class .getResource("/org/apache/commons/pool3/impl/"); @Test public void testContextClassLoader() throws Exception { final ClassLoader savedClassloader = Thread.currentThread().getContextClassLoader(); try (final CustomClassLoader cl1 = new CustomClassLoader(1)) { Thread.currentThread().setContextClassLoader(cl1); final CustomClassLoaderObjectFactory factory1 = new CustomClassLoaderObjectFactory(1); try (final GenericObjectPool<URL, IllegalStateException> pool1 = new GenericObjectPool<>(factory1)) { pool1.setMinIdle(1); pool1.setDurationBetweenEvictionRuns(Duration.ofMillis(100)); int counter = 0; while (counter < 50 && pool1.getNumIdle() != 1) { Thread.sleep(100); counter++; } assertEquals(1, pool1.getNumIdle(), "Wrong number of idle objects in pool1"); try (final CustomClassLoader cl2 = new CustomClassLoader(2)) { Thread.currentThread().setContextClassLoader(cl2); final CustomClassLoaderObjectFactory factory2 = new CustomClassLoaderObjectFactory(2); try (final GenericObjectPool<URL, IllegalStateException> pool2 = new GenericObjectPool<>(factory2)) { pool2.setMinIdle(1); pool2.addObject(); assertEquals(1, pool2.getNumIdle(), "Wrong number of idle objects in pool2"); pool2.clear(); pool2.setDurationBetweenEvictionRuns(Duration.ofMillis(100)); counter = 0; while (counter < 50 && pool2.getNumIdle() != 1) { Thread.sleep(100); counter++; } assertEquals(1, pool2.getNumIdle(), "Wrong number of idle objects in pool2"); } } } } finally { Thread.currentThread().setContextClassLoader(savedClassloader); } } }
5,213
0
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/impl/TestDefaultPooledObjectInfo.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.impl; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import java.text.SimpleDateFormat; import java.util.Set; import org.apache.commons.pool3.TestException; import org.apache.commons.pool3.impl.TestGenericObjectPool.SimpleFactory; import org.junit.jupiter.api.Test; public class TestDefaultPooledObjectInfo { @Test public void testGetLastBorrowTrace() throws Exception { final AbandonedConfig abandonedConfig = new AbandonedConfig(); abandonedConfig.setRemoveAbandonedOnBorrow(true); abandonedConfig.setRemoveAbandonedTimeout(TestConstants.ONE_SECOND_DURATION); abandonedConfig.setLogAbandoned(true); try (final GenericObjectPool<String, TestException> pool = new GenericObjectPool<>(new SimpleFactory(), new GenericObjectPoolConfig<>(), abandonedConfig)) { pool.borrowObject(); // pool.returnObject(s1); // Object not returned, causes abandoned object created exception final Set<DefaultPooledObjectInfo> strings = pool.listAllObjects(); final DefaultPooledObjectInfo s1Info = strings.iterator().next(); final String lastBorrowTrace = s1Info.getLastBorrowTrace(); assertTrue(lastBorrowTrace.startsWith("Pooled object created")); } } @Test public void testGetPooledObjectToString() throws Exception { try (final GenericObjectPool<String, TestException> pool = new GenericObjectPool<>(new SimpleFactory())) { final String s1 = pool.borrowObject(); final Set<DefaultPooledObjectInfo> strings = pool.listAllObjects(); assertEquals(1, strings.size()); final DefaultPooledObjectInfo s1Info = strings.iterator().next(); assertEquals(s1, s1Info.getPooledObjectToString()); } } @Test public void testGetPooledObjectType() throws Exception { try (final GenericObjectPool<String, TestException> pool = new GenericObjectPool<>(new SimpleFactory())) { pool.borrowObject(); final Set<DefaultPooledObjectInfo> strings = pool.listAllObjects(); assertEquals(1, strings.size()); final DefaultPooledObjectInfo s1Info = strings.iterator().next(); assertEquals(String.class.getName(), s1Info.getPooledObjectType()); } } @Test public void testTiming() throws Exception { try (final GenericObjectPool<String, TestException> pool = new GenericObjectPool<>(new SimpleFactory())) { final long t1Millis = System.currentTimeMillis(); Thread.sleep(50); final String s1 = pool.borrowObject(); Thread.sleep(50); final long t2Millis = System.currentTimeMillis(); Thread.sleep(50); pool.returnObject(s1); Thread.sleep(50); final long t3Millis = System.currentTimeMillis(); Thread.sleep(50); pool.borrowObject(); Thread.sleep(50); final long t4Millis = System.currentTimeMillis(); final Set<DefaultPooledObjectInfo> strings = pool.listAllObjects(); assertEquals(1, strings.size()); final DefaultPooledObjectInfo s1Info = strings.iterator().next(); final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z"); assertTrue(s1Info.getCreateTime() > t1Millis); assertEquals(sdf.format(Long.valueOf(s1Info.getCreateTime())), s1Info.getCreateTimeFormatted()); assertTrue(s1Info.getCreateTime() < t2Millis); assertTrue(s1Info.getLastReturnTime() > t2Millis); assertEquals(sdf.format(Long.valueOf(s1Info.getLastReturnTime())), s1Info.getLastReturnTimeFormatted()); assertTrue(s1Info.getLastReturnTime() < t3Millis); assertTrue(s1Info.getLastBorrowTime() > t3Millis); assertEquals(sdf.format(Long.valueOf(s1Info.getLastBorrowTime())), s1Info.getLastBorrowTimeFormatted()); assertTrue(s1Info.getLastBorrowTime() < t4Millis); } } }
5,214
0
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/impl/TestEvictionTimer.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.impl; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import java.lang.reflect.Field; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ThreadPoolExecutor; import org.apache.commons.pool3.BasePooledObjectFactory; import org.apache.commons.pool3.PooledObject; import org.junit.jupiter.api.Test; /** * Tests for {@link EvictionTimer}. */ public class TestEvictionTimer { @Test public void testStartStopEvictionTimer() throws Exception { try (final GenericObjectPool<String, RuntimeException> pool = new GenericObjectPool<>(new BasePooledObjectFactory<String, RuntimeException>() { @Override public String create() { return null; } @Override public PooledObject<String> wrap(final String obj) { return new DefaultPooledObject<>(obj); } })) { // Start evictor #1 final BaseGenericObjectPool<String, RuntimeException>.Evictor evictor1 = pool.new Evictor(); EvictionTimer.schedule(evictor1, TestConstants.ONE_MINUTE_DURATION, TestConstants.ONE_MINUTE_DURATION); // 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(2, evictionExecutor.getQueue().size()); // Reaper plus one eviction task assertEquals(1, EvictionTimer.getNumTasks()); // Start evictor #2 final BaseGenericObjectPool<String, RuntimeException>.Evictor evictor2 = pool.new Evictor(); EvictionTimer.schedule(evictor2, TestConstants.ONE_MINUTE_DURATION, TestConstants.ONE_MINUTE_DURATION); // 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(3, evictionExecutor.getQueue().size()); // Reaper plus 2 eviction tasks assertEquals(2, EvictionTimer.getNumTasks()); // Stop evictor #1 EvictionTimer.cancel(evictor1, BaseObjectPoolConfig.DEFAULT_EVICTOR_SHUTDOWN_TIMEOUT, false); // 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(2, evictionExecutorOnStop.getQueue().size()); assertEquals(1, EvictionTimer.getNumTasks()); // Stop evictor #2 EvictionTimer.cancel(evictor2, BaseObjectPoolConfig.DEFAULT_EVICTOR_SHUTDOWN_TIMEOUT, false); // 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)); assertEquals(0, EvictionTimer.getNumTasks()); } } }
5,215
0
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/impl/TestGenericObjectPoolFactoryCreateFailure.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.impl; import static org.junit.jupiter.api.Assertions.assertFalse; import java.time.Duration; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.commons.pool3.BasePooledObjectFactory; import org.apache.commons.pool3.PooledObject; import org.apache.commons.pool3.Waiter; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; /** * Tests POOL-340. */ public class TestGenericObjectPoolFactoryCreateFailure { private static final class SingleObjectFactory extends BasePooledObjectFactory<Object, Exception> { private final AtomicBoolean created = new AtomicBoolean(); @Override public Object create() throws Exception { if (!created.getAndSet(true)) { return new Object(); } throw new Exception("Already created"); } @Override public boolean validateObject(final PooledObject<Object> p) { return true; } @Override public PooledObject<Object> wrap(final Object obj) { return new DefaultPooledObject<>(new Object()); } } private static final class WinnerRunnable implements Runnable { private final CountDownLatch barrier; private final AtomicBoolean failed; private final GenericObjectPool<Object, Exception> pool; private WinnerRunnable(final GenericObjectPool<Object, Exception> pool, final CountDownLatch barrier, final AtomicBoolean failed) { this.pool = pool; this.failed = failed; this.barrier = barrier; } @Override public void run() { try { println("start borrowing in parallel thread"); final Object obj = pool.borrowObject(); // wait for another thread to start borrowObject if (!barrier.await(5, TimeUnit.SECONDS)) { println("Timeout waiting"); failed.set(true); } else { // just to make sure, borrowObject has started waiting on queue Waiter.sleepQuietly(1000); } pool.returnObject(obj); println("ended borrowing in parallel thread"); } catch (final Exception e) { failed.set(true); e.printStackTrace(); } } } private static final Duration NEG_ONE_DURATION = Duration.ofMillis(-1); private static void println(final String msg) { // System.out.println(msg); } @Test @Timeout(value = 10_000, unit = TimeUnit.MILLISECONDS) public void testBorrowObjectStuck() { final SingleObjectFactory factory = new SingleObjectFactory(); final GenericObjectPoolConfig<Object> config = new GenericObjectPoolConfig<>(); config.setMaxIdle(1); config.setMaxTotal(1); config.setBlockWhenExhausted(true); config.setMinIdle(0); config.setTestOnBorrow(true); config.setTestOnReturn(true); config.setTestWhileIdle(false); config.setDurationBetweenEvictionRuns(NEG_ONE_DURATION); config.setMinEvictableIdleDuration(NEG_ONE_DURATION); config.setSoftMinEvictableIdleDuration(NEG_ONE_DURATION); config.setMaxWait(NEG_ONE_DURATION); try (GenericObjectPool<Object, Exception> pool = new GenericObjectPool<>(factory, config)) { final AtomicBoolean failed = new AtomicBoolean(); final CountDownLatch barrier = new CountDownLatch(1); final Thread thread1 = new Thread(new WinnerRunnable(pool, barrier, failed)); thread1.start(); // wait for object to be created while (!factory.created.get()) { Waiter.sleepQuietly(5); } // now borrow barrier.countDown(); try { println("try borrow in main thread"); final Object o = pool.borrowObject(); println("Success borrow in main thread " + o); } catch (final Exception e) { e.printStackTrace(); } assertFalse(failed.get()); } } }
5,216
0
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/impl/TestSynchronizedPooledObjectFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.impl; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock; import org.apache.commons.pool3.PooledObject; import org.apache.commons.pool3.PooledObjectFactory; /** * Copies PoolUtil's private static final class SynchronizedPooledObjectFactory. * * A fully synchronized PooledObjectFactory that wraps a PooledObjectFactory and * synchronizes access to the wrapped factory methods. * <p> * <b>Note:</b> This should not be used on pool implementations that already * provide proper synchronization such as the pools provided in the Commons Pool * library. * </p> */ final class TestSynchronizedPooledObjectFactory<T, E extends Exception> implements PooledObjectFactory<T, E> { /** Synchronization lock */ private final WriteLock writeLock = new ReentrantReadWriteLock().writeLock(); /** Wrapped factory */ private final PooledObjectFactory<T, E> factory; /** * Constructs a SynchronizedPoolableObjectFactory wrapping the given factory. * * @param factory * underlying factory to wrap * @throws IllegalArgumentException * if the factory is null */ TestSynchronizedPooledObjectFactory(final PooledObjectFactory<T, E> factory) throws IllegalArgumentException { if (factory == null) { throw new IllegalArgumentException("factory must not be null."); } this.factory = factory; } /** * {@inheritDoc} */ @Override public void activateObject(final PooledObject<T> p) throws E { writeLock.lock(); try { factory.activateObject(p); } finally { writeLock.unlock(); } } /** * {@inheritDoc} */ @Override public void destroyObject(final PooledObject<T> p) throws E { writeLock.lock(); try { factory.destroyObject(p); } finally { writeLock.unlock(); } } /** * {@inheritDoc} */ @Override public PooledObject<T> makeObject() throws E { writeLock.lock(); try { return factory.makeObject(); } finally { writeLock.unlock(); } } /** * {@inheritDoc} */ @Override public void passivateObject(final PooledObject<T> p) throws E { writeLock.lock(); try { factory.passivateObject(p); } finally { writeLock.unlock(); } } /** * {@inheritDoc} */ @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("SynchronizedPoolableObjectFactory"); sb.append("{factory=").append(factory); sb.append('}'); return sb.toString(); } /** * {@inheritDoc} */ @Override public boolean validateObject(final PooledObject<T> p) { writeLock.lock(); try { return factory.validateObject(p); } finally { writeLock.unlock(); } } }
5,217
0
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/impl/TestAbandonedKeyedObjectPool.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.impl; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.PrintWriter; import java.lang.management.ManagementFactory; import java.time.Duration; import java.util.ArrayList; import java.util.Objects; import java.util.Set; import javax.management.MBeanServer; import javax.management.ObjectName; import org.apache.commons.pool3.DestroyMode; import org.apache.commons.pool3.KeyedPooledObjectFactory; import org.apache.commons.pool3.PooledObject; import org.apache.commons.pool3.Waiter; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** * Tests for {@link AbandonedConfig}. */ public class TestAbandonedKeyedObjectPool { final class ConcurrentBorrower extends Thread { private final ArrayList<PooledTestObject> borrowed; public ConcurrentBorrower(final ArrayList<PooledTestObject> borrowed) { this.borrowed = borrowed; } @Override public void run() { try { borrowed.add(pool.borrowObject(0)); } catch (final Exception e) { // expected in most cases } } } final class ConcurrentReturner extends Thread { private final PooledTestObject returned; public ConcurrentReturner(final PooledTestObject obj) { returned = obj; } @Override public void run() { try { sleep(20); pool.returnObject(0, returned); } catch (final Exception e) { // ignore } } } private static final class SimpleFactory implements KeyedPooledObjectFactory<Integer, PooledTestObject, InterruptedException> { private final long destroyLatencyMillis; private final long validateLatencyMillis; public SimpleFactory() { destroyLatencyMillis = 0; validateLatencyMillis = 0; } public SimpleFactory(final long destroyLatencyMillis, final long validateLatencyMillis) { this.destroyLatencyMillis = destroyLatencyMillis; this.validateLatencyMillis = validateLatencyMillis; } @Override public void activateObject(final Integer key, final PooledObject<PooledTestObject> obj) { obj.getObject().setActive(true); } @Override public void destroyObject(final Integer key, final PooledObject<PooledTestObject> obj) throws InterruptedException { destroyObject(key, obj, DestroyMode.NORMAL); } @Override public void destroyObject(final Integer key, final PooledObject<PooledTestObject> obj, final DestroyMode destroyMode) throws InterruptedException { obj.getObject().setActive(false); // while destroying instances, yield control to other threads // helps simulate threading errors Thread.yield(); if (destroyLatencyMillis != 0) { Thread.sleep(destroyLatencyMillis); } obj.getObject().destroy(destroyMode); } @Override public PooledObject<PooledTestObject> makeObject(final Integer key) { return new DefaultPooledObject<>(new PooledTestObject()); } @Override public void passivateObject(final Integer key, final PooledObject<PooledTestObject> obj) { obj.getObject().setActive(false); } @Override public boolean validateObject(final Integer key, final PooledObject<PooledTestObject> obj) { Waiter.sleepQuietly(validateLatencyMillis); return true; } } private GenericKeyedObjectPool<Integer, PooledTestObject, InterruptedException> pool; private AbandonedConfig abandonedConfig; @SuppressWarnings("deprecation") @BeforeEach public void setUp() { abandonedConfig = new AbandonedConfig(); // Uncomment the following line to enable logging: // abandonedConfig.setLogAbandoned(true); // One second Duration. abandonedConfig.setRemoveAbandonedTimeout(TestConstants.ONE_SECOND_DURATION); assertEquals(TestConstants.ONE_SECOND_DURATION, abandonedConfig.getRemoveAbandonedTimeoutDuration()); pool = new GenericKeyedObjectPool<>( new SimpleFactory(), new GenericKeyedObjectPoolConfig<>(), abandonedConfig); } @AfterEach public void tearDown() throws Exception { final ObjectName jmxName = pool.getJmxName(); final String poolName = Objects.toString(jmxName, null); pool.clear(); pool.close(); pool = null; final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); final Set<ObjectName> result = mbs.queryNames(new ObjectName( "org.apache.commoms.pool3:type=GenericKeyedObjectPool,*"), null); // There should be no registered pools at this point final int registeredPoolCount = result.size(); final StringBuilder msg = new StringBuilder("Current pool is: "); msg.append(poolName); msg.append(" Still open pools are: "); for (final ObjectName name : result) { // Clean these up ready for the next test msg.append(name.toString()); msg.append(" created via\n"); msg.append(mbs.getAttribute(name, "CreationStackTrace")); msg.append('\n'); mbs.unregisterMBean(name); } assertEquals(0, registeredPoolCount,msg.toString()); } /** * Verify that an object that gets flagged as abandoned and is subsequently * invalidated is only destroyed (and pool counter decremented) once. * * @throws InterruptedException May occur in some failure modes */ @Test public void testAbandonedInvalidate() throws InterruptedException { abandonedConfig = new AbandonedConfig(); abandonedConfig.setRemoveAbandonedOnMaintenance(true); abandonedConfig.setRemoveAbandonedTimeout(Duration.ofMillis(2000)); pool.close(); // Unregister pool created by setup pool = new GenericKeyedObjectPool<>( // destroys take 100 millis new SimpleFactory(100, 0), new GenericKeyedObjectPoolConfig<>(), abandonedConfig); final int n = 10; pool.setMaxTotal(n); pool.setBlockWhenExhausted(false); pool.setDurationBetweenEvictionRuns(Duration.ofMillis(250)); PooledTestObject pooledObj = null; final Integer key = 0; for (int i = 0; i < 5; i++) { pooledObj = pool.borrowObject(key); } Thread.sleep(1000); // abandon checked out instances and let evictor start if (!pool.getKeys().contains(key)) { Thread.sleep(1000); // Wait a little more. } if (!pool.getKeys().contains(key)) { Thread.sleep(1000); // Wait a little more. } pool.invalidateObject(key, pooledObj); // Should not trigger another destroy / decrement Thread.sleep(2000); // give evictor time to finish destroys assertEquals(0, pool.getNumActive()); assertEquals(5, pool.getDestroyedCount()); } /** * Verify that an object that gets flagged as abandoned and is subsequently returned * is destroyed instead of being returned to the pool (and possibly later destroyed * inappropriately). * * @throws Exception May occur in some failure modes */ @Test public void testAbandonedReturn() throws Exception { abandonedConfig = new AbandonedConfig(); abandonedConfig.setRemoveAbandonedOnBorrow(true); abandonedConfig.setRemoveAbandonedTimeout(TestConstants.ONE_SECOND_DURATION); pool.close(); // Unregister pool created by setup pool = new GenericKeyedObjectPool<>( new SimpleFactory(200, 0), new GenericKeyedObjectPoolConfig<>(), abandonedConfig); final int n = 10; pool.setMaxTotal(n); pool.setBlockWhenExhausted(false); PooledTestObject obj = null; for (int i = 0; i < n - 2; i++) { obj = pool.borrowObject(0); } Objects.requireNonNull(obj, "Unable to borrow object from pool"); final int deadMansHash = obj.hashCode(); final ConcurrentReturner returner = new ConcurrentReturner(obj); Thread.sleep(2000); // abandon checked out instances // Now start a race - returner waits until borrowObject has kicked // off removeAbandoned and then returns an instance that borrowObject // will deem abandoned. Make sure it is not returned to the borrower. returner.start(); // short delay, then return instance assertTrue(pool.borrowObject(0).hashCode() != deadMansHash); assertEquals(0, pool.getNumIdle()); assertEquals(1, pool.getNumActive()); } /** * Tests fix for Bug 28579, a bug in AbandonedObjectPool that causes numActive to go negative * in GenericKeyedObjectPool * * @throws Exception May occur in some failure modes */ @Test public void testConcurrentInvalidation() throws Exception { final int POOL_SIZE = 30; pool.setMaxTotalPerKey(POOL_SIZE); pool.setMaxIdlePerKey(POOL_SIZE); pool.setBlockWhenExhausted(false); // Exhaust the connection pool final ArrayList<PooledTestObject> vec = new ArrayList<>(); for (int i = 0; i < POOL_SIZE; i++) { vec.add(pool.borrowObject(0)); } // Abandon all borrowed objects for (final PooledTestObject element : vec) { element.setAbandoned(true); } // Try launching a bunch of borrows concurrently. Abandoned sweep will be triggered for each. final int CONCURRENT_BORROWS = 5; final Thread[] threads = new Thread[CONCURRENT_BORROWS]; for (int i = 0; i < CONCURRENT_BORROWS; i++) { threads[i] = new ConcurrentBorrower(vec); threads[i].start(); } // Wait for all the threads to finish for (int i = 0; i < CONCURRENT_BORROWS; i++) { threads[i].join(); } // Return all objects that have not been destroyed for (final PooledTestObject pto : vec) { if (pto.isActive()) { pool.returnObject(0, pto); } } // Now, the number of active instances should be 0 assertEquals(0, pool.getNumActive(), "numActive should have been 0, was " + pool.getNumActive()); } public void testDestroyModeAbandoned() throws Exception { abandonedConfig = new AbandonedConfig(); abandonedConfig.setRemoveAbandonedOnMaintenance(true); abandonedConfig.setRemoveAbandonedTimeout(TestConstants.ONE_SECOND_DURATION); pool.close(); // Unregister pool created by setup pool = new GenericKeyedObjectPool<>( // validate takes 1 second new SimpleFactory(0, 0), new GenericKeyedObjectPoolConfig<>(), abandonedConfig); pool.setDurationBetweenEvictionRuns(Duration.ofMillis(50)); // Borrow an object, wait long enough for it to be abandoned final PooledTestObject obj = pool.borrowObject(0); Thread.sleep(100); assertTrue(obj.isDetached()); } public void testDestroyModeNormal() throws Exception { abandonedConfig = new AbandonedConfig(); pool.close(); // Unregister pool created by setup pool = new GenericKeyedObjectPool<>(new SimpleFactory(0, 0)); pool.setMaxIdlePerKey(0); final PooledTestObject obj = pool.borrowObject(0); pool.returnObject(0, obj); assertTrue(obj.isDestroyed()); assertFalse(obj.isDetached()); } /** * Verify that an object that the evictor identifies as abandoned while it * is in process of being returned to the pool is not destroyed. * * @throws Exception May occur in some failure modes */ @Test public void testRemoveAbandonedWhileReturning() throws Exception { abandonedConfig = new AbandonedConfig(); abandonedConfig.setRemoveAbandonedOnMaintenance(true); abandonedConfig.setRemoveAbandonedTimeout(TestConstants.ONE_SECOND_DURATION); pool.close(); // Unregister pool created by setup pool = new GenericKeyedObjectPool<>( // validate takes 1 second new SimpleFactory(0, 1000), new GenericKeyedObjectPoolConfig<>(), abandonedConfig); final int n = 10; pool.setMaxTotal(n); pool.setBlockWhenExhausted(false); pool.setDurationBetweenEvictionRuns(Duration.ofMillis(500)); pool.setTestOnReturn(true); // Borrow an object, wait long enough for it to be abandoned // then arrange for evictor to run while it is being returned // validation takes a second, evictor runs every 500 ms final PooledTestObject obj = pool.borrowObject(0); Thread.sleep(50); // abandon obj pool.returnObject(0,obj); // evictor will run during validation final PooledTestObject obj2 = pool.borrowObject(0); assertEquals(obj, obj2); // should get original back assertFalse(obj2.isDestroyed()); // and not destroyed } /** * JIRA: POOL-300 */ @Test public void testStackTrace() throws Exception { abandonedConfig.setRemoveAbandonedOnMaintenance(true); abandonedConfig.setLogAbandoned(true); abandonedConfig.setRemoveAbandonedTimeout(TestConstants.ONE_SECOND_DURATION); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final BufferedOutputStream bos = new BufferedOutputStream(baos); final PrintWriter pw = new PrintWriter(bos); abandonedConfig.setLogWriter(pw); pool.setAbandonedConfig(abandonedConfig); pool.setDurationBetweenEvictionRuns(Duration.ofMillis(100)); final PooledTestObject o1 = pool.borrowObject(0); Thread.sleep(2000); assertTrue(o1.isDestroyed()); bos.flush(); assertTrue(baos.toString().indexOf("Pooled object") >= 0); } /** * Test case for https://issues.apache.org/jira/browse/DBCP-260. * Borrow and abandon all the available objects then attempt to borrow one * further object which should block until the abandoned objects are * removed. We don't want the test to block indefinitely when it fails so * use maxWait be check we don't actually have to wait that long. * * @throws Exception May occur in some failure modes */ @Test public void testWhenExhaustedBlock() throws Exception { abandonedConfig.setRemoveAbandonedOnMaintenance(true); pool.setAbandonedConfig(abandonedConfig); pool.setDurationBetweenEvictionRuns(Duration.ofMillis(500)); pool.setMaxTotal(1); @SuppressWarnings("unused") // This is going to be abandoned final PooledTestObject o1 = pool.borrowObject(0); final long startMillis = System.currentTimeMillis(); final PooledTestObject o2 = pool.borrowObject(0, 5000); final long endMillis = System.currentTimeMillis(); pool.returnObject(0, o2); assertTrue(endMillis - startMillis < 5000); } }
5,218
0
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/impl/TestPoolImplUtils.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.impl; import static org.junit.jupiter.api.Assertions.assertEquals; import java.time.Duration; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.concurrent.TimeUnit; import org.apache.commons.pool3.BasePooledObjectFactory; import org.apache.commons.pool3.PooledObject; import org.junit.jupiter.api.Test; public class TestPoolImplUtils { @SuppressWarnings("unused") private abstract static class FactoryAB<A, B> extends BasePooledObjectFactory<B, RuntimeException> { // empty by design } private abstract static class FactoryBA<A, B> extends FactoryAB<B, A> { // empty by design } private abstract static class FactoryC<C> extends FactoryBA<C, String> { // empty by design } @SuppressWarnings("unused") private abstract static class FactoryDE<D, E> extends FactoryC<D> { // empty by design } private abstract static class FactoryF<F> extends FactoryDE<Long, F> { // empty by design } private static final class NotSimpleFactory extends FactoryF<Integer> { @Override public Long create() { return null; } @Override public PooledObject<Long> wrap(final Long obj) { return null; } } private static final class SimpleFactory extends BasePooledObjectFactory<String, RuntimeException> { @Override public String create() { return null; } @Override public PooledObject<String> wrap(final String obj) { return null; } } private static final Instant INSTANT_1 = Instant.ofEpochMilli(1); private static final Instant INSTANT_0 = Instant.ofEpochMilli(0); @Test public void testFactoryTypeNotSimple() { final Class<?> result = PoolImplUtils.getFactoryType(NotSimpleFactory.class); assertEquals(Long.class, result); } @Test public void testFactoryTypeSimple() { final Class<?> result = PoolImplUtils.getFactoryType(SimpleFactory.class); assertEquals(String.class, result); } @Test public void testMaxInstants() { assertEquals(INSTANT_1, PoolImplUtils.max(INSTANT_0, INSTANT_1)); assertEquals(INSTANT_1, PoolImplUtils.max(INSTANT_1, INSTANT_0)); assertEquals(INSTANT_1, PoolImplUtils.max(INSTANT_1, INSTANT_1)); assertEquals(INSTANT_0, PoolImplUtils.max(INSTANT_0, INSTANT_0)); } @Test public void testMinInstants() { assertEquals(INSTANT_0, PoolImplUtils.min(INSTANT_0, INSTANT_1)); assertEquals(INSTANT_0, PoolImplUtils.min(INSTANT_1, INSTANT_0)); assertEquals(INSTANT_1, PoolImplUtils.min(INSTANT_1, INSTANT_1)); assertEquals(INSTANT_0, PoolImplUtils.min(INSTANT_0, INSTANT_0)); } @Test public void testToChronoUnit() { assertEquals(ChronoUnit.NANOS, PoolImplUtils.toChronoUnit(TimeUnit.NANOSECONDS)); assertEquals(ChronoUnit.MICROS, PoolImplUtils.toChronoUnit(TimeUnit.MICROSECONDS)); assertEquals(ChronoUnit.MILLIS, PoolImplUtils.toChronoUnit(TimeUnit.MILLISECONDS)); assertEquals(ChronoUnit.SECONDS, PoolImplUtils.toChronoUnit(TimeUnit.SECONDS)); assertEquals(ChronoUnit.MINUTES, PoolImplUtils.toChronoUnit(TimeUnit.MINUTES)); assertEquals(ChronoUnit.HOURS, PoolImplUtils.toChronoUnit(TimeUnit.HOURS)); assertEquals(ChronoUnit.DAYS, PoolImplUtils.toChronoUnit(TimeUnit.DAYS)); } @Test public void testToDuration() { assertEquals(Duration.ZERO, PoolImplUtils.toDuration(0, TimeUnit.MILLISECONDS)); assertEquals(Duration.ofMillis(1), PoolImplUtils.toDuration(1, TimeUnit.MILLISECONDS)); for (final TimeUnit tu : TimeUnit.values()) { // All TimeUnit should be handled. assertEquals(Duration.ZERO, PoolImplUtils.toDuration(0, tu)); } } }
5,219
0
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/impl/TestBaseGenericObjectPool.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.impl; import static org.junit.jupiter.api.Assertions.assertEquals; import java.lang.management.ManagementFactory; import java.time.Duration; import java.util.ArrayList; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import javax.management.MBeanServer; import javax.management.ObjectName; import org.apache.commons.pool3.TestException; import org.apache.commons.pool3.Waiter; import org.apache.commons.pool3.WaiterFactory; import org.apache.commons.pool3.impl.TestGenericObjectPool.SimpleFactory; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; /** */ public class TestBaseGenericObjectPool { BaseGenericObjectPool<String, TestException> pool; SimpleFactory factory; @BeforeEach public void setUp() { factory = new SimpleFactory(); pool = new GenericObjectPool<>(factory); } @AfterEach public void tearDown() { pool.close(); pool = null; factory = null; } @Test public void testActiveTimeStatistics() { for (int i = 0; i < 99; i++) { // must be < MEAN_TIMING_STATS_CACHE_SIZE pool.updateStatsReturn(Duration.ofMillis(i)); } assertEquals(49, pool.getMeanActiveTimeMillis(), Double.MIN_VALUE); } @Test public void testBorrowWaitStatistics() { final DefaultPooledObject<String> p = (DefaultPooledObject<String>) factory.makeObject(); pool.updateStatsBorrow(p, Duration.ofMillis(10)); pool.updateStatsBorrow(p, Duration.ofMillis(20)); pool.updateStatsBorrow(p, Duration.ofMillis(20)); pool.updateStatsBorrow(p, Duration.ofMillis(30)); assertEquals(20, pool.getMeanBorrowWaitTimeMillis(), Double.MIN_VALUE); assertEquals(30, pool.getMaxBorrowWaitTimeMillis(), 0); } public void testBorrowWaitStatisticsMax() { final DefaultPooledObject<String> p = (DefaultPooledObject<String>) factory.makeObject(); assertEquals(0, pool.getMaxBorrowWaitTimeMillis(), Double.MIN_VALUE); pool.updateStatsBorrow(p, Duration.ZERO); assertEquals(0, pool.getMaxBorrowWaitTimeMillis(), Double.MIN_VALUE); pool.updateStatsBorrow(p, Duration.ofMillis(20)); assertEquals(20, pool.getMaxBorrowWaitTimeMillis(), Double.MIN_VALUE); pool.updateStatsBorrow(p, Duration.ofMillis(20)); assertEquals(20, pool.getMaxBorrowWaitTimeMillis(), Double.MIN_VALUE); pool.updateStatsBorrow(p, Duration.ofMillis(10)); assertEquals(20, pool.getMaxBorrowWaitTimeMillis(), Double.MIN_VALUE); } @Test public void testEvictionTimerMultiplePools() throws InterruptedException { final AtomicIntegerFactory factory = new AtomicIntegerFactory(); factory.setValidateLatency(50); try (final GenericObjectPool<AtomicInteger, RuntimeException> evictingPool = new GenericObjectPool<>(factory)) { evictingPool.setDurationBetweenEvictionRuns(Duration.ofMillis(100)); evictingPool.setNumTestsPerEvictionRun(5); evictingPool.setTestWhileIdle(true); evictingPool.setMinEvictableIdleDuration(Duration.ofMillis(50)); for (int i = 0; i < 10; i++) { try { evictingPool.addObject(); } catch (final Exception e) { e.printStackTrace(); } } for (int i = 0; i < 1000; i++) { try (final GenericObjectPool<AtomicInteger, RuntimeException> nonEvictingPool = new GenericObjectPool<>(factory)) { // empty } } Thread.sleep(1000); assertEquals(0, evictingPool.getNumIdle()); } } /** * POOL-393 * Tests JMX registration does not add too much latency to pool creation. */ @SuppressWarnings("resource") // pools closed in finally block @Test @Timeout(value = 10_000, unit = TimeUnit.MILLISECONDS) public void testJMXRegistrationLatency() { final int numPools = 1000; final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); final ArrayList<GenericObjectPool<Waiter, IllegalStateException>> pools = new ArrayList<>(); try { // final long startTime = System.currentTimeMillis(); for (int i = 0; i < numPools; i++) { pools.add(new GenericObjectPool<>(new WaiterFactory<>(0, 0, 0, 0, 0, 0), new GenericObjectPoolConfig<>())); } // System.out.println("Duration: " + (System.currentTimeMillis() - startTime)); final ObjectName oname = pools.get(numPools - 1).getJmxName(); assertEquals(1, mbs.queryNames(oname, null).size()); } finally { pools.forEach(GenericObjectPool::close); } } }
5,220
0
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/impl/TestPooledSoftReference.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.impl; import static org.junit.jupiter.api.Assertions.assertEquals; import java.lang.ref.SoftReference; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** * Tests for PooledSoftReference. */ public class TestPooledSoftReference { private static final String REFERENT = "test"; private static final String REFERENT2 = "test2"; PooledSoftReference<String> ref; @BeforeEach public void setUp() { final SoftReference<String> softRef = new SoftReference<>(REFERENT); ref = new PooledSoftReference<>(softRef); } @Test public void testPooledSoftReference() { assertEquals(REFERENT, ref.getObject()); SoftReference<String> softRef = ref.getReference(); assertEquals(REFERENT, softRef.get()); softRef.clear(); softRef = new SoftReference<>(REFERENT2); ref.setReference(softRef); assertEquals(REFERENT2, ref.getObject()); softRef = ref.getReference(); assertEquals(REFERENT2, softRef.get()); softRef.clear(); } @Test public void testToString() { final String expected = "Referenced Object: test, State: IDLE"; assertEquals(expected, ref.toString()); } }
5,221
0
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/impl/CallStackTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache license, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the license for the specific language governing permissions and * limitations under the license. */ package org.apache.commons.pool3.impl; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.PrintWriter; import java.io.StringWriter; import java.util.stream.Stream; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; public class CallStackTest { public static Stream<Arguments> data() { // @formatter:off return Stream.of( Arguments.arguments(new ThrowableCallStack("Test", false)), Arguments.arguments(new ThrowableCallStack("yyyy-MM-dd'T'HH:mm:ss.SSSXXX", true)), Arguments.arguments(new SecurityManagerCallStack("Test", false)), Arguments.arguments(new SecurityManagerCallStack("yyyy-MM-dd'T'HH:mm:ss.SSSXXX", true)) ); // @formatter:on } private final StringWriter writer = new StringWriter(); @ParameterizedTest @MethodSource("data") public void testPrintClearedStackTraceIsNoOp(final CallStack stack) { stack.fillInStackTrace(); stack.clear(); stack.printStackTrace(new PrintWriter(writer)); final String stackTrace = writer.toString(); assertEquals("", stackTrace); } @ParameterizedTest @MethodSource("data") public void testPrintFilledStackTrace(final CallStack stack) { stack.fillInStackTrace(); stack.printStackTrace(new PrintWriter(writer)); final String stackTrace = writer.toString(); assertTrue(stackTrace.contains(getClass().getName())); } }
5,222
0
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/impl/TestSoftReferenceObjectPool.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.impl; import org.apache.commons.pool3.BasePooledObjectFactory; import org.apache.commons.pool3.ObjectPool; import org.apache.commons.pool3.PooledObject; import org.apache.commons.pool3.PooledObjectFactory; import org.apache.commons.pool3.TestBaseObjectPool; /** */ public class TestSoftReferenceObjectPool extends TestBaseObjectPool { private static final class SimpleFactory extends BasePooledObjectFactory<String, RuntimeException> { int counter; @Override public String create() { return String.valueOf(counter++); } @Override public PooledObject<String> wrap(final String value) { return new DefaultPooledObject<>(value); } } @Override protected Object getNthObject(final int n) { return String.valueOf(n); } @Override protected boolean isFifo() { return false; } @Override protected boolean isLifo() { return false; } @Override protected <E extends Exception> ObjectPool<String, E> makeEmptyPool(final int cap) { return (ObjectPool<String, E>) new SoftReferenceObjectPool<>(new SimpleFactory()); } @Override protected <E extends Exception> ObjectPool<Object, E> makeEmptyPool(final PooledObjectFactory<Object, E> factory) { return new SoftReferenceObjectPool<>(factory); } }
5,223
0
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/impl/TestDefaultPooledObject.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.impl; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.lessThan; import static org.hamcrest.Matchers.lessThanOrEqualTo; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.commons.pool3.PooledObject; import org.junit.jupiter.api.Test; /** * Tests {@link DefaultPooledObject}. */ public class TestDefaultPooledObject { /** * JIRA: POOL-279 * * @throws Exception May occur in some failure modes */ @Test public void testGetIdleTimeMillis() throws Exception { final DefaultPooledObject<Object> dpo = new DefaultPooledObject<>(new Object()); final AtomicBoolean negativeIdleTimeReturned = new AtomicBoolean(false); final ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 3); final Runnable allocateAndDeallocateTask = () -> { for (int i1 = 0; i1 < 10000; i1++) { if (dpo.getIdleDuration().isNegative()) { negativeIdleTimeReturned.set(true); break; } if (dpo.getIdleDuration().isNegative()) { negativeIdleTimeReturned.set(true); break; } } dpo.allocate(); for (int i2 = 0; i2 < 10000; i2++) { if (dpo.getIdleDuration().isNegative()) { negativeIdleTimeReturned.set(true); break; } } dpo.deallocate(); }; final Runnable getIdleTimeTask = () -> { for (int i = 0; i < 10000; i++) { if (dpo.getIdleDuration().isNegative()) { negativeIdleTimeReturned.set(true); break; } } }; final double probabilityOfAllocationTask = 0.7; final List<Future<?>> futures = new ArrayList<>(); for (int i = 1; i <= 10000; i++) { final Runnable randomTask = Math.random() < probabilityOfAllocationTask ? allocateAndDeallocateTask : getIdleTimeTask; futures.add(executor.submit(randomTask)); } for (final Future<?> future : futures) { future.get(); } assertFalse(negativeIdleTimeReturned.get(), "DefaultPooledObject.getIdleTimeMillis() returned a negative value"); } @Test public void testInitialStateActiveDuration() throws InterruptedException { final PooledObject<Object> dpo = new DefaultPooledObject<>(new Object()); // Sleep MUST be "long enough" to test that we are not returning a negative time. // Need an API in Java 8 to get the clock granularity. Thread.sleep(200); // In the initial state, all instants are the creation instant: last borrow, last use, last return. // In the initial state, the active duration is the time between "now" and the creation time. // In the initial state, the idle duration is the time between "now" and the last return, which is the creation time. assertFalse(dpo.getActiveDuration().isNegative()); assertFalse(dpo.getActiveDuration().isZero()); // We use greaterThanOrEqualTo instead of equal because "now" many be different when each argument is evaluated. assertThat(1L, lessThanOrEqualTo(2L)); // sanity check assertThat(Duration.ZERO, lessThanOrEqualTo(Duration.ZERO.plusNanos(1))); // sanity check assertThat(dpo.getActiveDuration(), lessThanOrEqualTo(dpo.getIdleDuration())); // Deprecated assertThat(dpo.getActiveDuration(), lessThanOrEqualTo(dpo.getActiveDuration())); } @Test public void testInitialStateCreateInstant() { final PooledObject<Object> dpo = new DefaultPooledObject<>(new Object()); // In the initial state, all instants are the creation instant: last borrow, last use, last return. // Instant vs. Instant assertEquals(dpo.getCreateInstant(), dpo.getLastBorrowInstant()); assertEquals(dpo.getCreateInstant(), dpo.getLastReturnInstant()); assertEquals(dpo.getCreateInstant(), dpo.getLastUsedInstant()); assertEquals(dpo.getCreateInstant(), dpo.getCreateInstant()); } @Test public void testInitialStateDuration() throws InterruptedException { final PooledObject<Object> dpo = new DefaultPooledObject<>(new Object()); final Duration duration1 = dpo.getFullDuration(); assertNotNull(duration1); assertFalse(duration1.isNegative()); Thread.sleep(100); final Duration duration2 = dpo.getFullDuration(); assertNotNull(duration2); assertFalse(duration2.isNegative()); assertThat(duration1, lessThan(duration2)); } @Test public void testInitialStateIdleDuration() throws InterruptedException { final PooledObject<Object> dpo = new DefaultPooledObject<>(new Object()); // Sleep MUST be "long enough" to test that we are not returning a negative time. Thread.sleep(200); // In the initial state, all instants are the creation instant: last borrow, last use, last return. // In the initial state, the active duration is the time between "now" and the creation time. // In the initial state, the idle duration is the time between "now" and the last return, which is the creation time. assertFalse(dpo.getIdleDuration().isNegative()); assertFalse(dpo.getIdleDuration().isZero()); // We use greaterThanOrEqualTo instead of equal because "now" many be different when each argument is evaluated. assertThat(dpo.getIdleDuration(), lessThanOrEqualTo(dpo.getActiveDuration())); } }
5,224
0
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/impl/TestGenericObjectPool.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.impl; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.lessThanOrEqualTo; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import java.lang.management.ManagementFactory; import java.lang.ref.WeakReference; import java.nio.charset.UnsupportedCharsetException; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.NoSuchElementException; import java.util.Objects; import java.util.Random; import java.util.Set; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import javax.management.MBeanServer; import javax.management.ObjectName; import org.apache.commons.pool3.BasePooledObjectFactory; import org.apache.commons.pool3.ObjectPool; import org.apache.commons.pool3.PoolUtils; import org.apache.commons.pool3.PooledObject; import org.apache.commons.pool3.PooledObjectFactory; import org.apache.commons.pool3.SwallowedExceptionListener; import org.apache.commons.pool3.TestBaseObjectPool; import org.apache.commons.pool3.TestException; import org.apache.commons.pool3.VisitTracker; import org.apache.commons.pool3.VisitTrackerFactory; import org.apache.commons.pool3.Waiter; import org.apache.commons.pool3.WaiterFactory; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; /** */ public class TestGenericObjectPool extends TestBaseObjectPool { private final class ConcurrentBorrowAndEvictThread extends Thread { private final boolean borrow; public String obj; public ConcurrentBorrowAndEvictThread(final boolean borrow) { this.borrow = borrow; } @Override public void run() { try { if (borrow) { obj = genericObjectPool.borrowObject(); } else { genericObjectPool.evict(); } } catch (final Exception e) { // Ignore. } } } private static final class CreateErrorFactory extends BasePooledObjectFactory<String, InterruptedException> { private final Semaphore semaphore = new Semaphore(0); @Override public String create() throws InterruptedException { semaphore.acquire(); throw new UnknownError("wiggle"); } public boolean hasQueuedThreads() { return semaphore.hasQueuedThreads(); } public void release() { semaphore.release(); } @Override public PooledObject<String> wrap(final String obj) { return new DefaultPooledObject<>(obj); } } private static final class CreateFailFactory extends BasePooledObjectFactory<String, InterruptedException> { private final Semaphore semaphore = new Semaphore(0); @Override public String create() throws InterruptedException { semaphore.acquire(); throw new UnsupportedCharsetException("wibble"); } public boolean hasQueuedThreads() { return semaphore.hasQueuedThreads(); } public void release() { semaphore.release(); } @Override public PooledObject<String> wrap(final String obj) { return new DefaultPooledObject<>(obj); } } private static final class DummyFactory extends BasePooledObjectFactory<Object, RuntimeException> { @Override public Object create() { return null; } @Override public PooledObject<Object> wrap(final Object value) { return new DefaultPooledObject<>(value); } } private static final class EvictionThread<T, E extends Exception> extends Thread { private final GenericObjectPool<T, E> pool; public EvictionThread(final GenericObjectPool<T, E> pool) { this.pool = pool; } @Override public void run() { try { pool.evict(); } catch (final Exception e) { // Ignore } } } /** * Factory that creates HashSets. Note that this means * 0) All instances are initially equal (not discernible by equals) * 1) Instances are mutable and mutation can cause change in identity / hash code. */ private static final class HashSetFactory extends BasePooledObjectFactory<HashSet<String>, RuntimeException> { @Override public HashSet<String> create() { return new HashSet<>(); } @Override public PooledObject<HashSet<String>> wrap(final HashSet<String> value) { return new DefaultPooledObject<>(value); } } /** * Attempts to invalidate an object, swallowing IllegalStateException. */ static class InvalidateThread implements Runnable { private final String obj; private final ObjectPool<String, ? extends Exception> pool; private boolean done; public InvalidateThread(final ObjectPool<String, ? extends Exception> pool, final String obj) { this.obj = obj; this.pool = pool; } public boolean complete() { return done; } @Override public void run() { try { pool.invalidateObject(obj); } catch (final IllegalStateException ex) { // Ignore } catch (final Exception ex) { fail("Unexpected exception " + ex.toString()); } finally { done = true; } } } private static final class InvalidFactory extends BasePooledObjectFactory<Object, RuntimeException> { @Override public Object create() { return new Object(); } @Override public boolean validateObject(final PooledObject<Object> obj) { Waiter.sleepQuietly(1000); return false; } @Override public PooledObject<Object> wrap(final Object value) { return new DefaultPooledObject<>(value); } } public static class SimpleFactory implements PooledObjectFactory<String, TestException> { int makeCounter; int activationCounter; int validateCounter; int activeCount; boolean evenValid = true; boolean oddValid = true; boolean exceptionOnPassivate; boolean exceptionOnActivate; boolean exceptionOnDestroy; boolean exceptionOnValidate; boolean enableValidation = true; long destroyLatency; long makeLatency; long validateLatency; int maxTotal = Integer.MAX_VALUE; public SimpleFactory() { this(true); } public SimpleFactory(final boolean valid) { this(valid,valid); } public SimpleFactory(final boolean evalid, final boolean ovalid) { evenValid = evalid; oddValid = ovalid; } @Override public void activateObject(final PooledObject<String> obj) throws TestException { final boolean hurl; final boolean evenTest; final boolean oddTest; final int counter; synchronized (this) { hurl = exceptionOnActivate; evenTest = evenValid; oddTest = oddValid; counter = activationCounter++; } if (hurl && !(counter%2 == 0 ? evenTest : oddTest)) { throw new TestException(); } } @Override public void destroyObject(final PooledObject<String> obj) throws TestException { final long waitLatency; final boolean hurl; synchronized (this) { waitLatency = destroyLatency; hurl = exceptionOnDestroy; } if (waitLatency > 0) { doWait(waitLatency); } synchronized (this) { activeCount--; } if (hurl) { throw new TestException(); } } private void doWait(final long latency) { Waiter.sleepQuietly(latency); } public synchronized int getMakeCounter() { return makeCounter; } public synchronized boolean isThrowExceptionOnActivate() { return exceptionOnActivate; } public synchronized boolean isValidationEnabled() { return enableValidation; } @Override public PooledObject<String> makeObject() { final long waitLatency; synchronized (this) { activeCount++; if (activeCount > maxTotal) { throw new IllegalStateException( "Too many active instances: " + activeCount); } waitLatency = makeLatency; } if (waitLatency > 0) { doWait(waitLatency); } final int counter; synchronized (this) { counter = makeCounter++; } return new DefaultPooledObject<>(String.valueOf(counter)); } @Override public void passivateObject(final PooledObject<String> obj) throws TestException { final boolean hurl; synchronized (this) { hurl = exceptionOnPassivate; } if (hurl) { throw new TestException(); } } public synchronized void setDestroyLatency(final long destroyLatency) { this.destroyLatency = destroyLatency; } public synchronized void setEvenValid(final boolean valid) { evenValid = valid; } public synchronized void setMakeLatency(final long makeLatency) { this.makeLatency = makeLatency; } public synchronized void setMaxTotal(final int maxTotal) { this.maxTotal = maxTotal; } public synchronized void setOddValid(final boolean valid) { oddValid = valid; } public synchronized void setThrowExceptionOnActivate(final boolean b) { exceptionOnActivate = b; } public synchronized void setThrowExceptionOnDestroy(final boolean b) { exceptionOnDestroy = b; } public synchronized void setThrowExceptionOnPassivate(final boolean bool) { exceptionOnPassivate = bool; } public synchronized void setThrowExceptionOnValidate(final boolean bool) { exceptionOnValidate = bool; } public synchronized void setValid(final boolean valid) { setEvenValid(valid); setOddValid(valid); } public synchronized void setValidateLatency(final long validateLatency) { this.validateLatency = validateLatency; } public synchronized void setValidationEnabled(final boolean b) { enableValidation = b; } @Override public boolean validateObject(final PooledObject<String> obj) { final boolean validate; final boolean throwException; final boolean evenTest; final boolean oddTest; final long waitLatency; final int counter; synchronized (this) { validate = enableValidation; throwException = exceptionOnValidate; evenTest = evenValid; oddTest = oddValid; counter = validateCounter++; waitLatency = validateLatency; } if (waitLatency > 0) { doWait(waitLatency); } if (throwException) { throw new RuntimeException("validation failed"); } if (validate) { return counter%2 == 0 ? evenTest : oddTest; } return true; } } public static class TestEvictionPolicy<T> implements EvictionPolicy<T> { private final AtomicInteger callCount = new AtomicInteger(0); @Override public boolean evict(final EvictionConfig config, final PooledObject<T> underTest, final int idleCount) { return callCount.incrementAndGet() > 1500; } } static class TestThread<T, E extends Exception> implements Runnable { /** source of random delay times */ private final java.util.Random random; /** pool to borrow from */ private final ObjectPool<T, E> pool; /** number of borrow attempts */ private final int iter; /** delay before each borrow attempt */ private final int startDelay; /** time to hold each borrowed object before returning it */ private final int holdTime; /** whether or not start and hold time are randomly generated */ private final boolean randomDelay; /** object expected to be borrowed (fail otherwise) */ private final Object expectedObject; private volatile boolean complete; private volatile boolean failed; private volatile Throwable error; public TestThread(final ObjectPool<T, E> pool) { this(pool, 100, 50, true, null); } public TestThread(final ObjectPool<T, E> pool, final int iter) { this(pool, iter, 50, true, null); } public TestThread(final ObjectPool<T, E> pool, final int iter, final int delay) { this(pool, iter, delay, true, null); } public TestThread(final ObjectPool<T, E> pool, final int iter, final int delay, final boolean randomDelay) { this(pool, iter, delay, randomDelay, null); } public TestThread(final ObjectPool<T, E> pool, final int iter, final int delay, final boolean randomDelay, final Object obj) { this(pool, iter, delay, delay, randomDelay, obj); } public TestThread(final ObjectPool<T, E> pool, final int iter, final int startDelay, final int holdTime, final boolean randomDelay, final Object obj) { this.pool = pool; this.iter = iter; this.startDelay = startDelay; this.holdTime = holdTime; this.randomDelay = randomDelay; this.random = this.randomDelay ? new Random() : null; this.expectedObject = obj; } public boolean complete() { return complete; } public boolean failed() { return failed; } @Override public void run() { for (int i = 0; i < iter; i++) { final long actualStartDelay = randomDelay ? (long) random.nextInt(startDelay) : startDelay; final long actualHoldTime = randomDelay ? (long) random.nextInt(holdTime) : holdTime; Waiter.sleepQuietly(actualStartDelay); T obj = null; try { obj = pool.borrowObject(); } catch (final Exception e) { error = e; failed = true; complete = true; break; } if (expectedObject != null && !expectedObject.equals(obj)) { error = new Throwable("Expected: " + expectedObject + " found: " + obj); failed = true; complete = true; break; } Waiter.sleepQuietly(actualHoldTime); try { pool.returnObject(obj); } catch (final Exception e) { error = e; failed = true; complete = true; break; } } complete = true; } } /* * Very simple test thread that just tries to borrow an object from * the provided pool returns it after a wait */ static class WaitingTestThread<E extends Exception> extends Thread { private final GenericObjectPool<String, E> pool; private final long pause; private Throwable thrown; private long preBorrowMillis; // just before borrow private long postBorrowMillis; // borrow returned private long postReturnMillis; // after object was returned private long endedMillis; private String objectId; public WaitingTestThread(final GenericObjectPool<String, E> pool, final long pause) { this.pool = pool; this.pause = pause; this.thrown = null; } @Override public void run() { try { preBorrowMillis = System.currentTimeMillis(); final String obj = pool.borrowObject(); objectId = obj; postBorrowMillis = System.currentTimeMillis(); Thread.sleep(pause); pool.returnObject(obj); postReturnMillis = System.currentTimeMillis(); } catch (final Throwable e) { thrown = e; } finally{ endedMillis = System.currentTimeMillis(); } } } private static final boolean DISPLAY_THREAD_DETAILS= Boolean.getBoolean("TestGenericObjectPool.display.thread.details"); // To pass this to a Maven test, use: // mvn test -DargLine="-DTestGenericObjectPool.display.thread.details=true" // @see https://issues.apache.org/jira/browse/SUREFIRE-121 protected GenericObjectPool<String, TestException> genericObjectPool; private SimpleFactory simpleFactory; private void assertConfiguration(final GenericObjectPoolConfig<?> expected, final GenericObjectPool<?, ?> actual) { assertEquals(Boolean.valueOf(expected.getTestOnCreate()), Boolean.valueOf(actual.getTestOnCreate()), "testOnCreate"); assertEquals(Boolean.valueOf(expected.getTestOnBorrow()), Boolean.valueOf(actual.getTestOnBorrow()), "testOnBorrow"); assertEquals(Boolean.valueOf(expected.getTestOnReturn()), Boolean.valueOf(actual.getTestOnReturn()), "testOnReturn"); assertEquals(Boolean.valueOf(expected.getTestWhileIdle()), Boolean.valueOf(actual.getTestWhileIdle()), "testWhileIdle"); assertEquals(Boolean.valueOf(expected.getBlockWhenExhausted()), Boolean.valueOf(actual.getBlockWhenExhausted()), "whenExhaustedAction"); assertEquals(expected.getMaxTotal(), actual.getMaxTotal(), "maxTotal"); assertEquals(expected.getMaxIdle(), actual.getMaxIdle(), "maxIdle"); assertEquals(expected.getMaxWaitDuration(), actual.getMaxWaitDuration(), "maxWaitDuration"); assertEquals(expected.getMinEvictableIdleDuration(), actual.getMinEvictableIdleDuration(), "minEvictableIdleDuration"); assertEquals(expected.getNumTestsPerEvictionRun(), actual.getNumTestsPerEvictionRun(), "numTestsPerEvictionRun"); assertEquals(expected.getEvictorShutdownTimeoutDuration(), actual.getEvictorShutdownTimeoutDuration(), "evictorShutdownTimeoutDuration"); } private void checkEvict(final boolean lifo) throws Exception { // yea this is hairy but it tests all the code paths in GOP.evict() genericObjectPool.setSoftMinEvictableIdleDuration(Duration.ofMillis(10)); genericObjectPool.setMinIdle(2); genericObjectPool.setTestWhileIdle(true); genericObjectPool.setLifo(lifo); genericObjectPool.addObjects(5); genericObjectPool.evict(); simpleFactory.setEvenValid(false); simpleFactory.setOddValid(false); simpleFactory.setThrowExceptionOnActivate(true); genericObjectPool.evict(); genericObjectPool.addObjects(5); simpleFactory.setThrowExceptionOnActivate(false); simpleFactory.setThrowExceptionOnPassivate(true); genericObjectPool.evict(); simpleFactory.setThrowExceptionOnPassivate(false); simpleFactory.setEvenValid(true); simpleFactory.setOddValid(true); Thread.sleep(125); genericObjectPool.evict(); assertEquals(2, genericObjectPool.getNumIdle()); } private void checkEvictionOrder(final boolean lifo) throws Exception { checkEvictionOrderPart1(lifo); tearDown(); setUp(); checkEvictionOrderPart2(lifo); } private void checkEvictionOrderPart1(final boolean lifo) throws Exception { genericObjectPool.setNumTestsPerEvictionRun(2); genericObjectPool.setMinEvictableIdleDuration(Duration.ofMillis(100)); genericObjectPool.setLifo(lifo); for (int i = 0; i < 5; i++) { genericObjectPool.addObject(); Thread.sleep(100); } // Order, oldest to youngest, is "0", "1", ...,"4" genericObjectPool.evict(); // Should evict "0" and "1" final Object obj = genericObjectPool.borrowObject(); assertNotEquals("0", obj, "oldest not evicted"); assertNotEquals("1", obj, "second oldest not evicted"); // 2 should be next out for FIFO, 4 for LIFO assertEquals(lifo ? "4" : "2" , obj,"Wrong instance returned"); } private void checkEvictionOrderPart2(final boolean lifo) throws Exception { // Two eviction runs in sequence genericObjectPool.setNumTestsPerEvictionRun(2); genericObjectPool.setMinEvictableIdleDuration(Duration.ofMillis(100)); genericObjectPool.setLifo(lifo); for (int i = 0; i < 5; i++) { genericObjectPool.addObject(); Thread.sleep(100); } genericObjectPool.evict(); // Should evict "0" and "1" genericObjectPool.evict(); // Should evict "2" and "3" final Object obj = genericObjectPool.borrowObject(); assertEquals("4", obj,"Wrong instance remaining in pool"); } private void checkEvictorVisiting(final boolean lifo) throws Exception { VisitTracker<Object> obj; VisitTrackerFactory<Object> trackerFactory = new VisitTrackerFactory<>(); try (GenericObjectPool<VisitTracker<Object>,RuntimeException> trackerPool = new GenericObjectPool<>(trackerFactory)) { trackerPool.setNumTestsPerEvictionRun(2); trackerPool.setMinEvictableIdleDuration(Duration.ofMillis(-1)); trackerPool.setTestWhileIdle(true); trackerPool.setLifo(lifo); trackerPool.setTestOnReturn(false); trackerPool.setTestOnBorrow(false); for (int i = 0; i < 8; i++) { trackerPool.addObject(); } trackerPool.evict(); // Visit oldest 2 - 0 and 1 obj = trackerPool.borrowObject(); trackerPool.returnObject(obj); obj = trackerPool.borrowObject(); trackerPool.returnObject(obj); // borrow, return, borrow, return // FIFO will move 0 and 1 to end // LIFO, 7 out, then in, then out, then in trackerPool.evict(); // Should visit 2 and 3 in either case for (int i = 0; i < 8; i++) { final VisitTracker<Object> tracker = trackerPool.borrowObject(); if (tracker.getId() >= 4) { assertEquals( 0, tracker.getValidateCount(),"Unexpected instance visited " + tracker.getId()); } else { assertEquals( 1, tracker.getValidateCount(), "Instance " + tracker.getId() + " visited wrong number of times."); } } } trackerFactory = new VisitTrackerFactory<>(); try (GenericObjectPool<VisitTracker<Object>, RuntimeException> trackerPool = new GenericObjectPool<>(trackerFactory)) { trackerPool.setNumTestsPerEvictionRun(3); trackerPool.setMinEvictableIdleDuration(Duration.ofMillis(-1)); trackerPool.setTestWhileIdle(true); trackerPool.setLifo(lifo); trackerPool.setTestOnReturn(false); trackerPool.setTestOnBorrow(false); for (int i = 0; i < 8; i++) { trackerPool.addObject(); } trackerPool.evict(); // 0, 1, 2 trackerPool.evict(); // 3, 4, 5 obj = trackerPool.borrowObject(); trackerPool.returnObject(obj); obj = trackerPool.borrowObject(); trackerPool.returnObject(obj); obj = trackerPool.borrowObject(); trackerPool.returnObject(obj); // borrow, return, borrow, return // FIFO 3,4,5,6,7,0,1,2 // LIFO 7,6,5,4,3,2,1,0 // In either case, pointer should be at 6 trackerPool.evict(); // Should hit 6,7,0 - 0 for second time for (int i = 0; i < 8; i++) { final VisitTracker<Object> tracker = trackerPool.borrowObject(); if (tracker.getId() != 0) { assertEquals( 1, tracker.getValidateCount(), "Instance " + tracker.getId() + " visited wrong number of times."); } else { assertEquals( 2, tracker.getValidateCount(), "Instance " + tracker.getId() + " visited wrong number of times."); } } } // Randomly generate a pools with random numTests // and make sure evictor cycles through elements appropriately final int[] smallPrimes = { 2, 3, 5, 7 }; final Random random = new Random(); random.setSeed(System.currentTimeMillis()); for (int i = 0; i < 4; i++) { for (int j = 0; j < 5; j++) { try (GenericObjectPool<VisitTracker<Object>, RuntimeException> trackerPool = new GenericObjectPool<>(trackerFactory)) { trackerPool.setNumTestsPerEvictionRun(smallPrimes[i]); trackerPool.setMinEvictableIdleDuration(Duration.ofMillis(-1)); trackerPool.setTestWhileIdle(true); trackerPool.setLifo(lifo); trackerPool.setTestOnReturn(false); trackerPool.setTestOnBorrow(false); trackerPool.setMaxIdle(-1); final int instanceCount = 10 + random.nextInt(20); trackerPool.setMaxTotal(instanceCount); for (int k = 0; k < instanceCount; k++) { trackerPool.addObject(); } // Execute a random number of evictor runs final int runs = 10 + random.nextInt(50); for (int k = 0; k < runs; k++) { trackerPool.evict(); } // Number of times evictor should have cycled through the pool final int cycleCount = runs * trackerPool.getNumTestsPerEvictionRun() / instanceCount; // Look at elements and make sure they are visited cycleCount // or cycleCount + 1 times VisitTracker<Object> tracker = null; int visitCount = 0; for (int k = 0; k < instanceCount; k++) { tracker = trackerPool.borrowObject(); assertTrue(trackerPool.getNumActive() <= trackerPool.getMaxTotal()); visitCount = tracker.getValidateCount(); assertTrue(visitCount >= cycleCount && visitCount <= cycleCount + 1); } } } } } private BasePooledObjectFactory<String, RuntimeException> createDefaultPooledObjectFactory() { return new BasePooledObjectFactory<String, RuntimeException>() { @Override public String create() { // fake return null; } @Override public PooledObject<String> wrap(final String obj) { // fake return new DefaultPooledObject<>(obj); } }; } private BasePooledObjectFactory<String, RuntimeException> createNullPooledObjectFactory() { return new BasePooledObjectFactory<String, RuntimeException>() { @Override public String create() { // fake return null; } @Override public PooledObject<String> wrap(final String obj) { // fake return null; } }; } private BasePooledObjectFactory<String, InterruptedException> createSlowObjectFactory(final long elapsedTimeMillis) { return new BasePooledObjectFactory<String, InterruptedException>() { @Override public String create() throws InterruptedException { Thread.sleep(elapsedTimeMillis); return "created"; } @Override public PooledObject<String> wrap(final String obj) { // fake return new DefaultPooledObject<>(obj); } }; } @Override protected Object getNthObject(final int n) { return String.valueOf(n); } @Override protected boolean isFifo() { return false; } @Override protected boolean isLifo() { return true; } @Override protected ObjectPool<String, TestException> makeEmptyPool(final int minCap) { final GenericObjectPool<String, TestException> mtPool = new GenericObjectPool<>(new SimpleFactory()); mtPool.setMaxTotal(minCap); mtPool.setMaxIdle(minCap); return mtPool; } @Override protected <E extends Exception> ObjectPool<Object, E> makeEmptyPool(final PooledObjectFactory<Object, E> fac) { return new GenericObjectPool<>(fac); } /** * Kicks off <numThreads> test threads, each of which will go through * <iterations> borrow-return cycles with random delay times <= delay * in between. */ private <T, E extends Exception> void runTestThreads(final int numThreads, final int iterations, final int delay, final GenericObjectPool<T, E> testPool) { final TestThread<T, E>[] threads = new TestThread[numThreads]; for (int i = 0; i < numThreads; i++) { threads[i] = new TestThread<>(testPool, iterations, delay); final Thread t = new Thread(threads[i]); t.start(); } for (int i = 0; i < numThreads; i++) { while (!threads[i].complete()) { Waiter.sleepQuietly(500L); } if (threads[i].failed()) { fail("Thread " + i + " failed: " + threads[i].error.toString()); } } } @BeforeEach public void setUp() { simpleFactory = new SimpleFactory(); genericObjectPool = new GenericObjectPool<>(simpleFactory); } @AfterEach public void tearDown() throws Exception { final ObjectName jmxName = genericObjectPool.getJmxName(); final String poolName = Objects.toString(jmxName, null); genericObjectPool.clear(); genericObjectPool.close(); genericObjectPool = null; simpleFactory = null; final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); final Set<ObjectName> result = mbs.queryNames(new ObjectName("org.apache.commoms.pool3:type=GenericObjectPool,*"), null); // There should be no registered pools at this point final int registeredPoolCount = result.size(); final StringBuilder msg = new StringBuilder("Current pool is: "); msg.append(poolName); msg.append(" Still open pools are: "); for (final ObjectName name : result) { // Clean these up ready for the next test msg.append(name.toString()); msg.append(" created via\n"); msg.append(mbs.getAttribute(name, "CreationStackTrace")); msg.append('\n'); mbs.unregisterMBean(name); } assertEquals(0, registeredPoolCount, msg.toString()); // Make sure that EvictionTimer executor is shut down. Thread.yield(); if (EvictionTimer.getExecutor() != null) { Thread.sleep(1000); } assertNull(EvictionTimer.getExecutor(), "EvictionTimer.getExecutor()"); } /** * Check that a pool that starts an evictor, but is never closed does not leave EvictionTimer executor running. Confirmation check is in * {@link #tearDown()}. * * @throws TestException Custom exception * @throws InterruptedException if any thread has interrupted the current thread. The <em>interrupted status</em> of the current thread is cleared when this * exception is thrown. */ @SuppressWarnings("deprecation") @Test public void testAbandonedPool() throws TestException, InterruptedException { final GenericObjectPoolConfig<String> config = new GenericObjectPoolConfig<>(); config.setJmxEnabled(false); GenericObjectPool<String, TestException> abandoned = new GenericObjectPool<>(simpleFactory, config); abandoned.setDurationBetweenEvictionRuns(Duration.ofMillis(100)); // Starts evictor assertEquals(abandoned.getRemoveAbandonedTimeoutDuration(), abandoned.getRemoveAbandonedTimeoutDuration()); // This is ugly, but forces GC to hit the pool final WeakReference<GenericObjectPool<String, TestException>> ref = new WeakReference<>(abandoned); abandoned = null; while (ref.get() != null) { System.gc(); Thread.sleep(100); } } @Test @Timeout(value = 60000, unit = TimeUnit.MILLISECONDS) public void testAddObject() throws Exception { assertEquals( 0, genericObjectPool.getNumIdle(),"should be zero idle"); genericObjectPool.addObject(); assertEquals( 1, genericObjectPool.getNumIdle(),"should be one idle"); assertEquals( 0, genericObjectPool.getNumActive(),"should be zero active"); final String obj = genericObjectPool.borrowObject(); assertEquals( 0, genericObjectPool.getNumIdle(),"should be zero idle"); assertEquals( 1, genericObjectPool.getNumActive(),"should be one active"); genericObjectPool.returnObject(obj); assertEquals( 1, genericObjectPool.getNumIdle(),"should be one idle"); assertEquals( 0, genericObjectPool.getNumActive(),"should be zero active"); } @Test public void testAppendStats() { assertFalse(genericObjectPool.getMessageStatistics()); assertEquals("foo", genericObjectPool.appendStats("foo")); try (final GenericObjectPool<?, TestException> pool = new GenericObjectPool<>(new SimpleFactory())) { pool.setMessagesStatistics(true); assertNotEquals("foo", pool.appendStats("foo")); pool.setMessagesStatistics(false); assertEquals("foo", pool.appendStats("foo")); } } /* * Note: This test relies on timing for correct execution. There *should* be * enough margin for this to work correctly on most (all?) systems but be * aware of this if you see a failure of this test. */ @SuppressWarnings({ "rawtypes", "unchecked" }) @Test @Timeout(value = 60000, unit = TimeUnit.MILLISECONDS) public void testBorrowObjectFairness() throws Exception { final int numThreads = 40; final int maxTotal = 40; final GenericObjectPoolConfig config = new GenericObjectPoolConfig(); config.setMaxTotal(maxTotal); config.setMaxIdle(maxTotal); config.setFairness(true); config.setLifo(false); genericObjectPool = new GenericObjectPool(simpleFactory, config); // Exhaust the pool final String[] objects = new String[maxTotal]; for (int i = 0; i < maxTotal; i++) { objects[i] = genericObjectPool.borrowObject(); } // Start and park threads waiting to borrow objects final TestThread[] threads = new TestThread[numThreads]; for(int i=0;i<numThreads;i++) { threads[i] = new TestThread(genericObjectPool, 1, 0, 2000, false, String.valueOf(i % maxTotal)); final Thread t = new Thread(threads[i]); t.start(); // Short delay to ensure threads start in correct order Thread.sleep(10); } // Return objects, other threads should get served in order for (int i = 0; i < maxTotal; i++) { genericObjectPool.returnObject(objects[i]); } // Wait for threads to finish for (int i = 0; i < numThreads; i++) { while (!threads[i].complete()) { Waiter.sleepQuietly(500L); } if (threads[i].failed()) { fail("Thread " + i + " failed: " + threads[i].error.toString()); } } } @Test public void testBorrowTimings() throws Exception { // Borrow final String object = genericObjectPool.borrowObject(); final PooledObject<String> po = genericObjectPool.getPooledObject(object); // In the initial state, all instants are the creation instant: last borrow, last use, last return. // In the initial state, the active duration is the time between "now" and the creation time. // In the initial state, the idle duration is the time between "now" and the last return, which is the creation time. // But... this PO might have already been used in other tests in this class. final Instant lastBorrowInstant1 = po.getLastBorrowInstant(); final Instant lastReturnInstant1 = po.getLastReturnInstant(); final Instant lastUsedInstant1 = po.getLastUsedInstant(); assertThat(po.getCreateInstant(), lessThanOrEqualTo(lastBorrowInstant1)); assertThat(po.getCreateInstant(), lessThanOrEqualTo(lastReturnInstant1)); assertThat(po.getCreateInstant(), lessThanOrEqualTo(lastUsedInstant1)); // Sleep MUST be "long enough" to detect that more than 0 milliseconds have elapsed. // Need an API in Java 8 to get the clock granularity. Thread.sleep(200); assertFalse(po.getActiveDuration().isNegative()); assertFalse(po.getActiveDuration().isZero()); // We use greaterThanOrEqualTo instead of equal because "now" many be different when each argument is evaluated. assertThat(1L, lessThanOrEqualTo(2L)); // sanity check assertThat(Duration.ZERO, lessThanOrEqualTo(Duration.ZERO.plusNanos(1))); // sanity check assertThat(po.getActiveDuration(), lessThanOrEqualTo(po.getIdleDuration())); // Deprecated assertThat(po.getActiveDuration(), lessThanOrEqualTo(po.getActiveDuration())); // // TODO How to compare ID with AD since other tests may have touched the PO? assertThat(po.getActiveDuration(), lessThanOrEqualTo(po.getIdleDuration())); // assertThat(po.getCreateInstant(), lessThanOrEqualTo(po.getLastBorrowInstant())); assertThat(po.getCreateInstant(), lessThanOrEqualTo(po.getLastReturnInstant())); assertThat(po.getCreateInstant(), lessThanOrEqualTo(po.getLastUsedInstant())); assertThat(lastBorrowInstant1, lessThanOrEqualTo(po.getLastBorrowInstant())); assertThat(lastReturnInstant1, lessThanOrEqualTo(po.getLastReturnInstant())); assertThat(lastUsedInstant1, lessThanOrEqualTo(po.getLastUsedInstant())); genericObjectPool.returnObject(object); assertFalse(po.getActiveDuration().isNegative()); assertFalse(po.getActiveDuration().isZero()); assertThat(po.getActiveDuration(), lessThanOrEqualTo(po.getActiveDuration())); assertThat(lastBorrowInstant1, lessThanOrEqualTo(po.getLastBorrowInstant())); assertThat(lastReturnInstant1, lessThanOrEqualTo(po.getLastReturnInstant())); assertThat(lastUsedInstant1, lessThanOrEqualTo(po.getLastUsedInstant())); } /** * On first borrow, first object fails validation, second object is OK. * Subsequent borrows are OK. This was POOL-152. * @throws Exception */ @Test @Timeout(value = 60000, unit = TimeUnit.MILLISECONDS) public void testBrokenFactoryShouldNotBlockPool() throws Exception { final int maxTotal = 1; simpleFactory.setMaxTotal(maxTotal); genericObjectPool.setMaxTotal(maxTotal); genericObjectPool.setBlockWhenExhausted(true); genericObjectPool.setTestOnBorrow(true); // First borrow object will need to create a new object which will fail // validation. String obj = null; Exception ex = null; simpleFactory.setValid(false); try { obj = genericObjectPool.borrowObject(); } catch (final Exception e) { ex = e; } // Failure expected assertNotNull(ex); assertTrue(ex instanceof NoSuchElementException); assertNull(obj); // Configure factory to create valid objects so subsequent borrows work simpleFactory.setValid(true); // Subsequent borrows should be OK obj = genericObjectPool.borrowObject(); assertNotNull(obj); genericObjectPool.returnObject(obj); } // POOL-259 @Test public void testClientWaitStats() throws TestException { final SimpleFactory factory = new SimpleFactory(); // Give makeObject a little latency factory.setMakeLatency(200); try (final GenericObjectPool<String, TestException> pool = new GenericObjectPool<>(factory, new GenericObjectPoolConfig<>())) { final String s = pool.borrowObject(); // First borrow waits on create, so wait time should be at least 200 ms // Allow 100ms error in clock times assertTrue(pool.getMaxBorrowWaitTimeMillis() >= 100); assertTrue(pool.getMeanBorrowWaitTimeMillis() >= 100); pool.returnObject(s); pool.borrowObject(); // Second borrow does not have to wait on create, average should be about 100 assertTrue(pool.getMaxBorrowWaitTimeMillis() > 100); assertTrue(pool.getMeanBorrowWaitTimeMillis() < 200); assertTrue(pool.getMeanBorrowWaitTimeMillis() > 20); } } @Test @Timeout(value = 60000, unit = TimeUnit.MILLISECONDS) public void testCloseMultiplePools1() { try (final GenericObjectPool<String, TestException> genericObjectPool2 = new GenericObjectPool<>(simpleFactory)) { genericObjectPool.setDurationBetweenEvictionRuns(TestConstants.ONE_MILLISECOND_DURATION); genericObjectPool2.setDurationBetweenEvictionRuns(TestConstants.ONE_MILLISECOND_DURATION); } genericObjectPool.close(); } @Test @Timeout(value = 60000, unit = TimeUnit.MILLISECONDS) public void testCloseMultiplePools2() throws Exception { try (final GenericObjectPool<String, TestException> genericObjectPool2 = new GenericObjectPool<>(simpleFactory)) { // Ensure eviction takes a long time, during which time EvictionTimer.executor's queue is empty simpleFactory.setDestroyLatency(1000L); // Ensure there is an object to evict, so that above latency takes effect genericObjectPool.setDurationBetweenEvictionRuns(TestConstants.ONE_MILLISECOND_DURATION); genericObjectPool2.setDurationBetweenEvictionRuns(TestConstants.ONE_MILLISECOND_DURATION); genericObjectPool.setMinEvictableIdleDuration(TestConstants.ONE_MILLISECOND_DURATION); genericObjectPool2.setMinEvictableIdleDuration(TestConstants.ONE_MILLISECOND_DURATION); genericObjectPool.addObject(); genericObjectPool2.addObject(); // Close both pools } genericObjectPool.close(); } @Test @Timeout(value = 60000, unit = TimeUnit.MILLISECONDS) public void testConcurrentBorrowAndEvict() throws Exception { genericObjectPool.setMaxTotal(1); genericObjectPool.addObject(); for (int i = 0; i < 5000; i++) { final ConcurrentBorrowAndEvictThread one = new ConcurrentBorrowAndEvictThread(true); final ConcurrentBorrowAndEvictThread two = new ConcurrentBorrowAndEvictThread(false); one.start(); two.start(); one.join(); two.join(); genericObjectPool.returnObject(one.obj); /* Uncomment this for a progress indication if (i % 10 == 0) { System.out.println(i/10); } */ } } /** * POOL-231 - verify that concurrent invalidates of the same object do not * corrupt pool destroyCount. * * @throws Exception May occur in some failure modes */ @Test public void testConcurrentInvalidate() throws Exception { // Get allObjects and idleObjects loaded with some instances final int nObjects = 1000; genericObjectPool.setMaxTotal(nObjects); genericObjectPool.setMaxIdle(nObjects); final String[] obj = new String[nObjects]; for (int i = 0; i < nObjects; i++) { obj[i] = genericObjectPool.borrowObject(); } for (int i = 0; i < nObjects; i++) { if (i % 2 == 0) { genericObjectPool.returnObject(obj[i]); } } final int nThreads = 20; final int nIterations = 60; final InvalidateThread[] threads = new InvalidateThread[nThreads]; // Randomly generated list of distinct invalidation targets final ArrayList<Integer> targets = new ArrayList<>(); final Random random = new Random(); for (int j = 0; j < nIterations; j++) { // Get a random invalidation target Integer targ = Integer.valueOf(random.nextInt(nObjects)); while (targets.contains(targ)) { targ = Integer.valueOf(random.nextInt(nObjects)); } targets.add(targ); // Launch nThreads threads all trying to invalidate the target for (int i = 0; i < nThreads; i++) { threads[i] = new InvalidateThread(genericObjectPool, obj[targ.intValue()]); } for (int i = 0; i < nThreads; i++) { new Thread(threads[i]).start(); } boolean done = false; while (!done) { done = true; for (int i = 0; i < nThreads; i++) { done = done && threads[i].complete(); } Thread.sleep(100); } } assertEquals(nIterations, genericObjectPool.getDestroyedCount()); } @Test public void testConstructorNullFactory() { // add dummy assert (won't be invoked because of IAE) to avoid "unused" warning assertThrows(IllegalArgumentException.class, () -> new GenericObjectPool<>(null)); } @Test @Timeout(value = 60000, unit = TimeUnit.MILLISECONDS) public void testConstructors() { // Make constructor arguments all different from defaults final int minIdle = 2; final Duration maxWaitDuration = Duration.ofMillis(3); final int maxIdle = 4; final int maxTotal = 5; final Duration minEvictableIdleDuration = Duration.ofMillis(6); final long minEvictableIdleMillis = minEvictableIdleDuration.toMillis(); final int numTestsPerEvictionRun = 7; final boolean testOnBorrow = true; final boolean testOnReturn = true; final boolean testWhileIdle = true; final long timeBetweenEvictionRunsMillis = 8; final Duration durationBetweenEvictionRuns = Duration.ofMillis(timeBetweenEvictionRunsMillis); final boolean blockWhenExhausted = false; final boolean lifo = false; final PooledObjectFactory<Object, RuntimeException> dummyFactory = new DummyFactory(); try (GenericObjectPool<Object, RuntimeException> dummyPool = new GenericObjectPool<>(dummyFactory)) { assertEquals(GenericObjectPoolConfig.DEFAULT_MAX_IDLE, dummyPool.getMaxIdle()); assertEquals(BaseObjectPoolConfig.DEFAULT_MAX_WAIT, dummyPool.getMaxWaitDuration()); assertEquals(GenericObjectPoolConfig.DEFAULT_MIN_IDLE, dummyPool.getMinIdle()); assertEquals(GenericObjectPoolConfig.DEFAULT_MAX_TOTAL, dummyPool.getMaxTotal()); assertEquals(BaseObjectPoolConfig.DEFAULT_MIN_EVICTABLE_IDLE_DURATION, dummyPool.getMinEvictableIdleDuration()); assertEquals(BaseObjectPoolConfig.DEFAULT_NUM_TESTS_PER_EVICTION_RUN, dummyPool.getNumTestsPerEvictionRun()); assertEquals(Boolean.valueOf(BaseObjectPoolConfig.DEFAULT_TEST_ON_BORROW), Boolean.valueOf(dummyPool.getTestOnBorrow())); assertEquals(Boolean.valueOf(BaseObjectPoolConfig.DEFAULT_TEST_ON_RETURN), Boolean.valueOf(dummyPool.getTestOnReturn())); assertEquals(Boolean.valueOf(BaseObjectPoolConfig.DEFAULT_TEST_WHILE_IDLE), Boolean.valueOf(dummyPool.getTestWhileIdle())); assertEquals(BaseObjectPoolConfig.DEFAULT_DURATION_BETWEEN_EVICTION_RUNS, dummyPool.getDurationBetweenEvictionRuns()); assertEquals(Boolean.valueOf(BaseObjectPoolConfig.DEFAULT_BLOCK_WHEN_EXHAUSTED), Boolean.valueOf(dummyPool.getBlockWhenExhausted())); assertEquals(Boolean.valueOf(BaseObjectPoolConfig.DEFAULT_LIFO), Boolean.valueOf(dummyPool.getLifo())); } final GenericObjectPoolConfig<Object> config = new GenericObjectPoolConfig<>(); config.setLifo(lifo); config.setMaxIdle(maxIdle); config.setMinIdle(minIdle); config.setMaxTotal(maxTotal); config.setMaxWait(maxWaitDuration); config.setMinEvictableIdleDuration(minEvictableIdleDuration); assertEquals(minEvictableIdleMillis, config.getMinEvictableIdleDuration().toMillis()); config.setNumTestsPerEvictionRun(numTestsPerEvictionRun); config.setTestOnBorrow(testOnBorrow); config.setTestOnReturn(testOnReturn); config.setTestWhileIdle(testWhileIdle); config.setDurationBetweenEvictionRuns(durationBetweenEvictionRuns); assertEquals(timeBetweenEvictionRunsMillis, config.getDurationBetweenEvictionRuns().toMillis()); config.setBlockWhenExhausted(blockWhenExhausted); try (GenericObjectPool<Object, RuntimeException> dummyPool = new GenericObjectPool<>(dummyFactory, config)) { assertEquals(maxIdle, dummyPool.getMaxIdle()); assertEquals(maxWaitDuration, dummyPool.getMaxWaitDuration()); assertEquals(minIdle, dummyPool.getMinIdle()); assertEquals(maxTotal, dummyPool.getMaxTotal()); assertEquals(minEvictableIdleDuration, dummyPool.getMinEvictableIdleDuration()); assertEquals(numTestsPerEvictionRun, dummyPool.getNumTestsPerEvictionRun()); assertEquals(Boolean.valueOf(testOnBorrow), Boolean.valueOf(dummyPool.getTestOnBorrow())); assertEquals(Boolean.valueOf(testOnReturn), Boolean.valueOf(dummyPool.getTestOnReturn())); assertEquals(Boolean.valueOf(testWhileIdle), Boolean.valueOf(dummyPool.getTestWhileIdle())); assertEquals(durationBetweenEvictionRuns, dummyPool.getDurationBetweenEvictionRuns()); assertEquals(Boolean.valueOf(blockWhenExhausted), Boolean.valueOf(dummyPool.getBlockWhenExhausted())); assertEquals(Boolean.valueOf(lifo), Boolean.valueOf(dummyPool.getLifo())); } } @Test @Timeout(value = 60000, unit = TimeUnit.MILLISECONDS) public void testDefaultConfiguration() { assertConfiguration(new GenericObjectPoolConfig<>(),genericObjectPool); } /** * Verifies that when a factory's makeObject produces instances that are not * discernible by equals, the pool can handle them. * * JIRA: POOL-283 */ @Test public void testEqualsIndiscernible() throws Exception { final HashSetFactory factory = new HashSetFactory(); try (final GenericObjectPool<HashSet<String>, RuntimeException> pool = new GenericObjectPool<>(factory, new GenericObjectPoolConfig<>())) { final HashSet<String> s1 = pool.borrowObject(); final HashSet<String> s2 = pool.borrowObject(); pool.returnObject(s1); pool.returnObject(s2); } } @Test public void testErrorFactoryDoesNotBlockThreads() throws Exception { final CreateErrorFactory factory = new CreateErrorFactory(); try (final GenericObjectPool<String, InterruptedException> createFailFactoryPool = new GenericObjectPool<>(factory)) { createFailFactoryPool.setMaxTotal(1); // Try and borrow the first object from the pool final WaitingTestThread<InterruptedException> thread1 = new WaitingTestThread<>(createFailFactoryPool, 0); thread1.start(); // Wait for thread to reach semaphore while (!factory.hasQueuedThreads()) { Thread.sleep(200); } // Try and borrow the second object from the pool final WaitingTestThread<InterruptedException> thread2 = new WaitingTestThread<>(createFailFactoryPool, 0); thread2.start(); // Pool will not call factory since maximum number of object creations // are already queued. // Thread 2 will wait on an object being returned to the pool // Give thread 2 a chance to reach this state Thread.sleep(1000); // Release thread1 factory.release(); // Pre-release thread2 factory.release(); // Both threads should now complete. boolean threadRunning = true; int count = 0; while (threadRunning && count < 15) { threadRunning = thread1.isAlive(); threadRunning = thread2.isAlive(); Thread.sleep(200); count++; } assertFalse(thread1.isAlive()); assertFalse(thread2.isAlive()); assertTrue(thread1.thrown instanceof UnknownError); assertTrue(thread2.thrown instanceof UnknownError); } } /** * Tests addObject contention between ensureMinIdle triggered by * the Evictor with minIdle &gt; 0 and borrowObject. * * @throws Exception May occur in some failure modes */ @Test @Timeout(value = 60000, unit = TimeUnit.MILLISECONDS) public void testEvictAddObjects() throws Exception { simpleFactory.setMakeLatency(300); simpleFactory.setMaxTotal(2); genericObjectPool.setMaxTotal(2); genericObjectPool.setMinIdle(1); genericObjectPool.borrowObject(); // numActive = 1, numIdle = 0 // Create a test thread that will run once and try a borrow after // 150ms fixed delay final TestThread<String, TestException> borrower = new TestThread<>(genericObjectPool, 1, 150, false); final Thread borrowerThread = new Thread(borrower); // Set evictor to run in 100 ms - will create idle instance genericObjectPool.setDurationBetweenEvictionRuns(Duration.ofMillis(100)); borrowerThread.start(); // Off to the races borrowerThread.join(); assertFalse(borrower.failed()); } @Test @Timeout(value = 60000, unit = TimeUnit.MILLISECONDS) public void testEvictFIFO() throws Exception { checkEvict(false); } @Test @Timeout(value = 60000, unit = TimeUnit.MILLISECONDS) public void testEviction() throws Exception { genericObjectPool.setMaxIdle(500); genericObjectPool.setMaxTotal(500); genericObjectPool.setNumTestsPerEvictionRun(100); genericObjectPool.setMinEvictableIdleDuration(Duration.ofMillis(250)); genericObjectPool.setDurationBetweenEvictionRuns(Duration.ofMillis(500)); genericObjectPool.setTestWhileIdle(true); final String[] active = new String[500]; for (int i = 0; i < 500; i++) { active[i] = genericObjectPool.borrowObject(); } for (int i = 0; i < 500; i++) { genericObjectPool.returnObject(active[i]); } Waiter.sleepQuietly(1000L); assertTrue(genericObjectPool.getNumIdle() < 500,"Should be less than 500 idle, found " + genericObjectPool.getNumIdle()); Waiter.sleepQuietly(600L); assertTrue(genericObjectPool.getNumIdle() < 400,"Should be less than 400 idle, found " + genericObjectPool.getNumIdle()); Waiter.sleepQuietly(600L); assertTrue(genericObjectPool.getNumIdle() < 300,"Should be less than 300 idle, found " + genericObjectPool.getNumIdle()); Waiter.sleepQuietly(600L); assertTrue(genericObjectPool.getNumIdle() < 200,"Should be less than 200 idle, found " + genericObjectPool.getNumIdle()); Waiter.sleepQuietly(600L); assertTrue(genericObjectPool.getNumIdle() < 100,"Should be less than 100 idle, found " + genericObjectPool.getNumIdle()); Waiter.sleepQuietly(600L); assertEquals(0,genericObjectPool.getNumIdle(),"Should be zero idle, found " + genericObjectPool.getNumIdle()); for (int i = 0; i < 500; i++) { active[i] = genericObjectPool.borrowObject(); } for (int i = 0; i < 500; i++) { genericObjectPool.returnObject(active[i]); } Waiter.sleepQuietly(1000L); assertTrue(genericObjectPool.getNumIdle() < 500,"Should be less than 500 idle, found " + genericObjectPool.getNumIdle()); Waiter.sleepQuietly(600L); assertTrue(genericObjectPool.getNumIdle() < 400,"Should be less than 400 idle, found " + genericObjectPool.getNumIdle()); Waiter.sleepQuietly(600L); assertTrue(genericObjectPool.getNumIdle() < 300,"Should be less than 300 idle, found " + genericObjectPool.getNumIdle()); Waiter.sleepQuietly(600L); assertTrue(genericObjectPool.getNumIdle() < 200,"Should be less than 200 idle, found " + genericObjectPool.getNumIdle()); Waiter.sleepQuietly(600L); assertTrue(genericObjectPool.getNumIdle() < 100,"Should be less than 100 idle, found " + genericObjectPool.getNumIdle()); Waiter.sleepQuietly(600L); assertEquals(0,genericObjectPool.getNumIdle(),"Should be zero idle, found " + genericObjectPool.getNumIdle()); } @Test @Timeout(value = 60000, unit = TimeUnit.MILLISECONDS) public void testEvictionInvalid() throws Exception { try (final GenericObjectPool<Object, RuntimeException> invalidFactoryPool = new GenericObjectPool<>(new InvalidFactory())) { invalidFactoryPool.setMaxIdle(1); invalidFactoryPool.setMaxTotal(1); invalidFactoryPool.setTestOnBorrow(false); invalidFactoryPool.setTestOnReturn(false); invalidFactoryPool.setTestWhileIdle(true); invalidFactoryPool.setMinEvictableIdleDuration(Duration.ofSeconds(100)); invalidFactoryPool.setNumTestsPerEvictionRun(1); final Object p = invalidFactoryPool.borrowObject(); invalidFactoryPool.returnObject(p); // Run eviction in a separate thread final Thread t = new EvictionThread<>(invalidFactoryPool); t.start(); // Sleep to make sure evictor has started Thread.sleep(300); try { invalidFactoryPool.borrowObject(1); } catch (final NoSuchElementException nsee) { // Ignore } // Make sure evictor has finished Thread.sleep(1000); // Should have an empty pool assertEquals( 0, invalidFactoryPool.getNumIdle(),"Idle count different than expected."); assertEquals( 0, invalidFactoryPool.getNumActive(),"Total count different than expected."); } } /** * Test to make sure evictor visits least recently used objects first, * regardless of FIFO/LIFO. * * JIRA: POOL-86 * * @throws Exception May occur in some failure modes */ @Test @Timeout(value = 60000, unit = TimeUnit.MILLISECONDS) public void testEvictionOrder() throws Exception { checkEvictionOrder(false); tearDown(); setUp(); checkEvictionOrder(true); } @Test @Timeout(value = 60000, unit = TimeUnit.MILLISECONDS) public void testEvictionPolicy() throws Exception { genericObjectPool.setMaxIdle(500); genericObjectPool.setMaxTotal(500); genericObjectPool.setNumTestsPerEvictionRun(500); genericObjectPool.setMinEvictableIdleDuration(Duration.ofMillis(250)); genericObjectPool.setDurationBetweenEvictionRuns(Duration.ofMillis(500)); genericObjectPool.setTestWhileIdle(true); // ClassNotFoundException assertThrows(IllegalArgumentException.class, () -> genericObjectPool.setEvictionPolicyClassName(Long.toString(System.currentTimeMillis())), "setEvictionPolicyClassName must throw an error if the class name is invalid."); // InstantiationException assertThrows(IllegalArgumentException.class, () -> genericObjectPool.setEvictionPolicyClassName(java.io.Serializable.class.getName()), "setEvictionPolicyClassName must throw an error if the class name is invalid."); // IllegalAccessException assertThrows(IllegalArgumentException.class, () -> genericObjectPool.setEvictionPolicyClassName(java.util.Collections.class.getName()), "setEvictionPolicyClassName must throw an error if the class name is invalid."); assertThrows(IllegalArgumentException.class, () -> genericObjectPool.setEvictionPolicyClassName(java.lang.String.class.getName()), () -> "setEvictionPolicyClassName must throw an error if a class that does not implement EvictionPolicy is specified."); genericObjectPool.setEvictionPolicy(new TestEvictionPolicy<>()); assertEquals(TestEvictionPolicy.class.getName(), genericObjectPool.getEvictionPolicyClassName()); genericObjectPool.setEvictionPolicyClassName(TestEvictionPolicy.class.getName()); assertEquals(TestEvictionPolicy.class.getName(), genericObjectPool.getEvictionPolicyClassName()); final String[] active = new String[500]; for (int i = 0; i < 500; i++) { active[i] = genericObjectPool.borrowObject(); } for (int i = 0; i < 500; i++) { genericObjectPool.returnObject(active[i]); } // Eviction policy ignores first 1500 attempts to evict and then always // evicts. After 1s, there should have been two runs of 500 tests so no // evictions Waiter.sleepQuietly(1000L); assertEquals(500, genericObjectPool.getNumIdle(), "Should be 500 idle"); // A further 1s wasn't enough so allow 2s for the evictor to clear out // all of the idle objects. Waiter.sleepQuietly(2000L); assertEquals(0, genericObjectPool.getNumIdle(), "Should be 0 idle"); } @Test @Timeout(value = 60000, unit = TimeUnit.MILLISECONDS) public void testEvictionSoftMinIdle() throws Exception { final class TimeTest extends BasePooledObjectFactory<TimeTest, RuntimeException> { private final long createTimeMillis; public TimeTest() { createTimeMillis = System.currentTimeMillis(); } @Override public TimeTest create() { return new TimeTest(); } public long getCreateTimeMillis() { return createTimeMillis; } @Override public PooledObject<TimeTest> wrap(final TimeTest value) { return new DefaultPooledObject<>(value); } } try (final GenericObjectPool<TimeTest, RuntimeException> timePool = new GenericObjectPool<>(new TimeTest())) { timePool.setMaxIdle(5); timePool.setMaxTotal(5); timePool.setNumTestsPerEvictionRun(5); timePool.setMinEvictableIdleDuration(Duration.ofSeconds(3)); timePool.setSoftMinEvictableIdleDuration(TestConstants.ONE_SECOND_DURATION); 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].getCreateTimeMillis()); } for (int i = 0; i < 5; i++) { timePool.returnObject(active[i]); } // Soft evict all but minIdle(2) Thread.sleep(1500L); timePool.evict(); assertEquals(2, timePool.getNumIdle(), "Idle count different than expected."); // Hard evict the rest. Thread.sleep(2000L); timePool.evict(); assertEquals(0, timePool.getNumIdle(), "Idle count different than expected."); } } @Test @Timeout(value = 60000, unit = TimeUnit.MILLISECONDS) public void testEvictionWithNegativeNumTests() throws Exception { // when numTestsPerEvictionRun is negative, it represents a fraction of the idle objects to test genericObjectPool.setMaxIdle(6); genericObjectPool.setMaxTotal(6); genericObjectPool.setNumTestsPerEvictionRun(-2); genericObjectPool.setMinEvictableIdleDuration(Duration.ofMillis(50)); genericObjectPool.setDurationBetweenEvictionRuns(Duration.ofMillis(100)); final String[] active = new String[6]; for (int i = 0; i < 6; i++) { active[i] = genericObjectPool.borrowObject(); } for (int i = 0; i < 6; i++) { genericObjectPool.returnObject(active[i]); } Waiter.sleepQuietly(100L); assertTrue(genericObjectPool.getNumIdle() <= 6,"Should at most 6 idle, found " + genericObjectPool.getNumIdle()); Waiter.sleepQuietly(100L); assertTrue(genericObjectPool.getNumIdle() <= 3,"Should at most 3 idle, found " + genericObjectPool.getNumIdle()); Waiter.sleepQuietly(100L); assertTrue(genericObjectPool.getNumIdle() <= 2,"Should be at most 2 idle, found " + genericObjectPool.getNumIdle()); Waiter.sleepQuietly(100L); assertEquals(0,genericObjectPool.getNumIdle(),"Should be zero idle, found " + genericObjectPool.getNumIdle()); } @Test @Timeout(value = 60000, unit = TimeUnit.MILLISECONDS) public void testEvictLIFO() throws Exception { checkEvict(true); } /** * Verifies that the evictor visits objects in expected order * and frequency. * * @throws Exception May occur in some failure modes */ @Test public void testEvictorVisiting() throws Exception { checkEvictorVisiting(true); checkEvictorVisiting(false); } @Test @Timeout(value = 60000, unit = TimeUnit.MILLISECONDS) public void testEvictWhileEmpty() throws Exception { genericObjectPool.evict(); genericObjectPool.evict(); genericObjectPool.close(); } @Test @Timeout(value = 60000, unit = TimeUnit.MILLISECONDS) public void testExceptionInValidationDuringEviction() throws Exception { genericObjectPool.setMaxIdle(1); genericObjectPool.setMinEvictableIdleDuration(Duration.ZERO); genericObjectPool.setTestWhileIdle(true); final String active = genericObjectPool.borrowObject(); genericObjectPool.returnObject(active); simpleFactory.setThrowExceptionOnValidate(true); assertThrows(RuntimeException.class, () -> genericObjectPool.evict()); assertEquals(0, genericObjectPool.getNumActive()); assertEquals(0, genericObjectPool.getNumIdle()); } @Test @Timeout(value = 60000, unit = TimeUnit.MILLISECONDS) public void testExceptionOnActivateDuringBorrow() throws Exception { final String obj1 = genericObjectPool.borrowObject(); final String obj2 = genericObjectPool.borrowObject(); genericObjectPool.returnObject(obj1); genericObjectPool.returnObject(obj2); simpleFactory.setThrowExceptionOnActivate(true); simpleFactory.setEvenValid(false); // Activation will now throw every other time // First attempt throws, but loop continues and second succeeds final String obj = genericObjectPool.borrowObject(); assertEquals(1, genericObjectPool.getNumActive()); assertEquals(0, genericObjectPool.getNumIdle()); genericObjectPool.returnObject(obj); simpleFactory.setValid(false); // Validation will now fail on activation when borrowObject returns // an idle instance, and then when attempting to create a new instance assertThrows(NoSuchElementException.class, () -> genericObjectPool.borrowObject()); assertEquals(0, genericObjectPool.getNumActive()); assertEquals(0, genericObjectPool.getNumIdle()); } @Test @Timeout(value = 60000, unit = TimeUnit.MILLISECONDS) public void testExceptionOnDestroyDuringBorrow() throws Exception { simpleFactory.setThrowExceptionOnDestroy(true); genericObjectPool.setTestOnBorrow(true); genericObjectPool.borrowObject(); simpleFactory.setValid(false); // Make validation fail on next borrow attempt assertThrows(NoSuchElementException.class, () -> genericObjectPool.borrowObject()); assertEquals(1, genericObjectPool.getNumActive()); assertEquals(0, genericObjectPool.getNumIdle()); } @Test @Timeout(value = 60000, unit = TimeUnit.MILLISECONDS) public void testExceptionOnDestroyDuringReturn() throws Exception { simpleFactory.setThrowExceptionOnDestroy(true); genericObjectPool.setTestOnReturn(true); final String obj1 = genericObjectPool.borrowObject(); genericObjectPool.borrowObject(); simpleFactory.setValid(false); // Make validation fail genericObjectPool.returnObject(obj1); assertEquals(1, genericObjectPool.getNumActive()); assertEquals(0, genericObjectPool.getNumIdle()); } @Test @Timeout(value = 60000, unit = TimeUnit.MILLISECONDS) public void testExceptionOnPassivateDuringReturn() throws Exception { final String obj = genericObjectPool.borrowObject(); simpleFactory.setThrowExceptionOnPassivate(true); genericObjectPool.returnObject(obj); assertEquals(0,genericObjectPool.getNumIdle()); } @Test public void testFailingFactoryDoesNotBlockThreads() throws Exception { final CreateFailFactory factory = new CreateFailFactory(); try (final GenericObjectPool<String, InterruptedException> createFailFactoryPool = new GenericObjectPool<>(factory)) { createFailFactoryPool.setMaxTotal(1); // Try and borrow the first object from the pool final WaitingTestThread<InterruptedException> thread1 = new WaitingTestThread<>(createFailFactoryPool, 0); thread1.start(); // Wait for thread to reach semaphore while (!factory.hasQueuedThreads()) { Thread.sleep(200); } // Try and borrow the second object from the pool final WaitingTestThread<InterruptedException> thread2 = new WaitingTestThread<>(createFailFactoryPool, 0); thread2.start(); // Pool will not call factory since maximum number of object creations // are already queued. // Thread 2 will wait on an object being returned to the pool // Give thread 2 a chance to reach this state Thread.sleep(1000); // Release thread1 factory.release(); // Pre-release thread2 factory.release(); // Both threads should now complete. boolean threadRunning = true; int count = 0; while (threadRunning && count < 15) { threadRunning = thread1.isAlive(); threadRunning = thread2.isAlive(); Thread.sleep(200); count++; } assertFalse(thread1.isAlive()); assertFalse(thread2.isAlive()); assertTrue(thread1.thrown instanceof UnsupportedCharsetException); assertTrue(thread2.thrown instanceof UnsupportedCharsetException); } } @Test @Timeout(value = 60000, unit = TimeUnit.MILLISECONDS) public void testFIFO() throws Exception { genericObjectPool.setLifo(false); genericObjectPool.addObject(); // "0" genericObjectPool.addObject(); // "1" genericObjectPool.addObject(); // "2" assertEquals( "0", genericObjectPool.borrowObject(),"Oldest"); assertEquals( "1", genericObjectPool.borrowObject(),"Middle"); assertEquals( "2", genericObjectPool.borrowObject(),"Youngest"); final String o = genericObjectPool.borrowObject(); assertEquals( "3", o,"new-3"); genericObjectPool.returnObject(o); assertEquals( o, genericObjectPool.borrowObject(),"returned-3"); assertEquals( "4", genericObjectPool.borrowObject(),"new-4"); } @Test public void testGetFactoryType_DefaultPooledObjectFactory() { try (final GenericObjectPool<String, RuntimeException> pool = new GenericObjectPool<>(createDefaultPooledObjectFactory())) { assertNotNull(pool.getFactoryType()); } } @Test public void testGetFactoryType_NullPooledObjectFactory() { try (final GenericObjectPool<String, RuntimeException> pool = new GenericObjectPool<>(createNullPooledObjectFactory())) { assertNotNull(pool.getFactoryType()); } } @Test public void testGetFactoryType_PoolUtilsSynchronizedDefaultPooledFactory() { try (final GenericObjectPool<String, RuntimeException> pool = new GenericObjectPool<>( PoolUtils.synchronizedPooledFactory(createDefaultPooledObjectFactory()))) { assertNotNull(pool.getFactoryType()); } } @Test public void testGetFactoryType_PoolUtilsSynchronizedNullPooledFactory() { try (final GenericObjectPool<String, RuntimeException> pool = new GenericObjectPool<>( PoolUtils.synchronizedPooledFactory(createNullPooledObjectFactory()))) { assertNotNull(pool.getFactoryType()); } } @Test public void testGetFactoryType_SynchronizedDefaultPooledObjectFactory() { try (final GenericObjectPool<String, RuntimeException> pool = new GenericObjectPool<>( new TestSynchronizedPooledObjectFactory<>(createDefaultPooledObjectFactory()))) { assertNotNull(pool.getFactoryType()); } } @Test public void testGetFactoryType_SynchronizedNullPooledObjectFactory() { try (final GenericObjectPool<String, RuntimeException> pool = new GenericObjectPool<>( new TestSynchronizedPooledObjectFactory<>(createNullPooledObjectFactory()))) { assertNotNull(pool.getFactoryType()); } } @Test public void testGetStatsString() { try (final GenericObjectPool<String, RuntimeException> pool = new GenericObjectPool<>( new TestSynchronizedPooledObjectFactory<>(createNullPooledObjectFactory()))) { assertNotNull(pool.getStatsString()); } } /** * Verify that threads waiting on a depleted pool get served when a checked out object is * invalidated. * * JIRA: POOL-240 * * @throws Exception May occur in some failure modes */ @Test public void testInvalidateFreesCapacity() throws Exception { final SimpleFactory factory = new SimpleFactory(); try (final GenericObjectPool<String, TestException> pool = new GenericObjectPool<>(factory)) { pool.setMaxTotal(2); pool.setMaxWait(Duration.ofMillis(500)); // Borrow an instance and hold if for 5 seconds final WaitingTestThread<TestException> thread1 = new WaitingTestThread<>(pool, 5000); thread1.start(); // Borrow another instance final String obj = pool.borrowObject(); // Launch another thread - will block, but fail in 500 ms final WaitingTestThread<TestException> thread2 = new WaitingTestThread<>(pool, 100); thread2.start(); // Invalidate the object borrowed by this thread - should allow thread2 to create Thread.sleep(20); pool.invalidateObject(obj); Thread.sleep(600); // Wait for thread2 to timeout if (thread2.thrown != null) { fail(thread2.thrown.toString()); } } } /** * Ensure the pool is registered. */ @Test @Timeout(value = 60000, unit = TimeUnit.MILLISECONDS) public void testJmxRegistration() { final ObjectName oname = genericObjectPool.getJmxName(); final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); final Set<ObjectName> result = mbs.queryNames(oname, null); assertEquals(1, result.size()); genericObjectPool.jmxUnregister(); final GenericObjectPoolConfig<String> config = new GenericObjectPoolConfig<>(); config.setJmxEnabled(false); try (final GenericObjectPool<String, TestException> poolWithoutJmx = new GenericObjectPool<>(simpleFactory, config)) { assertNull(poolWithoutJmx.getJmxName()); config.setJmxEnabled(true); poolWithoutJmx.jmxUnregister(); } config.setJmxNameBase(null); try (final GenericObjectPool<String, TestException> poolWithDefaultJmxNameBase = new GenericObjectPool<>(simpleFactory, config)) { assertNotNull(poolWithDefaultJmxNameBase.getJmxName()); } } @Test @Timeout(value = 60000, unit = TimeUnit.MILLISECONDS) public void testLIFO() throws Exception { final String o; genericObjectPool.setLifo(true); genericObjectPool.addObject(); // "0" genericObjectPool.addObject(); // "1" genericObjectPool.addObject(); // "2" assertEquals( "2", genericObjectPool.borrowObject(),"Youngest"); assertEquals( "1", genericObjectPool.borrowObject(),"Middle"); assertEquals( "0", genericObjectPool.borrowObject(),"Oldest"); o = genericObjectPool.borrowObject(); assertEquals( "3", o,"new-3"); genericObjectPool.returnObject(o); assertEquals( o, genericObjectPool.borrowObject(),"returned-3"); assertEquals( "4", genericObjectPool.borrowObject(),"new-4"); } /** * Simplest example of recovery from factory outage. * A thread gets into parked wait on the deque when there is capacity to create, but * creates are failing due to factory outage. Verify that the borrower is served * once the factory is back online. */ @Test @Disabled @Timeout(value = 1000, unit = TimeUnit.MILLISECONDS) public void testLivenessOnTransientFactoryFailure() throws InterruptedException { final DisconnectingWaiterFactory<String> factory = new DisconnectingWaiterFactory<>( DisconnectingWaiterFactory.DEFAULT_DISCONNECTED_CREATE_ACTION, DisconnectingWaiterFactory.DEFAULT_DISCONNECTED_LIFECYCLE_ACTION, (obj) -> false // all instances fail validation ); final AtomicBoolean failed = new AtomicBoolean(false); try (GenericObjectPool<Waiter, IllegalStateException> pool = new GenericObjectPool<>(factory)) { pool.setMaxWait(Duration.ofMillis(100)); pool.setTestOnReturn(true); pool.setMaxTotal(1); final Waiter w = pool.borrowObject(); final Thread t = new Thread(() -> { try { pool.borrowObject(); } catch (final NoSuchElementException e) { failed.set(true); } }); Thread.sleep(10); t.start(); // t is blocked waiting on the deque Thread.sleep(10); factory.disconnect(); pool.returnObject(w); // validation fails, so no return Thread.sleep(10); factory.connect(); // Borrower should be able to be served now t.join(); } if (failed.get()) { fail("Borrower timed out waiting for an instance"); } } /** * Test the following scenario: * Thread 1 borrows an instance * Thread 2 starts to borrow another instance before thread 1 returns its instance * Thread 1 returns its instance while thread 2 is validating its newly created instance * The test verifies that the instance created by Thread 2 is not leaked. * * @throws Exception May occur in some failure modes */ @Test @Timeout(value = 60000, unit = TimeUnit.MILLISECONDS) public void testMakeConcurrentWithReturn() throws Exception { genericObjectPool.setTestOnBorrow(true); simpleFactory.setValid(true); // Borrow and return an instance, with a short wait final WaitingTestThread<TestException> thread1 = new WaitingTestThread<>(genericObjectPool, 200); thread1.start(); Thread.sleep(50); // wait for validation to succeed // Slow down validation and borrow an instance simpleFactory.setValidateLatency(400); final String instance = genericObjectPool.borrowObject(); // Now make sure that we have not leaked an instance assertEquals(simpleFactory.getMakeCounter(), genericObjectPool.getNumIdle() + 1); genericObjectPool.returnObject(instance); assertEquals(simpleFactory.getMakeCounter(), genericObjectPool.getNumIdle()); } @Test @Timeout(value = 60000, unit = TimeUnit.MILLISECONDS) public void testMaxIdle() throws Exception { genericObjectPool.setMaxTotal(100); genericObjectPool.setMaxIdle(8); final String[] active = new String[100]; for(int i=0;i<100;i++) { active[i] = genericObjectPool.borrowObject(); } assertEquals(100,genericObjectPool.getNumActive()); assertEquals(0,genericObjectPool.getNumIdle()); for(int i=0;i<100;i++) { genericObjectPool.returnObject(active[i]); assertEquals(99 - i,genericObjectPool.getNumActive()); assertEquals(i < 8 ? i+1 : 8,genericObjectPool.getNumIdle()); } } @Test @Timeout(value = 60000, unit = TimeUnit.MILLISECONDS) public void testMaxIdleZero() throws Exception { genericObjectPool.setMaxTotal(100); genericObjectPool.setMaxIdle(0); final String[] active = new String[100]; for(int i=0;i<100;i++) { active[i] = genericObjectPool.borrowObject(); } assertEquals(100,genericObjectPool.getNumActive()); assertEquals(0,genericObjectPool.getNumIdle()); for(int i=0;i<100;i++) { genericObjectPool.returnObject(active[i]); assertEquals(99 - i,genericObjectPool.getNumActive()); assertEquals(0, genericObjectPool.getNumIdle()); } } /** * Showcasing a possible deadlock situation as reported in POOL-356 */ @Test @Timeout(value = 60000, unit = TimeUnit.MILLISECONDS) @SuppressWarnings("rawtypes") public void testMaxIdleZeroUnderLoad() { // Config final int numThreads = 199; // And main thread makes a round 200. final int numIter = 20; final int delay = 25; final int maxTotal = 10; simpleFactory.setMaxTotal(maxTotal); genericObjectPool.setMaxTotal(maxTotal); genericObjectPool.setBlockWhenExhausted(true); genericObjectPool.setDurationBetweenEvictionRuns(Duration.ofMillis(-1)); // this is important to trigger POOL-356 genericObjectPool.setMaxIdle(0); // Start threads to borrow objects final TestThread[] threads = new TestThread[numThreads]; for(int i=0;i<numThreads;i++) { // Factor of 2 on iterations so main thread does work whilst other // threads are running. Factor of 2 on delay so average delay for // other threads == actual delay for main thread threads[i] = new TestThread<>(genericObjectPool, numIter * 2, delay * 2); final Thread t = new Thread(threads[i]); t.start(); } // Give the threads a chance to start doing some work Waiter.sleepQuietly(100L); for (int i = 0; i < numIter; i++) { String obj = null; try { Waiter.sleepQuietly(delay); obj = genericObjectPool.borrowObject(); // Under load, observed numActive > maxTotal if (genericObjectPool.getNumActive() > genericObjectPool.getMaxTotal()) { throw new IllegalStateException("Too many active objects"); } Waiter.sleepQuietly(delay); } catch (final Exception e) { // Shouldn't happen e.printStackTrace(); fail("Exception on borrow"); } finally { if (obj != null) { try { genericObjectPool.returnObject(obj); } catch (final Exception e) { // Ignore } } } } for (int i = 0; i < numThreads; i++) { while (!threads[i].complete()) { Waiter.sleepQuietly(500L); } if (threads[i].failed()) { threads[i].error.printStackTrace(); fail("Thread " + i + " failed: " + threads[i].error.toString()); } } } @Test @Timeout(value = 60000, unit = TimeUnit.MILLISECONDS) public void testMaxTotal() throws Exception { genericObjectPool.setMaxTotal(3); genericObjectPool.setBlockWhenExhausted(false); genericObjectPool.borrowObject(); genericObjectPool.borrowObject(); genericObjectPool.borrowObject(); assertThrows(NoSuchElementException.class, () -> genericObjectPool.borrowObject()); } /** * Verifies that maxTotal is not exceeded when factory destroyObject * has high latency, testOnReturn is set and there is high incidence of * validation failures. */ @Test @Timeout(value = 60000, unit = TimeUnit.MILLISECONDS) public void testMaxTotalInvariant() { final int maxTotal = 15; simpleFactory.setEvenValid(false); // Every other validation fails simpleFactory.setDestroyLatency(100); // Destroy takes 100 ms simpleFactory.setMaxTotal(maxTotal); // (makes - destroys) bound simpleFactory.setValidationEnabled(true); genericObjectPool.setMaxTotal(maxTotal); genericObjectPool.setMaxIdle(-1); genericObjectPool.setTestOnReturn(true); genericObjectPool.setMaxWait(Duration.ofMillis(1000)); runTestThreads(5, 10, 50, genericObjectPool); } @Test @Timeout(value = 60000, unit = TimeUnit.MILLISECONDS) @SuppressWarnings("rawtypes") public void testMaxTotalUnderLoad() { // Config final int numThreads = 199; // And main thread makes a round 200. final int numIter = 20; final int delay = 25; final int maxTotal = 10; simpleFactory.setMaxTotal(maxTotal); genericObjectPool.setMaxTotal(maxTotal); genericObjectPool.setBlockWhenExhausted(true); genericObjectPool.setDurationBetweenEvictionRuns(Duration.ofMillis(-1)); // Start threads to borrow objects final TestThread[] threads = new TestThread[numThreads]; for(int i=0;i<numThreads;i++) { // Factor of 2 on iterations so main thread does work whilst other // threads are running. Factor of 2 on delay so average delay for // other threads == actual delay for main thread threads[i] = new TestThread<>(genericObjectPool, numIter * 2, delay * 2); final Thread t = new Thread(threads[i]); t.start(); } // Give the threads a chance to start doing some work Waiter.sleepQuietly(5000); for (int i = 0; i < numIter; i++) { String obj = null; try { Waiter.sleepQuietly(delay); obj = genericObjectPool.borrowObject(); // Under load, observed numActive > maxTotal if (genericObjectPool.getNumActive() > genericObjectPool.getMaxTotal()) { throw new IllegalStateException("Too many active objects"); } Waiter.sleepQuietly(delay); } catch (final Exception e) { // Shouldn't happen e.printStackTrace(); fail("Exception on borrow"); } finally { if (obj != null) { try { genericObjectPool.returnObject(obj); } catch (final Exception e) { // Ignore } } } } for (int i = 0; i < numThreads; i++) { while(!threads[i].complete()) { Waiter.sleepQuietly(500L); } if(threads[i].failed()) { fail("Thread " + i + " failed: " + threads[i].error.toString()); } } } @Test @Timeout(value = 60000, unit = TimeUnit.MILLISECONDS) public void testMaxTotalZero() throws Exception { genericObjectPool.setMaxTotal(0); genericObjectPool.setBlockWhenExhausted(false); assertThrows(NoSuchElementException.class, () -> genericObjectPool.borrowObject()); } /* * Test multi-threaded pool access. * Multiple threads, but maxTotal only allows half the threads to succeed. * * This test was prompted by Continuum build failures in the Commons DBCP test case: * TestPerUserPoolDataSource.testMultipleThreads2() * Let's see if the this fails on Continuum too! */ @Test @Timeout(value = 60000, unit = TimeUnit.MILLISECONDS) public void testMaxWaitMultiThreaded() throws Exception { final long maxWait = 500; // wait for connection final long holdTime = 2 * maxWait; // how long to hold connection final int threads = 10; // number of threads to grab the object initially genericObjectPool.setBlockWhenExhausted(true); genericObjectPool.setMaxWait(Duration.ofMillis(maxWait)); genericObjectPool.setMaxTotal(threads); // Create enough threads so half the threads will have to wait final WaitingTestThread<TestException>[] wtt = new WaitingTestThread[threads * 2]; for (int i = 0; i < wtt.length; i++) { wtt[i] = new WaitingTestThread<>(genericObjectPool, holdTime); } final long originMillis = System.currentTimeMillis() - 1000; for (final WaitingTestThread<TestException> element : wtt) { element.start(); } int failed = 0; for (final WaitingTestThread<TestException> element : wtt) { element.join(); if (element.thrown != null){ failed++; } } if (DISPLAY_THREAD_DETAILS || wtt.length/2 != failed){ System.out.println( "MaxWait: " + maxWait + " HoldTime: " + holdTime + " MaxTotal: " + threads + " Threads: " + wtt.length + " Failed: " + failed ); for (final WaitingTestThread<TestException> wt : wtt) { System.out.println( "PreBorrow: " + (wt.preBorrowMillis - originMillis) + " PostBorrow: " + (wt.postBorrowMillis != 0 ? wt.postBorrowMillis - originMillis : -1) + " BorrowTime: " + (wt.postBorrowMillis != 0 ? wt.postBorrowMillis - wt.preBorrowMillis : -1) + " PostReturn: " + (wt.postReturnMillis != 0 ? wt.postReturnMillis - originMillis : -1) + " Ended: " + (wt.endedMillis - originMillis) + " ObjId: " + wt.objectId ); } } assertEquals(wtt.length / 2, failed,"Expected half the threads to fail"); } @Test @Timeout(value = 60000, unit = TimeUnit.MILLISECONDS) public void testMinIdle() throws Exception { genericObjectPool.setMaxIdle(500); genericObjectPool.setMinIdle(5); genericObjectPool.setMaxTotal(10); genericObjectPool.setNumTestsPerEvictionRun(0); genericObjectPool.setMinEvictableIdleDuration(Duration.ofMillis(50)); genericObjectPool.setDurationBetweenEvictionRuns(Duration.ofMillis(100)); genericObjectPool.setTestWhileIdle(true); Waiter.sleepQuietly(150L); assertEquals(5, genericObjectPool.getNumIdle(), "Should be 5 idle, found " + genericObjectPool.getNumIdle()); final String[] active = new String[5]; active[0] = genericObjectPool.borrowObject(); Waiter.sleepQuietly(150L); assertEquals(5, genericObjectPool.getNumIdle(), "Should be 5 idle, found " + genericObjectPool.getNumIdle()); for (int i = 1; i < 5; i++) { active[i] = genericObjectPool.borrowObject(); } Waiter.sleepQuietly(150L); assertEquals(5, genericObjectPool.getNumIdle(), "Should be 5 idle, found " + genericObjectPool.getNumIdle()); for (int i = 0; i < 5; i++) { genericObjectPool.returnObject(active[i]); } Waiter.sleepQuietly(150L); assertEquals(10, genericObjectPool.getNumIdle(), "Should be 10 idle, found " + genericObjectPool.getNumIdle()); } @Test @Timeout(value = 60000, unit = TimeUnit.MILLISECONDS) public void testMinIdleMaxTotal() throws Exception { genericObjectPool.setMaxIdle(500); genericObjectPool.setMinIdle(5); genericObjectPool.setMaxTotal(10); genericObjectPool.setNumTestsPerEvictionRun(0); genericObjectPool.setMinEvictableIdleDuration(Duration.ofMillis(50)); genericObjectPool.setDurationBetweenEvictionRuns(Duration.ofMillis(100)); genericObjectPool.setTestWhileIdle(true); Waiter.sleepQuietly(150L); assertEquals(5, genericObjectPool.getNumIdle(), "Should be 5 idle, found " + genericObjectPool.getNumIdle()); final String[] active = new String[10]; Waiter.sleepQuietly(150L); assertEquals(5, genericObjectPool.getNumIdle(), "Should be 5 idle, found " + genericObjectPool.getNumIdle()); for (int i = 0; i < 5; i++) { active[i] = genericObjectPool.borrowObject(); } Waiter.sleepQuietly(150L); assertEquals(5, genericObjectPool.getNumIdle(), "Should be 5 idle, found " + genericObjectPool.getNumIdle()); for(int i = 0 ; i < 5 ; i++) { genericObjectPool.returnObject(active[i]); } Waiter.sleepQuietly(150L); assertEquals(10, genericObjectPool.getNumIdle(), "Should be 10 idle, found " + genericObjectPool.getNumIdle()); for (int i = 0; i < 10; i++) { active[i] = genericObjectPool.borrowObject(); } Waiter.sleepQuietly(150L); assertEquals(0, genericObjectPool.getNumIdle(), "Should be 0 idle, found " + genericObjectPool.getNumIdle()); for (int i = 0; i < 10; i++) { genericObjectPool.returnObject(active[i]); } Waiter.sleepQuietly(150L); assertEquals(10, genericObjectPool.getNumIdle(), "Should be 10 idle, found " + genericObjectPool.getNumIdle()); } /** * Verifies that returning an object twice (without borrow in between) causes ISE * but does not re-validate or re-passivate the instance. * * JIRA: POOL-285 */ @Test public void testMultipleReturn() throws Exception { final WaiterFactory<String> factory = new WaiterFactory<>(0, 0, 0, 0, 0, 0); try (final GenericObjectPool<Waiter, IllegalStateException> pool = new GenericObjectPool<>(factory)) { pool.setTestOnReturn(true); final Waiter waiter = pool.borrowObject(); pool.returnObject(waiter); assertEquals(1, waiter.getValidationCount()); assertEquals(1, waiter.getPassivationCount()); try { pool.returnObject(waiter); fail("Expecting IllegalStateException from multiple return"); } catch (final IllegalStateException ex) { // Exception is expected, now check no repeat validation/passivation assertEquals(1, waiter.getValidationCount()); assertEquals(1, waiter.getPassivationCount()); } } } // POOL-248 @Test public void testMultipleReturnOfSameObject() throws Exception { try (final GenericObjectPool<String, TestException> pool = new GenericObjectPool<>(simpleFactory, new GenericObjectPoolConfig<>())) { assertEquals(0, pool.getNumActive()); assertEquals(0, pool.getNumIdle()); final String obj = pool.borrowObject(); assertEquals(1, pool.getNumActive()); assertEquals(0, pool.getNumIdle()); pool.returnObject(obj); assertEquals(0, pool.getNumActive()); assertEquals(1, pool.getNumIdle()); assertThrows(IllegalStateException.class, () -> pool.returnObject(obj)); assertEquals(0, pool.getNumActive()); assertEquals(1, pool.getNumIdle()); } } /** * Verifies that when a borrowed object is mutated in a way that does not * preserve equality and hash code, the pool can recognized it on return. * * JIRA: POOL-284 */ @Test public void testMutable() throws Exception { final HashSetFactory factory = new HashSetFactory(); try (final GenericObjectPool<HashSet<String>, RuntimeException> pool = new GenericObjectPool<>(factory, new GenericObjectPoolConfig<>())) { final HashSet<String> s1 = pool.borrowObject(); final HashSet<String> s2 = pool.borrowObject(); s1.add("One"); s2.add("One"); pool.returnObject(s1); pool.returnObject(s2); } } @Test @Timeout(value = 60000, unit = TimeUnit.MILLISECONDS) public void testNegativeMaxTotal() throws Exception { genericObjectPool.setMaxTotal(-1); genericObjectPool.setBlockWhenExhausted(false); final String obj = genericObjectPool.borrowObject(); assertEquals(getNthObject(0),obj); genericObjectPool.returnObject(obj); } /** * Verifies that concurrent threads never "share" instances */ @Test public void testNoInstanceOverlap() { final int maxTotal = 5; final int numThreads = 100; final int delay = 1; final int iterations = 1000; final AtomicIntegerFactory factory = new AtomicIntegerFactory(); try (final GenericObjectPool<AtomicInteger, RuntimeException> pool = new GenericObjectPool<>(factory)) { pool.setMaxTotal(maxTotal); pool.setMaxIdle(maxTotal); pool.setTestOnBorrow(true); pool.setBlockWhenExhausted(true); pool.setMaxWait(Duration.ofMillis(-1)); runTestThreads(numThreads, iterations, delay, pool); assertEquals(0, pool.getDestroyedByBorrowValidationCount()); } } /** * POOL-376 */ @Test @Timeout(value = 60000, unit = TimeUnit.MILLISECONDS) public void testNoInvalidateNPE() throws Exception { genericObjectPool.setMaxTotal(1); genericObjectPool.setTestOnCreate(true); genericObjectPool.setMaxWait(Duration.ofMillis(-1)); final String obj = genericObjectPool.borrowObject(); // Make validation fail - this will cause create() to return null simpleFactory.setValid(false); // Create a take waiter final WaitingTestThread<TestException> wtt = new WaitingTestThread<>(genericObjectPool, 200); wtt.start(); // Give wtt time to start Thread.sleep(200); genericObjectPool.invalidateObject(obj); // Now allow create to succeed so waiter can be served simpleFactory.setValid(true); } /** * Verify that when a factory returns a null object, pool methods throw NPE. * @throws InterruptedException */ @Test @Timeout(value = 1000, unit = TimeUnit.MILLISECONDS) public void testNPEOnFactoryNull() throws InterruptedException { final DisconnectingWaiterFactory<String> factory = new DisconnectingWaiterFactory<>( () -> null, // Override default to always return null from makeObject DisconnectingWaiterFactory.DEFAULT_DISCONNECTED_LIFECYCLE_ACTION, DisconnectingWaiterFactory.DEFAULT_DISCONNECTED_VALIDATION_ACTION ); try (GenericObjectPool<Waiter, IllegalStateException> pool = new GenericObjectPool<>(factory)) { pool.setTestOnBorrow(true); pool.setMaxTotal(-1); pool.setMinIdle(1); // Disconnect the factory - will always return null in this state factory.disconnect(); assertThrows(NullPointerException.class, pool::borrowObject); assertThrows(NullPointerException.class, pool::addObject); assertThrows(NullPointerException.class, pool::ensureMinIdle); } } @Test public void testPreparePool() throws Exception { genericObjectPool.setMinIdle(1); genericObjectPool.setMaxTotal(1); genericObjectPool.preparePool(); assertEquals(1, genericObjectPool.getNumIdle()); final String obj = genericObjectPool.borrowObject(); genericObjectPool.preparePool(); assertEquals(0, genericObjectPool.getNumIdle()); genericObjectPool.setMinIdle(0); genericObjectPool.returnObject(obj); genericObjectPool.preparePool(); assertEquals(1, genericObjectPool.getNumIdle()); } @Test/* maxWaitMillis x2 + padding */ @Timeout(value = 1200, unit = TimeUnit.MILLISECONDS) public void testReturnBorrowObjectWithingMaxWaitMillis() throws Exception { final long maxWaitMillis = 500; try (final GenericObjectPool<String, InterruptedException> createSlowObjectFactoryPool = new GenericObjectPool<>( createSlowObjectFactory(60000))) { createSlowObjectFactoryPool.setMaxTotal(1); createSlowObjectFactoryPool.setMaxWait(Duration.ofMillis(maxWaitMillis)); // thread1 tries creating a slow object to make pool full. final WaitingTestThread<InterruptedException> thread1 = new WaitingTestThread<>(createSlowObjectFactoryPool, 0); thread1.start(); // Wait for thread1's reaching to create(). Thread.sleep(100); // another one tries borrowObject. It should return within maxWaitMillis. assertThrows(NoSuchElementException.class, () -> createSlowObjectFactoryPool.borrowObject(maxWaitMillis), "borrowObject must fail due to timeout by maxWaitMillis"); assertTrue(thread1.isAlive()); } } /** * This is the test case for POOL-263. It is disabled since it will always * pass without artificial delay being injected into GOP.returnObject() and * a way to this hasn't currently been found that doesn't involve * polluting the GOP implementation. The artificial delay needs to be * inserted just before the final call to isLifo() in the returnObject() * method. */ //@Test @Timeout(value = 60000, unit = TimeUnit.MILLISECONDS) public void testReturnObject() throws Exception { genericObjectPool.setMaxTotal(1); genericObjectPool.setMaxIdle(-1); final String active = genericObjectPool.borrowObject(); assertEquals(1, genericObjectPool.getNumActive()); assertEquals(0, genericObjectPool.getNumIdle()); final Thread t = new Thread(() -> genericObjectPool.close()); t.start(); genericObjectPool.returnObject(active); // Wait for the close() thread to complete while (t.isAlive()) { Thread.sleep(50); } assertEquals(0, genericObjectPool.getNumIdle()); } @Test @Timeout(value = 60000, unit = TimeUnit.MILLISECONDS) public void testSetConfig() throws Exception { final GenericObjectPoolConfig<String> expected = new GenericObjectPoolConfig<>(); assertConfiguration(expected,genericObjectPool); expected.setMaxTotal(2); expected.setMaxIdle(3); expected.setMaxWait(Duration.ofMillis(5)); expected.setMinEvictableIdleDuration(Duration.ofMillis(7L)); expected.setNumTestsPerEvictionRun(9); expected.setTestOnCreate(true); expected.setTestOnBorrow(true); expected.setTestOnReturn(true); expected.setTestWhileIdle(true); expected.setDurationBetweenEvictionRuns(Duration.ofMillis(11L)); expected.setBlockWhenExhausted(false); genericObjectPool.setConfig(expected); assertConfiguration(expected,genericObjectPool); } @Test @Timeout(value = 60000, unit = TimeUnit.MILLISECONDS) public void testSettersAndGetters() throws Exception { { // The object receives an Exception during its creation to prevent // memory leaks. See BaseGenericObjectPool constructor for more details. assertNotEquals("", genericObjectPool.getCreationStackTrace()); } { assertEquals(0, genericObjectPool.getBorrowedCount()); } { assertEquals(0, genericObjectPool.getReturnedCount()); } { assertEquals(0, genericObjectPool.getCreatedCount()); } { assertEquals(0, genericObjectPool.getDestroyedCount()); } { assertEquals(0, genericObjectPool.getDestroyedByEvictorCount()); } { assertEquals(0, genericObjectPool.getDestroyedByBorrowValidationCount()); } { assertEquals(0, genericObjectPool.getMeanActiveTimeMillis()); } { assertEquals(0, genericObjectPool.getMeanIdleTimeMillis()); } { assertEquals(0, genericObjectPool.getMeanBorrowWaitTimeMillis()); } { assertEquals(0, genericObjectPool.getMaxBorrowWaitTimeMillis()); } { assertEquals(0, genericObjectPool.getNumIdle()); } { genericObjectPool.setMaxTotal(123); assertEquals(123, genericObjectPool.getMaxTotal()); } { genericObjectPool.setMaxIdle(12); assertEquals(12, genericObjectPool.getMaxIdle()); } { genericObjectPool.setMaxWait(Duration.ofMillis(1234)); assertEquals(1234L, genericObjectPool.getMaxWaitDuration().toMillis()); } { genericObjectPool.setMinEvictableIdleDuration(Duration.ofMillis(12345)); assertEquals(12345L, genericObjectPool.getMinEvictableIdleDuration().toMillis()); } { genericObjectPool.setNumTestsPerEvictionRun(11); assertEquals(11, genericObjectPool.getNumTestsPerEvictionRun()); } { genericObjectPool.setTestOnBorrow(true); assertTrue(genericObjectPool.getTestOnBorrow()); genericObjectPool.setTestOnBorrow(false); assertFalse(genericObjectPool.getTestOnBorrow()); } { genericObjectPool.setTestOnReturn(true); assertTrue(genericObjectPool.getTestOnReturn()); genericObjectPool.setTestOnReturn(false); assertFalse(genericObjectPool.getTestOnReturn()); } { genericObjectPool.setTestWhileIdle(true); assertTrue(genericObjectPool.getTestWhileIdle()); genericObjectPool.setTestWhileIdle(false); assertFalse(genericObjectPool.getTestWhileIdle()); } { genericObjectPool.setDurationBetweenEvictionRuns(Duration.ofMillis(11235)); assertEquals(11235L,genericObjectPool.getDurationBetweenEvictionRuns().toMillis()); } { genericObjectPool.setSoftMinEvictableIdleDuration(Duration.ofMillis(12135)); assertEquals(12135L,genericObjectPool.getSoftMinEvictableIdleDuration().toMillis()); } { genericObjectPool.setBlockWhenExhausted(true); assertTrue(genericObjectPool.getBlockWhenExhausted()); genericObjectPool.setBlockWhenExhausted(false); assertFalse(genericObjectPool.getBlockWhenExhausted()); } } @Test @Timeout(value = 60000, unit = TimeUnit.MILLISECONDS) public void testStartAndStopEvictor() throws Exception { // set up pool without evictor genericObjectPool.setMaxIdle(6); genericObjectPool.setMaxTotal(6); genericObjectPool.setNumTestsPerEvictionRun(6); genericObjectPool.setMinEvictableIdleDuration(Duration.ofMillis(100)); for (int j = 0; j < 2; j++) { // populate the pool { final String[] active = new String[6]; for (int i = 0; i < 6; i++) { active[i] = genericObjectPool.borrowObject(); } for (int i = 0; i < 6; i++) { genericObjectPool.returnObject(active[i]); } } // note that it stays populated assertEquals(6,genericObjectPool.getNumIdle(),"Should have 6 idle"); // start the evictor genericObjectPool.setDurationBetweenEvictionRuns(Duration.ofMillis(50)); // wait a second (well, .2 seconds) Waiter.sleepQuietly(200L); // assert that the evictor has cleared out the pool assertEquals(0,genericObjectPool.getNumIdle(),"Should have 0 idle"); // stop the evictor genericObjectPool.startEvictor(Duration.ZERO); } } @Test public void testSwallowedExceptionListener() { genericObjectPool.setSwallowedExceptionListener(null); // must simply return final List<Exception> swallowedExceptions = new ArrayList<>(); /* * A simple listener, that will throw a OOM on 3rd exception. */ final SwallowedExceptionListener listener = e -> { if (swallowedExceptions.size() == 2) { throw new OutOfMemoryError(); } swallowedExceptions.add(e); }; genericObjectPool.setSwallowedExceptionListener(listener); final Exception e1 = new Exception(); final Exception e2 = new ArrayIndexOutOfBoundsException(); genericObjectPool.swallowException(e1); genericObjectPool.swallowException(e2); assertThrows(OutOfMemoryError.class, () -> genericObjectPool.swallowException(e1)); assertEquals(2, swallowedExceptions.size()); } @Test @Timeout(value = 60000, unit = TimeUnit.MILLISECONDS) public void testThreaded1() throws Exception { genericObjectPool.setMaxTotal(15); genericObjectPool.setMaxIdle(15); genericObjectPool.setMaxWait(Duration.ofMillis(1000)); runTestThreads(20, 100, 50, genericObjectPool); } @Test @Timeout(value = 60000, unit = TimeUnit.MILLISECONDS) public void testTimeoutNoLeak() throws Exception { genericObjectPool.setMaxTotal(2); genericObjectPool.setMaxWait(Duration.ofMillis(10)); genericObjectPool.setBlockWhenExhausted(true); final String obj = genericObjectPool.borrowObject(); final String obj2 = genericObjectPool.borrowObject(); assertThrows(NoSuchElementException.class, () -> genericObjectPool.borrowObject()); genericObjectPool.returnObject(obj2); genericObjectPool.returnObject(obj); genericObjectPool.borrowObject(); genericObjectPool.borrowObject(); } /** * Tests POOL-361 */ @Test public void testValidateOnCreate() throws Exception { genericObjectPool.setTestOnCreate(true); genericObjectPool.addObject(); assertEquals(1, simpleFactory.validateCounter); } /** * Tests POOL-361 */ @Test public void testValidateOnCreateFailure() throws Exception { genericObjectPool.setTestOnCreate(true); genericObjectPool.setTestOnBorrow(false); genericObjectPool.setMaxTotal(2); simpleFactory.setValid(false); // Make sure failed validations do not leak capacity genericObjectPool.addObject(); genericObjectPool.addObject(); assertEquals(0, genericObjectPool.getNumIdle()); assertEquals(0, genericObjectPool.getNumActive()); simpleFactory.setValid(true); final String obj = genericObjectPool.borrowObject(); assertNotNull(obj); genericObjectPool.addObject(); // Should have one idle, one out now assertEquals(1, genericObjectPool.getNumIdle()); assertEquals(1, genericObjectPool.getNumActive()); } /** * Verify that threads waiting on a depleted pool get served when a returning object fails * validation. * * JIRA: POOL-240 * * @throws Exception May occur in some failure modes */ @Test public void testValidationFailureOnReturnFreesCapacity() throws Exception { final SimpleFactory factory = new SimpleFactory(); factory.setValid(false); // Validate will always fail factory.setValidationEnabled(true); try (final GenericObjectPool<String, TestException> pool = new GenericObjectPool<>(factory)) { pool.setMaxTotal(2); pool.setMaxWait(Duration.ofMillis(1500)); pool.setTestOnReturn(true); pool.setTestOnBorrow(false); // Borrow an instance and hold if for 5 seconds final WaitingTestThread<TestException> thread1 = new WaitingTestThread<>(pool, 5000); thread1.start(); // Borrow another instance and return it after 500 ms (validation will fail) final WaitingTestThread<TestException> thread2 = new WaitingTestThread<>(pool, 500); thread2.start(); Thread.sleep(50); // Try to borrow an object final String obj = pool.borrowObject(); pool.returnObject(obj); } } // POOL-276 @Test public void testValidationOnCreateOnly() throws Exception { genericObjectPool.setMaxTotal(1); genericObjectPool.setTestOnCreate(true); genericObjectPool.setTestOnBorrow(false); genericObjectPool.setTestOnReturn(false); genericObjectPool.setTestWhileIdle(false); final String o1 = genericObjectPool.borrowObject(); assertEquals("0", o1); final Timer t = new Timer(); t.schedule( new TimerTask() { @Override public void run() { genericObjectPool.returnObject(o1); } }, 3000); final String o2 = genericObjectPool.borrowObject(); assertEquals("0", o2); assertEquals(1, simpleFactory.validateCounter); } @Test @Timeout(value = 60000, unit = TimeUnit.MILLISECONDS) public void testWhenExhaustedBlock() throws Exception { genericObjectPool.setMaxTotal(1); genericObjectPool.setBlockWhenExhausted(true); genericObjectPool.setMaxWait(Duration.ofMillis(10)); final String obj1 = genericObjectPool.borrowObject(); assertNotNull(obj1); assertThrows(NoSuchElementException.class, () -> genericObjectPool.borrowObject()); genericObjectPool.returnObject(obj1); genericObjectPool.close(); } /** * POOL-189 * * @throws Exception May occur in some failure modes */ @Test @Timeout(value = 60000, unit = TimeUnit.MILLISECONDS) public void testWhenExhaustedBlockClosePool() throws Exception { genericObjectPool.setMaxTotal(1); genericObjectPool.setBlockWhenExhausted(true); genericObjectPool.setMaxWait(Duration.ofMillis(-1)); final Object obj1 = genericObjectPool.borrowObject(); // Make sure an object was obtained assertNotNull(obj1); // Create a separate thread to try and borrow another object final WaitingTestThread<TestException> wtt = new WaitingTestThread<>(genericObjectPool, 200); wtt.start(); // Give wtt time to start Thread.sleep(200); // close the pool (Bug POOL-189) genericObjectPool.close(); // Give interrupt time to take effect Thread.sleep(200); // Check thread was interrupted assertTrue(wtt.thrown instanceof InterruptedException); } @Test @Timeout(value = 60000, unit = TimeUnit.MILLISECONDS) public void testWhenExhaustedBlockInterrupt() throws Exception { genericObjectPool.setMaxTotal(1); genericObjectPool.setBlockWhenExhausted(true); genericObjectPool.setMaxWait(Duration.ofMillis(-1)); final String obj1 = genericObjectPool.borrowObject(); // Make sure on object was obtained assertNotNull(obj1); // Create a separate thread to try and borrow another object final WaitingTestThread<TestException> wtt = new WaitingTestThread<>(genericObjectPool, 200000); wtt.start(); // Give wtt time to start Thread.sleep(200); wtt.interrupt(); // Give interrupt time to take effect Thread.sleep(200); // Check thread was interrupted assertTrue(wtt.thrown instanceof InterruptedException); // Return object to the pool genericObjectPool.returnObject(obj1); // Bug POOL-162 - check there is now an object in the pool genericObjectPool.setMaxWait(Duration.ofMillis(10)); String obj2 = null; try { obj2 = genericObjectPool.borrowObject(); assertNotNull(obj2); } catch (final NoSuchElementException e) { // Not expected fail("NoSuchElementException not expected"); } genericObjectPool.returnObject(obj2); genericObjectPool.close(); } @Test @Timeout(value = 60000, unit = TimeUnit.MILLISECONDS) public void testWhenExhaustedFail() throws Exception { genericObjectPool.setMaxTotal(1); genericObjectPool.setBlockWhenExhausted(false); final String obj1 = genericObjectPool.borrowObject(); assertNotNull(obj1); assertThrows(NoSuchElementException.class, () -> genericObjectPool.borrowObject()); genericObjectPool.returnObject(obj1); assertEquals(1, genericObjectPool.getNumIdle()); genericObjectPool.close(); } }
5,225
0
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/impl/TestSoftRefOutOfMemory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.impl; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import org.apache.commons.pool3.BasePooledObjectFactory; import org.apache.commons.pool3.PooledObject; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; /** */ public class TestSoftRefOutOfMemory { public static class LargePoolableObjectFactory extends BasePooledObjectFactory<String, RuntimeException> { private final String buffer; private int counter; public LargePoolableObjectFactory(final int size) { final char[] data = new char[size]; Arrays.fill(data, '.'); buffer = new String(data); } @Override public String create() { counter++; return String.valueOf(counter) + buffer; } @Override public PooledObject<String> wrap(final String value) { return new DefaultPooledObject<>(value); } } private static final class OomeFactory extends BasePooledObjectFactory<String, RuntimeException> { private final OomeTrigger trigger; public OomeFactory(final OomeTrigger trigger) { this.trigger = trigger; } @Override public String create() { if (trigger.equals(OomeTrigger.CREATE)) { throw new OutOfMemoryError(); } // It seems that as of Java 1.4 String.valueOf may return an // intern()'ed String this may cause problems when the tests // depend on the returned object to be eventually garbaged // collected. Either way, making sure a new String instance // is returned eliminated false failures. return new String(); } @Override public void destroyObject(final PooledObject<String> p) { if (trigger.equals(OomeTrigger.DESTROY)) { throw new OutOfMemoryError(); } super.destroyObject(p); } @Override public boolean validateObject(final PooledObject<String> p) { if (trigger.equals(OomeTrigger.VALIDATE)) { throw new OutOfMemoryError(); } return !trigger.equals(OomeTrigger.DESTROY); } @Override public PooledObject<String> wrap(final String value) { return new DefaultPooledObject<>(value); } } private enum OomeTrigger { CREATE, VALIDATE, DESTROY } public static class SmallPoolableObjectFactory extends BasePooledObjectFactory<String, RuntimeException> { private int counter; @Override public String create() { counter++; // It seems that as of Java 1.4 String.valueOf may return an // intern()'ed String this may cause problems when the tests // depend on the returned object to be eventually garbaged // collected. Either way, making sure a new String instance // is returned eliminated false failures. return new String(String.valueOf(counter)); } @Override public PooledObject<String> wrap(final String value) { return new DefaultPooledObject<>(value); } } private SoftReferenceObjectPool<String, RuntimeException> pool; @AfterEach public void tearDown() { if (pool != null) { pool.close(); pool = null; } System.gc(); } @Test public void testOutOfMemory() throws Exception { pool = new SoftReferenceObjectPool<>(new SmallPoolableObjectFactory()); String obj = pool.borrowObject(); assertEquals("1", obj); pool.returnObject(obj); obj = null; assertEquals(1, pool.getNumIdle()); final List<byte[]> garbage = new LinkedList<>(); final Runtime runtime = Runtime.getRuntime(); while (pool.getNumIdle() > 0) { try { long freeMemory = runtime.freeMemory(); if (freeMemory > Integer.MAX_VALUE) { freeMemory = Integer.MAX_VALUE; } garbage.add(new byte[Math.min(1024 * 1024, (int) freeMemory / 2)]); } catch (final OutOfMemoryError oome) { System.gc(); } System.gc(); } garbage.clear(); System.gc(); obj = pool.borrowObject(); assertEquals("2", obj); pool.returnObject(obj); obj = null; assertEquals(1, pool.getNumIdle()); } @Test public void testOutOfMemory1000() throws Exception { pool = new SoftReferenceObjectPool<>(new SmallPoolableObjectFactory()); for (int i = 0 ; i < 1000 ; i++) { pool.addObject(); } String obj = pool.borrowObject(); assertEquals("1000", obj); pool.returnObject(obj); obj = null; assertEquals(1000, pool.getNumIdle()); final List<byte[]> garbage = new LinkedList<>(); final Runtime runtime = Runtime.getRuntime(); while (pool.getNumIdle() > 0) { try { long freeMemory = runtime.freeMemory(); if (freeMemory > Integer.MAX_VALUE) { freeMemory = Integer.MAX_VALUE; } garbage.add(new byte[Math.min(1024 * 1024, (int) freeMemory / 2)]); } catch (final OutOfMemoryError oome) { System.gc(); } System.gc(); } garbage.clear(); System.gc(); obj = pool.borrowObject(); assertEquals("1001", obj); pool.returnObject(obj); obj = null; assertEquals(1, pool.getNumIdle()); } /** * Makes sure an {@link OutOfMemoryError} isn't swallowed. * * @throws Exception May occur in some failure modes */ @Test public void testOutOfMemoryError() throws Exception { pool = new SoftReferenceObjectPool<>(new OomeFactory(OomeTrigger.CREATE)); assertThrows(OutOfMemoryError.class, pool::borrowObject); pool.close(); pool = new SoftReferenceObjectPool<>(new OomeFactory(OomeTrigger.VALIDATE)); assertThrows(OutOfMemoryError.class, pool::borrowObject); pool.close(); pool = new SoftReferenceObjectPool<>(new OomeFactory(OomeTrigger.DESTROY)); assertThrows(OutOfMemoryError.class, pool::borrowObject); pool.close(); } @Test public void testOutOfMemoryLarge() throws Exception { pool = new SoftReferenceObjectPool<>(new LargePoolableObjectFactory(1000000)); String obj = pool.borrowObject(); assertTrue(obj.startsWith("1.")); pool.returnObject(obj); obj = null; assertEquals(1, pool.getNumIdle()); final List<byte[]> garbage = new LinkedList<>(); final Runtime runtime = Runtime.getRuntime(); while (pool.getNumIdle() > 0) { try { long freeMemory = runtime.freeMemory(); if (freeMemory > Integer.MAX_VALUE) { freeMemory = Integer.MAX_VALUE; } garbage.add(new byte[Math.min(1024 * 1024, (int) freeMemory / 2)]); } catch (final OutOfMemoryError oome) { System.gc(); } System.gc(); } garbage.clear(); System.gc(); obj = pool.borrowObject(); assertTrue(obj.startsWith("2.")); pool.returnObject(obj); obj = null; assertEquals(1, pool.getNumIdle()); } }
5,226
0
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/proxy/TestProxiedKeyedObjectPoolWithJdkProxy.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.proxy; public class TestProxiedKeyedObjectPoolWithJdkProxy extends AbstractTestProxiedKeyedObjectPool { @Override protected ProxySource<TestObject> getproxySource() { return new JdkProxySource<>(this.getClass().getClassLoader(), new Class<?>[] { TestObject.class }); } }
5,227
0
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/proxy/AbstractTestProxiedKeyedObjectPool.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.proxy; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.PrintWriter; import java.io.StringWriter; import java.time.Duration; import org.apache.commons.pool3.BaseKeyedPooledObjectFactory; import org.apache.commons.pool3.KeyedObjectPool; import org.apache.commons.pool3.KeyedPooledObjectFactory; import org.apache.commons.pool3.PooledObject; import org.apache.commons.pool3.impl.AbandonedConfig; import org.apache.commons.pool3.impl.DefaultPooledObject; import org.apache.commons.pool3.impl.GenericKeyedObjectPool; import org.apache.commons.pool3.impl.GenericKeyedObjectPoolConfig; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public abstract class AbstractTestProxiedKeyedObjectPool { private static final class TestKeyedObjectFactory extends BaseKeyedPooledObjectFactory<String, TestObject, RuntimeException> { @Override public TestObject create(final String key) { return new TestObjectImpl(); } @Override public PooledObject<TestObject> wrap(final TestObject value) { return new DefaultPooledObject<>(value); } } protected interface TestObject { String getData(); void setData(String data); } private static final class TestObjectImpl implements TestObject { private String data; @Override public String getData() { return data; } @Override public void setData(final String data) { this.data = data; } } private static final String KEY1 = "key1"; private static final String DATA1 = "data1"; private static final Duration ABANDONED_TIMEOUT_SECS = Duration.ofSeconds(3); private KeyedObjectPool<String, TestObject, RuntimeException> pool; private StringWriter log; protected abstract ProxySource<TestObject> getproxySource(); @BeforeEach public void setUp() { log = new StringWriter(); final PrintWriter pw = new PrintWriter(log); final AbandonedConfig abandonedConfig = new AbandonedConfig(); abandonedConfig.setLogAbandoned(true); abandonedConfig.setRemoveAbandonedOnBorrow(true); abandonedConfig.setUseUsageTracking(true); abandonedConfig.setRemoveAbandonedTimeout(ABANDONED_TIMEOUT_SECS); abandonedConfig.setLogWriter(pw); final GenericKeyedObjectPoolConfig<TestObject> config = new GenericKeyedObjectPoolConfig<>(); config.setMaxTotal(3); final KeyedPooledObjectFactory<String, TestObject, RuntimeException> factory = new TestKeyedObjectFactory(); @SuppressWarnings("resource") final KeyedObjectPool<String, TestObject, RuntimeException> innerPool = new GenericKeyedObjectPool<>(factory, config, abandonedConfig); pool = new ProxiedKeyedObjectPool<>(innerPool, getproxySource()); } @Test public void testAccessAfterInvalidate() { final TestObject obj = pool.borrowObject(KEY1); assertNotNull(obj); // Make sure proxied methods are working obj.setData(DATA1); assertEquals(DATA1, obj.getData()); pool.invalidateObject(KEY1, obj); assertNotNull(obj); assertThrows(IllegalStateException.class, obj::getData); } @Test public void testAccessAfterReturn() { final TestObject obj = pool.borrowObject(KEY1); assertNotNull(obj); // Make sure proxied methods are working obj.setData(DATA1); assertEquals(DATA1, obj.getData()); pool.returnObject(KEY1, obj); assertNotNull(obj); assertThrows(IllegalStateException.class, obj::getData); } @Test public void testBorrowObject() { final TestObject obj = pool.borrowObject(KEY1); assertNotNull(obj); // Make sure proxied methods are working obj.setData(DATA1); assertEquals(DATA1, obj.getData()); pool.returnObject(KEY1, obj); } @Test public void testPassThroughMethods01() { assertEquals(0, pool.getNumActive()); assertEquals(0, pool.getNumIdle()); pool.addObject(KEY1); assertEquals(0, pool.getNumActive()); assertEquals(1, pool.getNumIdle()); pool.clear(); assertEquals(0, pool.getNumActive()); assertEquals(0, pool.getNumIdle()); } @Test public void testPassThroughMethods02() { pool.close(); assertThrows(IllegalStateException.class, () -> pool.addObject(KEY1)); } @Test public void testUsageTracking() throws InterruptedException { final TestObject obj = pool.borrowObject(KEY1); assertNotNull(obj); // Use the object to trigger collection of last used stack trace obj.setData(DATA1); // Sleep long enough for the object to be considered abandoned Thread.sleep(ABANDONED_TIMEOUT_SECS.plusSeconds(2).toMillis()); // Borrow another object to trigger the abandoned object processing pool.borrowObject(KEY1); final String logOutput = log.getBuffer().toString(); assertTrue(logOutput.contains("Pooled object created")); assertTrue(logOutput.contains("The last code to use this object was")); } }
5,228
0
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/proxy/TestProxiedObjectPoolWithCglibProxy.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.proxy; public class TestProxiedObjectPoolWithCglibProxy extends AbstractTestProxiedObjectPool { @Override protected ProxySource<TestObject> getproxySource() { return new CglibProxySource<>(TestObject.class); } }
5,229
0
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/proxy/TestProxiedObjectPoolWithJdkProxy.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.proxy; public class TestProxiedObjectPoolWithJdkProxy extends AbstractTestProxiedObjectPool { @Override protected ProxySource<TestObject> getproxySource() { return new JdkProxySource<>(this.getClass().getClassLoader(), new Class<?>[] { TestObject.class }); } }
5,230
0
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/proxy/TestProxiedKeyedObjectPoolWithCglibProxy.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.proxy; public class TestProxiedKeyedObjectPoolWithCglibProxy extends AbstractTestProxiedKeyedObjectPool { @Override protected ProxySource<TestObject> getproxySource() { return new CglibProxySource<>(TestObject.class); } }
5,231
0
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/proxy/AbstractTestProxiedObjectPool.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.proxy; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.PrintWriter; import java.io.StringWriter; import java.time.Duration; import org.apache.commons.pool3.BasePooledObjectFactory; import org.apache.commons.pool3.ObjectPool; import org.apache.commons.pool3.PooledObject; import org.apache.commons.pool3.PooledObjectFactory; import org.apache.commons.pool3.impl.AbandonedConfig; import org.apache.commons.pool3.impl.DefaultPooledObject; import org.apache.commons.pool3.impl.GenericObjectPool; import org.apache.commons.pool3.impl.GenericObjectPoolConfig; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public abstract class AbstractTestProxiedObjectPool { protected interface TestObject { String getData(); void setData(String data); } private static final class TestObjectFactory extends BasePooledObjectFactory<TestObject, RuntimeException> { @Override public TestObject create() { return new TestObjectImpl(); } @Override public PooledObject<TestObject> wrap(final TestObject value) { return new DefaultPooledObject<>(value); } } private static final class TestObjectImpl implements TestObject { private String data; @Override public String getData() { return data; } @Override public void setData(final String data) { this.data = data; } } private static final String DATA1 = "data1"; private static final Duration ABANDONED_TIMEOUT_SECS = Duration.ofSeconds(3); private ObjectPool<TestObject, RuntimeException> pool; private StringWriter log; protected abstract ProxySource<TestObject> getproxySource(); @BeforeEach public void setUp() { log = new StringWriter(); final PrintWriter pw = new PrintWriter(log); final AbandonedConfig abandonedConfig = new AbandonedConfig(); abandonedConfig.setLogAbandoned(true); abandonedConfig.setRemoveAbandonedOnBorrow(true); abandonedConfig.setUseUsageTracking(true); abandonedConfig.setRemoveAbandonedTimeout(ABANDONED_TIMEOUT_SECS); abandonedConfig.setLogWriter(pw); final GenericObjectPoolConfig<TestObject> config = new GenericObjectPoolConfig<>(); config.setMaxTotal(3); final PooledObjectFactory<TestObject, RuntimeException> factory = new TestObjectFactory(); @SuppressWarnings("resource") final ObjectPool<TestObject, RuntimeException> innerPool = new GenericObjectPool<>(factory, config, abandonedConfig); pool = new ProxiedObjectPool<>(innerPool, getproxySource()); } @Test public void testAccessAfterInvalidate() { final TestObject obj = pool.borrowObject(); assertNotNull(obj); // Make sure proxied methods are working obj.setData(DATA1); assertEquals(DATA1, obj.getData()); pool.invalidateObject(obj); assertNotNull(obj); assertThrows(IllegalStateException.class, obj::getData); } @Test public void testAccessAfterReturn() { final TestObject obj = pool.borrowObject(); assertNotNull(obj); // Make sure proxied methods are working obj.setData(DATA1); assertEquals(DATA1, obj.getData()); pool.returnObject(obj); assertNotNull(obj); assertThrows(IllegalStateException.class, obj::getData); } @Test public void testBorrowObject() { final TestObject obj = pool.borrowObject(); assertNotNull(obj); // Make sure proxied methods are working obj.setData(DATA1); assertEquals(DATA1, obj.getData()); pool.returnObject(obj); } @Test public void testPassThroughMethods01() { assertEquals(0, pool.getNumActive()); assertEquals(0, pool.getNumIdle()); pool.addObject(); assertEquals(0, pool.getNumActive()); assertEquals(1, pool.getNumIdle()); pool.clear(); assertEquals(0, pool.getNumActive()); assertEquals(0, pool.getNumIdle()); } @Test public void testPassThroughMethods02() { pool.close(); assertThrows(IllegalStateException.class, () -> pool.addObject()); } @Test public void testUsageTracking() throws InterruptedException { final TestObject obj = pool.borrowObject(); assertNotNull(obj); // Use the object to trigger collection of last used stack trace obj.setData(DATA1); // Sleep long enough for the object to be considered abandoned Thread.sleep(ABANDONED_TIMEOUT_SECS.plusSeconds(2).toMillis()); // Borrow another object to trigger the abandoned object processing pool.borrowObject(); final String logOutput = log.getBuffer().toString(); assertTrue(logOutput.contains("Pooled object created")); assertTrue(logOutput.contains("The last code to use this object was")); } }
5,232
0
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/performance/PerformanceTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.performance; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.apache.commons.pool3.impl.GenericObjectPool; /** * Multi-thread performance test */ public class PerformanceTest { final class PerfTask implements Callable<TaskStats> { final TaskStats taskStats = new TaskStats(); long borrowTimeNanos; long returnTimeNanos; @Override public TaskStats call() { runOnce(); // warmup for (int i = 0; i < nrIterations; i++) { runOnce(); taskStats.totalBorrowNanos += borrowTimeNanos; taskStats.totalReturnNanos += returnTimeNanos; taskStats.nrSamples++; if (logLevel >= 2) { final String name = "thread" + Thread.currentThread().getName(); System.out.println("result " + taskStats.nrSamples + '\t' + name + '\t' + "borrow time: " + Duration.ofNanos(borrowTimeNanos) + '\t' + "return time: " + Duration.ofNanos(returnTimeNanos) + '\t' + "waiting: " + taskStats.waiting + '\t' + "complete: " + taskStats.complete); } } return taskStats; } public void runOnce() { try { taskStats.waiting++; if (logLevel >= 5) { final String name = "thread" + Thread.currentThread().getName(); System.out.println(name + " waiting: " + taskStats.waiting + " complete: " + taskStats.complete); } final long bbeginNanos = System.nanoTime(); final Integer o = pool.borrowObject(); final long bendNanos = System.nanoTime(); taskStats.waiting--; if (logLevel >= 3) { final String name = "thread" + Thread.currentThread().getName(); System.out.println(name + " waiting: " + taskStats.waiting + " complete: " + taskStats.complete); } final long rbeginNanos = System.nanoTime(); pool.returnObject(o); final long rendNanos = System.nanoTime(); Thread.yield(); taskStats.complete++; borrowTimeNanos = bendNanos - bbeginNanos; returnTimeNanos = rendNanos - rbeginNanos; } catch (final Exception e) { e.printStackTrace(); } } } private static final class TaskStats { public int waiting; public int complete; public long totalBorrowNanos; public long totalReturnNanos; public int nrSamples; } public static void main(final String[] args) { final PerformanceTest test = new PerformanceTest(); test.setLogLevel(0); System.out.println("Increase threads"); test.run(1, 50, 5, 5); test.run(1, 100, 5, 5); test.run(1, 200, 5, 5); test.run(1, 400, 5, 5); System.out.println("Increase threads & poolSize"); test.run(1, 50, 5, 5); test.run(1, 100, 10, 10); test.run(1, 200, 20, 20); test.run(1, 400, 40, 40); System.out.println("Increase maxIdle"); test.run(1, 400, 40, 5); test.run(1, 400, 40, 40); // System.out.println("Show creation/destruction of objects"); // test.setLogLevel(4); // test.run(1, 400, 40, 5); } private int logLevel; private int nrIterations = 5; private GenericObjectPool<Integer, RuntimeException> pool; private void run(final int iterations, final int nrThreads, final int maxTotal, final int maxIdle) { this.nrIterations = iterations; final SleepingObjectFactory factory = new SleepingObjectFactory(); if (logLevel >= 4) { factory.setDebug(true); } pool = new GenericObjectPool<>(factory); pool.setMaxTotal(maxTotal); pool.setMaxIdle(maxIdle); pool.setTestOnBorrow(true); final ExecutorService threadPool = Executors.newFixedThreadPool(nrThreads); final List<Callable<TaskStats>> tasks = new ArrayList<>(); for (int i = 0; i < nrThreads; i++) { tasks.add(new PerfTask()); Thread.yield(); } if (logLevel >= 1) { System.out.println("created"); } Thread.yield(); List<Future<TaskStats>> futures = null; try { futures = threadPool.invokeAll(tasks); } catch (final InterruptedException e) { e.printStackTrace(); } if (logLevel >= 1) { System.out.println("started"); } Thread.yield(); if (logLevel >= 1) { System.out.println("go"); } Thread.yield(); if (logLevel >= 1) { System.out.println("finish"); } final TaskStats aggregate = new TaskStats(); if (futures != null) { for (final Future<TaskStats> future : futures) { TaskStats taskStats = null; try { taskStats = future.get(); } catch (final InterruptedException | ExecutionException e) { e.printStackTrace(); } if (taskStats != null) { aggregate.complete += taskStats.complete; aggregate.nrSamples += taskStats.nrSamples; aggregate.totalBorrowNanos += taskStats.totalBorrowNanos; aggregate.totalReturnNanos += taskStats.totalReturnNanos; aggregate.waiting += taskStats.waiting; } } } final Duration totalBorrowDuration = Duration.ofNanos(aggregate.totalBorrowNanos); final Duration totalReturnDuration = Duration.ofNanos(aggregate.totalReturnNanos); System.out.println("-----------------------------------------"); System.out.println("nrIterations: " + iterations); System.out.println("nrThreads: " + nrThreads); System.out.println("maxTotal: " + maxTotal); System.out.println("maxIdle: " + maxIdle); System.out.println("nrSamples: " + aggregate.nrSamples); System.out.println("totalBorrowTime: " + totalBorrowDuration); System.out.println("totalReturnTime: " + totalReturnDuration); System.out.println("avg BorrowTime: " + totalBorrowDuration.dividedBy(aggregate.nrSamples)); System.out.println("avg ReturnTime: " + totalReturnDuration.dividedBy(aggregate.nrSamples)); threadPool.shutdown(); } public void setLogLevel(final int i) { logLevel = i; } }
5,233
0
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/performance/SleepingObjectFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.performance; import org.apache.commons.pool3.PooledObject; import org.apache.commons.pool3.PooledObjectFactory; import org.apache.commons.pool3.Waiter; import org.apache.commons.pool3.impl.DefaultPooledObject; /** * Sleepy ObjectFactory (everything takes a while longer) */ public class SleepingObjectFactory implements PooledObjectFactory<Integer, RuntimeException> { private int counter; private boolean debug; @Override public void activateObject(final PooledObject<Integer> obj) { debug("activateObject", obj); Waiter.sleepQuietly(10); } private void debug(final String method, final Object obj) { if (debug) { final String thread = "thread" + Thread.currentThread().getName(); System.out.println(thread + ": " + method + " " + obj); } } @Override public void destroyObject(final PooledObject<Integer> obj) { debug("destroyObject", obj); Waiter.sleepQuietly(250); } public boolean isDebug() { return debug; } @Override public PooledObject<Integer> makeObject() { // Deliberate choice to create a new object in case future unit tests // check for a specific object. final Integer obj = Integer.valueOf(counter++); debug("makeObject", obj); Waiter.sleepQuietly(500); return new DefaultPooledObject<>(obj); } @Override public void passivateObject(final PooledObject<Integer> obj) { debug("passivateObject", obj); Waiter.sleepQuietly(10); } public void setDebug(final boolean b) { debug = b; } @Override public boolean validateObject(final PooledObject<Integer> obj) { debug("validateObject", obj); Waiter.sleepQuietly(30); return true; } }
5,234
0
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/pool407/KeyedPool407Config.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.pool407; import java.time.Duration; import org.apache.commons.pool3.impl.GenericKeyedObjectPoolConfig; public final class KeyedPool407Config extends GenericKeyedObjectPoolConfig<KeyedPool407Fixture> { public KeyedPool407Config(final Duration poolConfigMaxWait) { setBlockWhenExhausted(Pool407Constants.BLOCK_WHEN_EXHAUSTED); setMaxTotalPerKey(Pool407Constants.MAX_TOTAL); setMaxWait(poolConfigMaxWait); } }
5,235
0
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/pool407/Pool407Config.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.pool407; import java.time.Duration; import org.apache.commons.pool3.impl.GenericObjectPoolConfig; /** * Tests POOL-407. */ public final class Pool407Config extends GenericObjectPoolConfig<Pool407Fixture> { public Pool407Config(final Duration poolConfigMaxWait) { setBlockWhenExhausted(Pool407Constants.BLOCK_WHEN_EXHAUSTED); setMaxTotal(Pool407Constants.MAX_TOTAL); setMaxWait(poolConfigMaxWait); } }
5,236
0
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/pool407/Pool407Fixture.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.pool407; public final class Pool407Fixture { // empty }
5,237
0
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/pool407/KeyedPool407Test.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.pool407; import java.time.Duration; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.apache.commons.pool3.PooledObject; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; /** * Tests POOL-407. */ public class KeyedPool407Test extends AbstractPool407Test { /** * Borrows from a pool and then immediately returns to that a pool. */ private static final class KeyedPool407RoundtripRunnable implements Runnable { private final KeyedPool407 pool; public KeyedPool407RoundtripRunnable(final KeyedPool407 pool) { this.pool = pool; } @Override public void run() { try { final KeyedPool407Fixture object = pool.borrowObject(KEY); if (object != null) { pool.returnObject(KEY, object); } } catch (final Exception e) { throw new RuntimeException(e); } } } private static final String KEY = "key"; protected void assertShutdown(final ExecutorService executor, final Duration poolConfigMaxWait, final AbstractKeyedPool407Factory factory) throws InterruptedException { // Old note: This never finishes when the factory makes nulls because two threads are stuck forever // If a factory always returns a null object or a null poolable object, then we will wait forever. // This would also be true is object validation always fails. executor.shutdown(); final boolean termination = executor.awaitTermination(Pool407Constants.AWAIT_TERMINATION_SECONDS, TimeUnit.SECONDS); // Order matters: test create() before makeObject() // Calling create() here in this test should not have side-effects final KeyedPool407Fixture obj = factory.create(KEY); // Calling makeObject() here in this test should not have side-effects final PooledObject<KeyedPool407Fixture> pooledObject = obj != null ? factory.makeObject(KEY) : null; assertShutdown(termination, poolConfigMaxWait, obj, pooledObject); } private void test(final AbstractKeyedPool407Factory factory, final int poolSize, final Duration poolConfigMaxWait) throws InterruptedException { final ExecutorService executor = Executors.newFixedThreadPool(poolSize); try (final KeyedPool407 pool = new KeyedPool407(factory, poolConfigMaxWait)) { // Start 'poolSize' threads that try to borrow a Pool407Fixture with the same key for (int i = 0; i < poolSize; i++) { executor.execute(new KeyedPool407RoundtripRunnable(pool)); } assertShutdown(executor, poolConfigMaxWait, factory); } } @Test public void testNormalFactoryNonNullFixtureWaitMax() throws InterruptedException { test(new KeyedPool407NormalFactory(new KeyedPool407Fixture()), Pool407Constants.POOL_SIZE, Pool407Constants.WAIT_FOREVER); } @Disabled @Test public void testNormalFactoryNullFixtureWaitMax() throws InterruptedException { test(new KeyedPool407NormalFactory(null), Pool407Constants.POOL_SIZE, Pool407Constants.WAIT_FOREVER); } @Disabled @Test public void testNullObjectFactoryWaitMax() throws InterruptedException { test(new KeyedPool407NullObjectFactory(), Pool407Constants.POOL_SIZE, Pool407Constants.WAIT_FOREVER); } @Disabled @Test public void testNullObjectFactoryWaitShort() throws InterruptedException { test(new KeyedPool407NullObjectFactory(), Pool407Constants.POOL_SIZE, Pool407Constants.WAIT_SHORT); } @Disabled @Test public void testNullPoolableFactoryWaitMax() throws InterruptedException { test(new KeyedPool407NullPoolableObjectFactory(), Pool407Constants.POOL_SIZE, Pool407Constants.WAIT_FOREVER); } @Disabled @Test public void testNullPoolableFactoryWaitShort() throws InterruptedException { test(new KeyedPool407NullPoolableObjectFactory(), Pool407Constants.POOL_SIZE, Pool407Constants.WAIT_SHORT); } }
5,238
0
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/pool407/Pool407NormalFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.pool407; import org.apache.commons.pool3.PooledObject; import org.apache.commons.pool3.impl.DefaultPooledObject; /** * Tests POOL-407. */ public final class Pool407NormalFactory extends AbstractPool407Factory { private final Pool407Fixture fixture; Pool407NormalFactory(final Pool407Fixture fixture) { this.fixture = fixture; } @Override public Pool407Fixture create() { // When this returns null, we fail-fast internally and borrowsObject() throws an exception. // // Old note: // This is key to the test, creation failed and returns null for instance see // https://github.com/openhab/openhab-core/blob/main/bundles/org.openhab.core.io.transport.modbus/src/main/java/org/openhab/core/io/transport/modbus/internal/pooling/ModbusSlaveConnectionFactoryImpl.java#L163 // the test passes when this returns new Pool407Fixture(); return fixture; } @Override boolean isDefaultMakeObject() { return true; } @Override boolean isNullFactory() { return fixture == null; } @Override public PooledObject<Pool407Fixture> wrap(final Pool407Fixture value) { // value will never be null here. return new DefaultPooledObject<>(value); } }
5,239
0
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/pool407/AbstractPool407Test.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.pool407; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import java.time.Duration; import org.apache.commons.pool3.PooledObject; /** * Tests POOL-407. */ public class AbstractPool407Test { protected <T> void assertShutdown(final boolean termination, final Duration poolConfigMaxWait, final T obj, final PooledObject<T> pooledObject) { if (pooledObject != null) { // The factory makes non-null objects and non-null PooledObjects, // therefore the ExecutorService should terminate when requested, without delay. assertTrue(termination); } else { // The factory makes null objects or null PooledObjects, // therefore the ExecutorService should keep trying to create objects as configured in the pool's config object. if (poolConfigMaxWait.equals(Pool407Constants.WAIT_FOREVER)) { // If poolConfigMaxWait is maxed out, then the ExecutorService will not shutdown without delay. if (obj == null) { // create() returned null, so wrap() was not even called, and borrowObject() fails fast. assertTrue(termination); } else { // The ExecutorService fails to terminate when requested because assertFalse(true); } } else { // If poolConfigMaxWait is short, then the ExecutorService should usually shutdown without delay. assertTrue(termination); } } } }
5,240
0
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/pool407/AbstractPool407Factory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.pool407; import org.apache.commons.pool3.BasePooledObjectFactory; import org.apache.commons.pool3.PooledObject; /** * Tests POOL-407. */ public abstract class AbstractPool407Factory extends BasePooledObjectFactory<Pool407Fixture, RuntimeException> { /** * Tests whether the subclass relies on the Pool's implementation of makeObject(). If the subclass returns false, then it implements makeObject(), in which * case makeObject() returns a bad object like null or a null wrapper. */ abstract boolean isDefaultMakeObject(); /** * Tests whether this instance makes null or null wrappers. * * @return whether this instance makes null or null wrappers. */ abstract boolean isNullFactory(); @Override public boolean validateObject(final PooledObject<Pool407Fixture> p) { // TODO Should this be enough even if wrap() does throw and returns a DefaultPooledObject wrapping a null? return !PooledObject.isNull(p); } }
5,241
0
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/pool407/KeyedPool407NullObjectFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.pool407; import org.apache.commons.pool3.PooledObject; import org.apache.commons.pool3.impl.DefaultPooledObject; /** * Tests POOL-407. */ public final class KeyedPool407NullObjectFactory extends AbstractKeyedPool407Factory { @Override public KeyedPool407Fixture create(final String key) { return null; } @Override boolean isDefaultMakeObject() { return false; } @Override public PooledObject<KeyedPool407Fixture> makeObject(final String key) throws RuntimeException { return new DefaultPooledObject<>(null); } @Override public PooledObject<KeyedPool407Fixture> wrap(final KeyedPool407Fixture value) { return new DefaultPooledObject<>(null); } }
5,242
0
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/pool407/KeyedPool407.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.pool407; import java.time.Duration; import org.apache.commons.pool3.BaseKeyedPooledObjectFactory; import org.apache.commons.pool3.impl.BaseObjectPoolConfig; import org.apache.commons.pool3.impl.GenericKeyedObjectPool; public final class KeyedPool407 extends GenericKeyedObjectPool<String, KeyedPool407Fixture, RuntimeException> { public KeyedPool407(final BaseKeyedPooledObjectFactory<String, KeyedPool407Fixture, RuntimeException> factory, final Duration maxWait) { super(factory, new KeyedPool407Config(BaseObjectPoolConfig.DEFAULT_MAX_WAIT)); } }
5,243
0
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/pool407/AbstractKeyedPool407Factory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.pool407; import org.apache.commons.pool3.BaseKeyedPooledObjectFactory; import org.apache.commons.pool3.PooledObject; /** * Tests POOL-407. */ public abstract class AbstractKeyedPool407Factory extends BaseKeyedPooledObjectFactory<String, KeyedPool407Fixture, RuntimeException> { abstract boolean isDefaultMakeObject(); @Override public boolean validateObject(final String key, final PooledObject<KeyedPool407Fixture> p) { // TODO Should this be enough even if wrap() does throw and returns a DefaultPooledObject wrapping a null? return !PooledObject.isNull(p); } }
5,244
0
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/pool407/KeyedPool407Fixture.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.pool407; public final class KeyedPool407Fixture { // empty }
5,245
0
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/pool407/KeyedPool407NormalFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.pool407; import org.apache.commons.pool3.PooledObject; import org.apache.commons.pool3.impl.DefaultPooledObject; /** * Tests POOL-407. */ public final class KeyedPool407NormalFactory extends AbstractKeyedPool407Factory { private final KeyedPool407Fixture fixture; KeyedPool407NormalFactory(final KeyedPool407Fixture fixture) { this.fixture = fixture; } @Override public KeyedPool407Fixture create(final String key) { // This is key to the test, creation failed and returns null for instance see // https://github.com/openhab/openhab-core/blob/main/bundles/org.openhab.core.io.transport.modbus/src/main/java/org/openhab/core/io/transport/modbus/internal/pooling/ModbusSlaveConnectionFactoryImpl.java#L163 // the test passes when this returns new Pool407Fixture(); return fixture; } @Override boolean isDefaultMakeObject() { return true; } @Override public PooledObject<KeyedPool407Fixture> wrap(final KeyedPool407Fixture value) { // value will never be null here. return new DefaultPooledObject<>(value); } }
5,246
0
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/pool407/KeyedPool407NullPoolableObjectFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.pool407; import org.apache.commons.pool3.PooledObject; /** * Tests POOL-407. */ public final class KeyedPool407NullPoolableObjectFactory extends AbstractKeyedPool407Factory { @Override public KeyedPool407Fixture create(final String key) { return null; } @Override boolean isDefaultMakeObject() { return false; } @Override public PooledObject<KeyedPool407Fixture> makeObject(final String key) throws RuntimeException { return null; } @Override public PooledObject<KeyedPool407Fixture> wrap(final KeyedPool407Fixture value) { return null; } }
5,247
0
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/pool407/Pool407NullObjectFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.pool407; import org.apache.commons.pool3.PooledObject; import org.apache.commons.pool3.impl.DefaultPooledObject; /** * Tests POOL-407. */ public final class Pool407NullObjectFactory extends AbstractPool407Factory { @Override public Pool407Fixture create() { // Never called because this class calls makeObject() and wrap(). return null; } @Override boolean isDefaultMakeObject() { return false; } @Override boolean isNullFactory() { return true; } @Override public PooledObject<Pool407Fixture> makeObject() throws RuntimeException { return new DefaultPooledObject<>(null); } @Override public PooledObject<Pool407Fixture> wrap(final Pool407Fixture value) { return new DefaultPooledObject<>(null); } }
5,248
0
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/pool407/Pool407Test.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.pool407; import java.time.Duration; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.apache.commons.pool3.PooledObject; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; /** * Tests POOL-407. */ public class Pool407Test extends AbstractPool407Test { /** * Borrows from a pool and then immediately returns to that a pool. */ private static final class Pool407RoundtripRunnable implements Runnable { private final Pool407 pool; public Pool407RoundtripRunnable(final Pool407 pool) { this.pool = pool; } @Override public void run() { try { final Pool407Fixture object = pool.borrowObject(); if (object != null) { pool.returnObject(object); } } catch (final Exception e) { throw new RuntimeException(e); } } } protected void assertShutdown(final ExecutorService executor, final Duration poolConfigMaxWait, final AbstractPool407Factory factory) throws InterruptedException { // Old note: This never finishes when the factory makes nulls because two threads are stuck forever // If a factory always returns a null object or a null poolable object, then we will wait forever. // This would also be true is object validation always fails. executor.shutdown(); final boolean termination = executor.awaitTermination(Pool407Constants.AWAIT_TERMINATION_SECONDS, TimeUnit.SECONDS); // Order matters: test create() before makeObject() // Calling create() here in this test should not have side-effects final Pool407Fixture obj = factory.create(); // Calling makeObject() here in this test should not have side-effects final PooledObject<Pool407Fixture> pooledObject = obj != null ? factory.makeObject() : null; assertShutdown(termination, poolConfigMaxWait, obj, pooledObject); } private void test(final AbstractPool407Factory factory, final int poolSize, final Duration poolConfigMaxWait) throws InterruptedException { final ExecutorService executor = Executors.newFixedThreadPool(poolSize); try (final Pool407 pool = new Pool407(factory, poolConfigMaxWait)) { // Start 'poolSize' threads that try to borrow a Pool407Fixture with the same key for (int i = 0; i < poolSize; i++) { executor.execute(new Pool407RoundtripRunnable(pool)); } assertShutdown(executor, poolConfigMaxWait, factory); } } @Test public void testNormalFactoryNonNullFixtureWaitMax() throws InterruptedException { test(new Pool407NormalFactory(new Pool407Fixture()), Pool407Constants.POOL_SIZE, Pool407Constants.WAIT_FOREVER); } @Test @Disabled public void testNormalFactoryNullFixtureWaitMax() throws InterruptedException { test(new Pool407NormalFactory(null), Pool407Constants.POOL_SIZE, Pool407Constants.WAIT_FOREVER); } @Disabled @Test public void testNullObjectFactoryWaitMax() throws InterruptedException { test(new Pool407NullObjectFactory(), Pool407Constants.POOL_SIZE, Pool407Constants.WAIT_FOREVER); } @Test @Disabled public void testNullObjectFactoryWaitShort() throws InterruptedException { test(new Pool407NullObjectFactory(), Pool407Constants.POOL_SIZE, Pool407Constants.WAIT_SHORT); } @Test @Disabled public void testNullPoolableFactoryWaitMax() throws InterruptedException { test(new Pool407NullPoolableObjectFactory(), Pool407Constants.POOL_SIZE, Pool407Constants.WAIT_FOREVER); } @Test @Disabled public void testNullPoolableFactoryWaitShort() throws InterruptedException { test(new Pool407NullPoolableObjectFactory(), Pool407Constants.POOL_SIZE, Pool407Constants.WAIT_SHORT); } }
5,249
0
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/pool407/Pool407Constants.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.pool407; import java.time.Duration; import org.apache.commons.pool3.impl.BaseObjectPoolConfig; /** * Tests POOL-407. */ final class Pool407Constants { static final int AWAIT_TERMINATION_SECONDS = 10; static final boolean BLOCK_WHEN_EXHAUSTED = true; static final int MAX_TOTAL = 1; static final int POOL_SIZE = 3; static final Duration WAIT_FOREVER = BaseObjectPoolConfig.DEFAULT_MAX_WAIT; static final Duration WAIT_SHORT = Duration.ofSeconds(1); }
5,250
0
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/pool407/Pool407NullPoolableObjectFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.pool407; import org.apache.commons.pool3.PooledObject; /** * Tests POOL-407. */ public final class Pool407NullPoolableObjectFactory extends AbstractPool407Factory { @Override public Pool407Fixture create() { return null; } @Override boolean isDefaultMakeObject() { return false; } @Override boolean isNullFactory() { return true; } @Override public PooledObject<Pool407Fixture> makeObject() throws RuntimeException { return null; } @Override public PooledObject<Pool407Fixture> wrap(final Pool407Fixture value) { return null; } }
5,251
0
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3
Create_ds/commons-pool/src/test/java/org/apache/commons/pool3/pool407/Pool407.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.pool407; import java.time.Duration; import org.apache.commons.pool3.BasePooledObjectFactory; import org.apache.commons.pool3.impl.GenericObjectPool; /** * Tests POOL-407. */ public final class Pool407 extends GenericObjectPool<Pool407Fixture, RuntimeException> { public Pool407(final BasePooledObjectFactory<Pool407Fixture, RuntimeException> factory, final Duration poolConfigMaxWait) { super(factory, new Pool407Config(poolConfigMaxWait)); } }
5,252
0
Create_ds/commons-pool/src/main/java/org/apache/commons
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3/DestroyMode.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3; /** * Destroy context provided to object factories via {@code destroyObject} and {@code invalidateObject} methods. Values * provide information about why the pool is asking for a pooled object to be destroyed. * * @since 2.9.0 */ public enum DestroyMode { /** Normal destroy. */ NORMAL, /** Destroy abandoned object. */ ABANDONED }
5,253
0
Create_ds/commons-pool/src/main/java/org/apache/commons
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3/PooledObjectFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3; /** * An interface defining life-cycle methods for instances to be served by an * {@link ObjectPool}. * <p> * By contract, when an {@link ObjectPool} delegates to a * {@link PooledObjectFactory}, * </p> * <ol> * <li> * {@link #makeObject} is called whenever a new instance is needed. * </li> * <li> * {@link #activateObject} is invoked on every instance that has been * {@link #passivateObject passivated} before it is * {@link ObjectPool#borrowObject borrowed} from the pool. * </li> * <li> * {@link #validateObject} may be invoked on {@link #activateObject activated} * instances to make sure they can be {@link ObjectPool#borrowObject borrowed} * from the pool. {@link #validateObject} may also be used to * test an instance being {@link ObjectPool#returnObject returned} to the pool * before it is {@link #passivateObject passivated}. It will only be invoked * on an activated instance. * </li> * <li> * {@link #passivateObject} is invoked on every instance when it is returned * to the pool. * </li> * <li> * {@link #destroyObject} is invoked on every instance when it is being * "dropped" from the pool (whether due to the response from * {@link #validateObject}, or for reasons specific to the pool * implementation.) There is no guarantee that the instance being destroyed * will be considered active, passive or in a generally consistent state. * </li> * </ol> * {@link PooledObjectFactory} must be thread-safe. The only promise * an {@link ObjectPool} makes is that the same instance of an object will not * be passed to more than one method of a {@code PoolableObjectFactory} * at a time. * <p> * While clients of a {@link KeyedObjectPool} borrow and return instances of * the underlying value type {@code V}, the factory methods act on instances of * {@link PooledObject PooledObject&lt;V&gt;}. These are the object wrappers that * pools use to track and maintain state information about the objects that * they manage. * </p> * * @param <T> Type of element managed in this factory. * @param <E> Type of exception thrown in this factory. * * @see ObjectPool * * @since 2.0 */ public interface PooledObjectFactory<T, E extends Exception> { /** * Reinitializes an instance to be returned by the pool. * * @param p a {@code PooledObject} wrapping the instance to be activated * * @throws E if there is a problem activating {@code obj}, * this exception may be swallowed by the pool. * * @see #destroyObject */ void activateObject(PooledObject<T> p) throws E; /** * Destroys an instance no longer needed by the pool, using the default (NORMAL) * DestroyMode. * <p> * It is important for implementations of this method to be aware that there * is no guarantee about what state {@code obj} will be in and the * implementation should be prepared to handle unexpected errors. * </p> * <p> * Also, an implementation must take in to consideration that instances lost * to the garbage collector may never be destroyed. * </p> * * @param p a {@code PooledObject} wrapping the instance to be destroyed * * @throws E should be avoided as it may be swallowed by * the pool implementation. * * @see #validateObject * @see ObjectPool#invalidateObject */ void destroyObject(PooledObject<T> p) throws E; /** * Destroys an instance no longer needed by the pool, using the provided * DestroyMode. * * @param p a {@code PooledObject} wrapping the instance to be destroyed * @param destroyMode DestroyMode providing context to the factory * * @throws E should be avoided as it may be swallowed by * the pool implementation. * * @see #validateObject * @see ObjectPool#invalidateObject * @see #destroyObject(PooledObject) * @see DestroyMode * @since 2.9.0 */ default void destroyObject(final PooledObject<T> p, final DestroyMode destroyMode) throws E { destroyObject(p); } /** * Creates an instance that can be served by the pool and wrap it in a * {@link PooledObject} to be managed by the pool. * * @return a {@code PooledObject} wrapping an instance that can be served by the pool, not null. * * @throws E if there is a problem creating a new instance, * this will be propagated to the code requesting an object. */ PooledObject<T> makeObject() throws E; /** * Uninitializes an instance to be returned to the idle object pool. * * @param p a {@code PooledObject} wrapping the instance to be passivated * * @throws E if there is a problem passivating {@code obj}, * this exception may be swallowed by the pool. * * @see #destroyObject */ void passivateObject(PooledObject<T> p) throws E; /** * Ensures that the instance is safe to be returned by the pool. * * @param p a {@code PooledObject} wrapping the instance to be validated * * @return {@code false} if {@code obj} is not valid and should * be dropped from the pool, {@code true} otherwise. */ boolean validateObject(PooledObject<T> p); }
5,254
0
Create_ds/commons-pool/src/main/java/org/apache/commons
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3/KeyedObjectPool.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3; import java.io.Closeable; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.NoSuchElementException; /** * A "keyed" pooling interface. * <p> * A keyed pool maintains a pool of instances for each key value. * </p> * <p> * Example of use: * </p> * <pre style="border:solid thin; padding: 1ex;" * > Object obj = <code style="color:#00C">null</code>; * Object key = <code style="color:#C00">"Key"</code>; * * <code style="color:#00C">try</code> { * obj = pool.borrowObject(key); * <code style="color:#0C0">//...use the object...</code> * } <code style="color:#00C">catch</code> (Exception e) { * <code style="color:#0C0">// invalidate the object</code> * pool.invalidateObject(key, obj); * <code style="color:#0C0">// do not return the object to the pool twice</code> * obj = <code style="color:#00C">null</code>; * } <code style="color:#00C">finally</code> { * <code style="color:#0C0">// make sure the object is returned to the pool</code> * <code style="color:#00C">if</code> (<code style="color:#00C">null</code> != obj) { * pool.returnObject(key, obj); * } * }</pre> * <p> * {@link KeyedObjectPool} implementations <i>may</i> choose to store at most * one instance per key value, or may choose to maintain a pool of instances * for each key (essentially creating a {@link java.util.Map Map} of * {@link ObjectPool pools}). * </p> * <p> * See {@link org.apache.commons.pool3.impl.GenericKeyedObjectPool * GenericKeyedObjectPool} for an implementation. * </p> * * @param <K> The type of keys maintained by this pool. * @param <V> Type of element pooled in this pool. * @param <E> Type of exception thrown by this pool. * * @see KeyedPooledObjectFactory * @see ObjectPool * @see org.apache.commons.pool3.impl.GenericKeyedObjectPool GenericKeyedObjectPool * * @since 2.0 */ public interface KeyedObjectPool<K, V, E extends Exception> extends Closeable { /** * Creates an object using the {@link KeyedPooledObjectFactory factory} or * other implementation dependent mechanism, passivate it, and then place it * in the idle object pool. {@code addObject} is useful for * "pre-loading" a pool with idle objects (Optional operation). * * @param key the key a new instance should be added to * * @throws E * when {@link KeyedPooledObjectFactory#makeObject} fails. * @throws IllegalStateException * after {@link #close} has been called on this pool. * @throws UnsupportedOperationException * when this pool cannot add new idle objects. */ void addObject(K key) throws E, IllegalStateException, UnsupportedOperationException; /** * Calls {@link KeyedObjectPool#addObject(Object)} with each * key in {@code keys} for {@code count} number of times. This has * the same effect as calling {@link #addObjects(Object, int)} * for each key in the {@code keys} collection. * * @param keys * {@link Collection} of keys to add objects for. * @param count * the number of idle objects to add for each {@code key}. * @throws E * when {@link KeyedObjectPool#addObject(Object)} fails. * @throws IllegalArgumentException * when {@code keyedPool}, {@code keys}, or any value * in {@code keys} is {@code null}. * @see #addObjects(Object, int) */ default void addObjects(final Collection<K> keys, final int count) throws E, IllegalArgumentException { if (keys == null) { throw new IllegalArgumentException(PoolUtils.MSG_NULL_KEYS); } for (final K key : keys) { addObjects(key, count); } } /** * Calls {@link KeyedObjectPool#addObject(Object)} * {@code key} {@code count} number of times. * * @param key * the key to add objects for. * @param count * the number of idle objects to add for {@code key}. * @throws E * when {@link KeyedObjectPool#addObject(Object)} fails. * @throws IllegalArgumentException * when {@code key} is {@code null}. * @since 2.8.0 */ default void addObjects(final K key, final int count) throws E, IllegalArgumentException { if (key == null) { throw new IllegalArgumentException(PoolUtils.MSG_NULL_KEY); } for (int i = 0; i < count; i++) { addObject(key); } } /** * Borrows an instance from this pool for the specified {@code key}. * <p> * Instances returned from this method will have been either newly created * with {@link KeyedPooledObjectFactory#makeObject makeObject} or will be * a previously idle object and have been activated with * {@link KeyedPooledObjectFactory#activateObject activateObject} and then * (optionally) validated with * {@link KeyedPooledObjectFactory#validateObject validateObject}. * </p> * <p> * By contract, clients <strong>must</strong> return the borrowed object * using {@link #returnObject returnObject}, * {@link #invalidateObject invalidateObject}, or a related method as * defined in an implementation or sub-interface, using a {@code key} * that is {@link Object#equals equivalent} to the one used to borrow the * instance in the first place. * </p> * <p> * The behavior of this method when the pool has been exhausted is not * strictly specified (although it may be specified by implementations). * </p> * * @param key the key used to obtain the object * * @return an instance from this pool. * * @throws IllegalStateException * after {@link #close close} has been called on this pool * @throws E * when {@link KeyedPooledObjectFactory#makeObject * makeObject} throws an exception * @throws NoSuchElementException * when the pool is exhausted and cannot or will not return * another instance */ V borrowObject(K key) throws E, NoSuchElementException, IllegalStateException; /** * Clears the pool, removing all pooled instances (optional operation). * * @throws UnsupportedOperationException when this implementation doesn't * support the operation * * @throws E if the pool cannot be cleared */ void clear() throws E, UnsupportedOperationException; /** * Clears the specified pool, removing all pooled instances corresponding to * the given {@code key} (optional operation). * * @param key the key to clear * * @throws UnsupportedOperationException when this implementation doesn't * support the operation * * @throws E if the key cannot be cleared */ void clear(K key) throws E, UnsupportedOperationException; /** * Closes this pool, and free any resources associated with it. * <p> * Calling {@link #addObject addObject} or * {@link #borrowObject borrowObject} after invoking this method on a pool * will cause them to throw an {@link IllegalStateException}. * </p> * <p> * Implementations should silently fail if not all resources can be freed. * </p> */ @Override void close(); /** * Gets a copy of the pool key list. * * @return a copy of the pool key list. * @since 2.12.0 */ default List<K> getKeys() { return Collections.emptyList(); } /** * Gets the total number of instances currently borrowed from this pool but * not yet returned. Returns a negative value if this information is not * available. * @return the total number of instances currently borrowed from this pool but * not yet returned. */ int getNumActive(); /** * Gets the number of instances currently borrowed from but not yet * returned to the pool corresponding to the given {@code key}. * Returns a negative value if this information is not available. * * @param key the key to query * @return the number of instances currently borrowed from but not yet * returned to the pool corresponding to the given {@code key}. */ int getNumActive(K key); /** * Gets the total number of instances currently idle in this pool. * Returns a negative value if this information is not available. * @return the total number of instances currently idle in this pool. */ int getNumIdle(); /** * Gets the number of instances corresponding to the given * {@code key} currently idle in this pool. Returns a negative value if * this information is not available. * * @param key the key to query * @return the number of instances corresponding to the given * {@code key} currently idle in this pool. */ int getNumIdle(K key); /** * Invalidates an object from the pool. * <p> * By contract, {@code obj} <strong>must</strong> have been obtained * using {@link #borrowObject borrowObject} or a related method as defined * in an implementation or sub-interface using a {@code key} that is * equivalent to the one used to borrow the {@code Object} in the first * place. * </p> * <p> * This method should be used when an object that has been borrowed is * determined (due to an exception or other problem) to be invalid. * </p> * * @param key the key used to obtain the object * @param obj a {@link #borrowObject borrowed} instance to be returned. * * @throws E if the instance cannot be invalidated */ void invalidateObject(K key, V obj) throws E; /** * Invalidates an object from the pool, using the provided * {@link DestroyMode}. * <p> * By contract, {@code obj} <strong>must</strong> have been obtained * using {@link #borrowObject borrowObject} or a related method as defined * in an implementation or sub-interface using a {@code key} that is * equivalent to the one used to borrow the {@code Object} in the first * place. * </p> * <p> * This method should be used when an object that has been borrowed is * determined (due to an exception or other problem) to be invalid. * </p> * * @param key the key used to obtain the object * @param obj a {@link #borrowObject borrowed} instance to be returned. * @param destroyMode destroy activation context provided to the factory * * @throws E if the instance cannot be invalidated * @since 2.9.0 */ default void invalidateObject(final K key, final V obj, final DestroyMode destroyMode) throws E { invalidateObject(key, obj); } /** * Return an instance to the pool. By contract, {@code obj} * <strong>must</strong> have been obtained using * {@link #borrowObject borrowObject} or a related method as defined in an * implementation or sub-interface using a {@code key} that is * equivalent to the one used to borrow the instance in the first place. * * @param key the key used to obtain the object * @param obj a {@link #borrowObject borrowed} instance to be returned. * * @throws IllegalStateException * if an attempt is made to return an object to the pool that * is in any state other than allocated (i.e. borrowed). * Attempting to return an object more than once or attempting * to return an object that was never borrowed from the pool * will trigger this exception. * * @throws E if an instance cannot be returned to the pool */ void returnObject(K key, V obj) throws E; }
5,255
0
Create_ds/commons-pool/src/main/java/org/apache/commons
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3/KeyedPooledObjectFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3; /** * An interface defining life-cycle methods for * instances to be served by a {@link KeyedObjectPool}. * <p> * By contract, when an {@link KeyedObjectPool} * delegates to a {@link KeyedPooledObjectFactory}, * </p> * <ol> * <li> * {@link #makeObject} is called whenever a new instance is needed. * </li> * <li> * {@link #activateObject} is invoked on every instance that has been * {@link #passivateObject passivated} before it is * {@link KeyedObjectPool#borrowObject borrowed} from the pool. * </li> * <li> * {@link #validateObject} may be invoked on {@link #activateObject activated} * instances to make sure they can be * {@link KeyedObjectPool#borrowObject borrowed} from the pool. * {@code validateObject} may also be used to test an * instance being {@link KeyedObjectPool#returnObject returned} to the pool * before it is {@link #passivateObject passivated}. It will only be invoked * on an activated instance. * </li> * <li> * {@link #passivateObject passivateObject} * is invoked on every instance when it is returned to the pool. * </li> * <li> * {@link #destroyObject destroyObject} * is invoked on every instance when it is being "dropped" from the * pool (whether due to the response from {@code validateObject}, * or for reasons specific to the pool implementation.) There is no * guarantee that the instance being destroyed will * be considered active, passive or in a generally consistent state. * </li> * </ol> * {@link KeyedPooledObjectFactory} must be thread-safe. The only promise * an {@link KeyedObjectPool} makes is that the same instance of an object will * not be passed to more than one method of a * {@code KeyedPooledObjectFactory} at a time. * <p> * While clients of a {@link KeyedObjectPool} borrow and return instances of * the underlying value type V, the factory methods act on instances of * {@link PooledObject PooledObject&lt;V&gt;}. These are the object wrappers that * pools use to track and maintain state informations about the objects that * they manage. * </p> * * @see KeyedObjectPool * @see BaseKeyedPooledObjectFactory * * @param <K> The type of keys managed by this factory. * @param <V> Type of element managed by this factory. * @param <E> Type of exception thrown by this factory. * * @since 2.0 */ public interface KeyedPooledObjectFactory<K, V, E extends Exception> { /** * Reinitializes an instance to be returned by the pool. * * @param key the key used when selecting the object * @param p a {@code PooledObject} wrapping the instance to be activated * * @throws E if there is a problem activating {@code obj}, * this exception may be swallowed by the pool. * * @see #destroyObject */ void activateObject(K key, PooledObject<V> p) throws E; /** * Destroys an instance no longer needed by the pool. * <p> * It is important for implementations of this method to be aware that there * is no guarantee about what state {@code obj} will be in and the * implementation should be prepared to handle unexpected errors. * </p> * <p> * Also, an implementation must take in to consideration that instances lost * to the garbage collector may never be destroyed. * </p> * * @param key the key used when selecting the instance * @param p a {@code PooledObject} wrapping the instance to be destroyed * * @throws E should be avoided as it may be swallowed by * the pool implementation. * * @see #validateObject * @see KeyedObjectPool#invalidateObject */ void destroyObject(K key, PooledObject<V> p) throws E; /** * Destroys an instance no longer needed by the pool, using the provided {@link DestroyMode}. * * @param key the key used when selecting the instance * @param p a {@code PooledObject} wrapping the instance to be destroyed * @param destroyMode DestroyMode providing context to the factory * * @throws E should be avoided as it may be swallowed by * the pool implementation. * * @see #validateObject * @see KeyedObjectPool#invalidateObject * @see #destroyObject(Object, PooledObject) * @see DestroyMode * @since 2.9.0 */ default void destroyObject(final K key, final PooledObject<V> p, final DestroyMode destroyMode) throws E { destroyObject(key, p); } /** * Creates an instance that can be served by the pool and * wrap it in a {@link PooledObject} to be managed by the pool. * * @param key the key used when constructing the object * * @return a {@code PooledObject} wrapping an instance that can * be served by the pool. * * @throws E if there is a problem creating a new instance, * this will be propagated to the code requesting an object. */ PooledObject<V> makeObject(K key) throws E; /** * Uninitializes an instance to be returned to the idle object pool. * * @param key the key used when selecting the object * @param p a {@code PooledObject} wrapping the instance to be passivated * * @throws E if there is a problem passivating {@code obj}, * this exception may be swallowed by the pool. * * @see #destroyObject */ void passivateObject(K key, PooledObject<V> p) throws E; /** * Ensures that the instance is safe to be returned by the pool. * * @param key the key used when selecting the object * @param p a {@code PooledObject} wrapping the instance to be validated * * @return {@code false} if {@code obj} is not valid and should * be dropped from the pool, {@code true} otherwise. */ boolean validateObject(K key, PooledObject<V> p); }
5,256
0
Create_ds/commons-pool/src/main/java/org/apache/commons
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3/BasePooledObjectFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3; import java.util.Objects; /** * A base implementation of {@code PoolableObjectFactory}. * <p> * All operations defined here are essentially no-op's. * <p> * This class is immutable, and therefore thread-safe * * @param <T> Type of element managed in this factory. * @param <E> Type of exception thrown in this factory. * * @see PooledObjectFactory * @see BaseKeyedPooledObjectFactory * * @since 2.0 */ public abstract class BasePooledObjectFactory<T, E extends Exception> extends BaseObject implements PooledObjectFactory<T, E> { /** * No-op. * * @param p ignored */ @Override public void activateObject(final PooledObject<T> p) throws E { // The default implementation is a no-op. } /** * Creates an object instance, to be wrapped in a {@link PooledObject}. * <p>This method <strong>must</strong> support concurrent, multi-threaded * invocation.</p> * * @return an instance to be served by the pool, not null. * * @throws E if there is a problem creating a new instance, * this will be propagated to the code requesting an object. */ public abstract T create() throws E; /** * No-op. * * @param p ignored */ @Override public void destroyObject(final PooledObject<T> p) throws E { // The default implementation is a no-op. } @Override public PooledObject<T> makeObject() throws E { return wrap(Objects.requireNonNull(create(), () -> String.format("BasePooledObjectFactory(%s).create() = null", getClass().getName()))); } /** * No-op. * * @param p ignored */ @Override public void passivateObject(final PooledObject<T> p) throws E { // The default implementation is a no-op. } /** * Always returns {@code true}. * * @param p ignored * * @return {@code true} */ @Override public boolean validateObject(final PooledObject<T> p) { return true; } /** * Wraps the provided instance with an implementation of * {@link PooledObject}. * * @param obj the instance to wrap, should not be null. * * @return The provided instance, wrapped by a {@link PooledObject} */ public abstract PooledObject<T> wrap(T obj); }
5,257
0
Create_ds/commons-pool/src/main/java/org/apache/commons
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3/UsageTracking.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3; /** * This interface may be implemented by an object pool to enable clients (primarily those clients that wrap pools to * provide pools with extended features) to provide additional information to the pool relating to object using allowing * more informed decisions and reporting to be made regarding abandoned objects. * * @param <T> The type of object provided by the pool. * * @since 2.0 */ public interface UsageTracking<T> { /** * Called every time a pooled object is used to enable the pool to better track borrowed objects. * * @param pooledObject The object that is being used. */ void use(T pooledObject); }
5,258
0
Create_ds/commons-pool/src/main/java/org/apache/commons
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3/BaseKeyedPooledObjectFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3; import java.util.Objects; /** * A base implementation of {@code KeyedPooledObjectFactory}. * <p> * All operations defined here are essentially no-op's. * </p> * <p> * This class is immutable, and therefore thread-safe. * </p> * * @see KeyedPooledObjectFactory * * @param <K> The type of keys managed by this factory. * @param <V> Type of element managed by this factory. * @param <E> Type of exception thrown by this factory. * * @since 2.0 */ public abstract class BaseKeyedPooledObjectFactory<K, V, E extends Exception> extends BaseObject implements KeyedPooledObjectFactory<K, V, E> { /** * Reinitializes an instance to be returned by the pool. * <p> * The default implementation is a no-op. * </p> * * @param key the key used when selecting the object * @param p a {@code PooledObject} wrapping the instance to be activated */ @Override public void activateObject(final K key, final PooledObject<V> p) throws E { // The default implementation is a no-op. } /** * Creates an instance that can be served by the pool. * * @param key the key used when constructing the object * @return an instance that can be served by the pool * * @throws E if there is a problem creating a new instance, * this will be propagated to the code requesting an object. */ public abstract V create(K key) throws E; /** * Destroys an instance no longer needed by the pool. * <p> * The default implementation is a no-op. * </p> * * @param key the key used when selecting the instance * @param p a {@code PooledObject} wrapping the instance to be destroyed */ @Override public void destroyObject(final K key, final PooledObject<V> p) throws E { // The default implementation is a no-op. } @Override public PooledObject<V> makeObject(final K key) throws E { return wrap( Objects.requireNonNull(create(key), () -> String.format("BaseKeyedPooledObjectFactory(%s).create(key=%s) = null", getClass().getName(), key))); } /** * Uninitializes an instance to be returned to the idle object pool. * <p> * The default implementation is a no-op. * </p> * * @param key the key used when selecting the object * @param p a {@code PooledObject} wrapping the instance to be passivated */ @Override public void passivateObject(final K key, final PooledObject<V> p) throws E { // The default implementation is a no-op. } /** * Ensures that the instance is safe to be returned by the pool. * <p> * The default implementation always returns {@code true}. * </p> * * @param key the key used when selecting the object * @param p a {@code PooledObject} wrapping the instance to be validated * @return always {@code true} in this default implementation */ @Override public boolean validateObject(final K key, final PooledObject<V> p) { return true; } /** * Wraps the provided instance with an implementation of * {@link PooledObject}. * * @param value the instance to wrap, should not be null. * @return The provided instance, wrapped by a {@link PooledObject} * @throws E if there is a problem wrapping an instance, * this will be propagated to the code requesting an object. */ public abstract PooledObject<V> wrap(V value) throws E; }
5,259
0
Create_ds/commons-pool/src/main/java/org/apache/commons
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3/SwallowedExceptionListener.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3; /** * Pools that unavoidably swallow exceptions may be configured with an instance * of this listener so the user may receive notification of when this happens. * The listener should not throw an exception when called but pools calling * listeners should protect themselves against exceptions anyway. * * @since 2.0 */ public interface SwallowedExceptionListener { /** * Notifies this instance every time the implementation unavoidably swallows * an exception. * * @param e The exception that was swallowed */ void onSwallowException(Exception e); }
5,260
0
Create_ds/commons-pool/src/main/java/org/apache/commons
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3/PooledObject.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3; import java.io.PrintWriter; import java.time.Duration; import java.time.Instant; import java.util.Deque; /** * Defines the wrapper that is used to track the additional information, such as * state, for the pooled objects. * <p> * Implementations of this class are required to be thread-safe. * </p> * * @param <T> the type of object in the pool. * @since 2.0 */ public interface PooledObject<T> extends Comparable<PooledObject<T>> { /** * Tests whether the given PooledObject is null <em>or</em> contains a null. * * @param pooledObject the PooledObject to test. * @return whether the given PooledObject is null <em>or</em> contains a null. * @since 2.12.0 */ static boolean isNull(final PooledObject<?> pooledObject) { return pooledObject == null || pooledObject.getObject() == null; } /** * Allocates the object. * * @return {@code true} if the original state was {@link PooledObjectState#IDLE IDLE} */ boolean allocate(); /** * Orders instances based on idle time - i.e. the length of time since the * instance was returned to the pool. Used by the GKOP idle object evictor. * <p> * Note: This class has a natural ordering that is inconsistent with * equals if distinct objects have the same identity hash code. * </p> * <p> * {@inheritDoc} * </p> */ @Override int compareTo(PooledObject<T> other); /** * Deallocates the object and sets it {@link PooledObjectState#IDLE IDLE} * if it is currently {@link PooledObjectState#ALLOCATED ALLOCATED}. * * @return {@code true} if the state was {@link PooledObjectState#ALLOCATED ALLOCATED}. */ boolean deallocate(); /** * Notifies the object that the eviction test has ended. * * @param idleQueue The queue of idle objects to which the object should be * returned. * @return Currently not used. */ boolean endEvictionTest(Deque<PooledObject<T>> idleQueue); @Override boolean equals(Object obj); /** * Gets the amount of time this object last spent in the active state (it may still be active in which case * subsequent calls will return an increased value). * * @return The duration last spent in the active state. * @since 2.11.0 */ default Duration getActiveDuration() { // Take copies to avoid threading issues final Instant lastReturnInstant = getLastReturnInstant(); final Instant lastBorrowInstant = getLastBorrowInstant(); // @formatter:off return lastReturnInstant.isAfter(lastBorrowInstant) ? Duration.between(lastBorrowInstant, lastReturnInstant) : Duration.between(lastBorrowInstant, Instant.now()); // @formatter:on } /** * Gets the number of times this object has been borrowed. * * @return -1 by default for implementations prior to release 2.7.0. * @since 2.7.0 */ default long getBorrowedCount() { return -1; } /** * Gets the time (using the same basis as {@link Instant#now()}) that this object was created. * * @return The creation time for the wrapped object. * @since 2.11.0 */ Instant getCreateInstant(); /** * Gets the duration since this object was created (using {@link Instant#now()}). * * @return The duration since this object was created. * @since 2.12.0 */ default Duration getFullDuration() { return Duration.between(getCreateInstant(), Instant.now()); } /** * Gets the amount of time that this object last spend in the * idle state (it may still be idle in which case subsequent calls will * return an increased value). * * @return The amount of time in last spent in the idle state. * @since 2.11.0 */ Duration getIdleDuration(); /** * Gets the time the wrapped object was last borrowed. * * @return The time the object was last borrowed. * @since 2.11.0 */ Instant getLastBorrowInstant(); /** * Gets the time the wrapped object was last borrowed. * * @return The time the object was last borrowed. * @since 2.11.0 */ Instant getLastReturnInstant(); /** * Gets an estimate of the last time this object was used. If the class of the pooled object implements * {@link TrackedUse}, what is returned is the maximum of {@link TrackedUse#getLastUsedInstant()} and * {@link #getLastBorrowInstant()}; otherwise this method gives the same value as {@link #getLastBorrowInstant()}. * * @return the last time this object was used * @since 2.11.0 */ Instant getLastUsedInstant(); /** * Gets the underlying object that is wrapped by this instance of * {@link PooledObject}. * * @return The wrapped object. */ T getObject(); /** * Gets the state of this object. * * @return state */ PooledObjectState getState(); @Override int hashCode(); /** * Sets the state to {@link PooledObjectState#INVALID INVALID}. */ void invalidate(); /** * Marks the pooled object as abandoned. */ void markAbandoned(); /** * Marks the object as returning to the pool. */ void markReturning(); /** * Prints the stack trace of the code that borrowed this pooled object and * the stack trace of the last code to use this object (if available) to * the supplied writer. * * @param writer The destination for the debug output. */ void printStackTrace(PrintWriter writer); /** * Sets whether to use abandoned object tracking. If this is true the * implementation will need to record the stack trace of the last caller to * borrow this object. * * @param logAbandoned The new configuration setting for abandoned * object tracking. */ void setLogAbandoned(boolean logAbandoned); /** * Sets the stack trace generation strategy based on whether or not fully detailed stack traces are required. * When set to false, abandoned logs may only include caller class information rather than method names, line * numbers, and other normal metadata available in a full stack trace. * * @param requireFullStackTrace the new configuration setting for abandoned object logging. * @since 2.7.0 */ default void setRequireFullStackTrace(final boolean requireFullStackTrace) { // noop } /** * Attempts to place the pooled object in the * {@link PooledObjectState#EVICTION} state. * * @return {@code true} if the object was placed in the * {@link PooledObjectState#EVICTION} state otherwise * {@code false}. */ boolean startEvictionTest(); /** * Gets a String form of the wrapper for debug purposes. The format is * not fixed and may change at any time. * * {@inheritDoc} */ @Override String toString(); /** * Records the current stack trace as the last time the object was used. */ void use(); }
5,261
0
Create_ds/commons-pool/src/main/java/org/apache/commons
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3/ObjectPool.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3; import java.io.Closeable; import java.util.NoSuchElementException; /** * A pooling simple interface. * <p> * Example of use: * </p> * <pre style="border:solid thin; padding: 1ex;" * > Object obj = <code style="color:#00C">null</code>; * * <code style="color:#00C">try</code> { * obj = pool.borrowObject(); * <code style="color:#00C">try</code> { * <code style="color:#0C0">//...use the object...</code> * } <code style="color:#00C">catch</code> (Exception e) { * <code style="color:#0C0">// invalidate the object</code> * pool.invalidateObject(obj); * <code style="color:#0C0">// do not return the object to the pool twice</code> * obj = <code style="color:#00C">null</code>; * } <code style="color:#00C">finally</code> { * <code style="color:#0C0">// make sure the object is returned to the pool</code> * <code style="color:#00C">if</code> (<code style="color:#00C">null</code> != obj) { * pool.returnObject(obj); * } * } * } <code style="color:#00C">catch</code>(Exception e) { * <code style="color:#0C0">// failed to borrow an object</code> * }</pre> * <p> * See {@link BaseObjectPool} for a simple base implementation. * </p> * * @param <T> Type of element pooled in this pool. * @param <E> Type of exception thrown by this pool. * * @see PooledObjectFactory * @see KeyedObjectPool * @see BaseObjectPool * * @since 2.0 */ public interface ObjectPool<T, E extends Exception> extends Closeable { /** * Creates an object using the {@link PooledObjectFactory factory} or other * implementation dependent mechanism, passivate it, and then place it in * the idle object pool. {@code addObject} is useful for "pre-loading" * a pool with idle objects. (Optional operation). * * @throws E * when {@link PooledObjectFactory#makeObject} fails. * @throws IllegalStateException * after {@link #close} has been called on this pool. * @throws UnsupportedOperationException * when this pool cannot add new idle objects. */ void addObject() throws E, IllegalStateException, UnsupportedOperationException; /** * Calls {@link ObjectPool#addObject()} {@code count} * number of times. * * @param count * the number of idle objects to add. * @throws E See {@link ObjectPool#addObject()}. * @since 2.8.0 */ default void addObjects(final int count) throws E { for (int i = 0; i < count; i++) { addObject(); } } /** * Borrows an instance from this pool. * <p> * Instances returned from this method will have been either newly created * with {@link PooledObjectFactory#makeObject} or will be a previously * idle object and have been activated with * {@link PooledObjectFactory#activateObject} and then validated with * {@link PooledObjectFactory#validateObject}. * </p> * <p> * By contract, clients <strong>must</strong> return the borrowed instance * using {@link #returnObject}, {@link #invalidateObject}, or a related * method as defined in an implementation or sub-interface. * </p> * <p> * The behavior of this method when the pool has been exhausted * is not strictly specified (although it may be specified by * implementations). * </p> * * @return an instance from this pool. * * @throws IllegalStateException * after {@link #close close} has been called on this pool. * @throws E * when {@link PooledObjectFactory#makeObject} throws an * exception. * @throws NoSuchElementException * when the pool is exhausted and cannot or will not return * another instance. */ T borrowObject() throws E, NoSuchElementException, IllegalStateException; /** * Clears any objects sitting idle in the pool, releasing any associated * resources (optional operation). Idle objects cleared must be * {@link PooledObjectFactory#destroyObject(PooledObject)}. * * @throws UnsupportedOperationException * if this implementation does not support the operation * * @throws E if the pool cannot be cleared */ void clear() throws E, UnsupportedOperationException; /** * Closes this pool, and free any resources associated with it. * <p> * Calling {@link #addObject} or {@link #borrowObject} after invoking this * method on a pool will cause them to throw an {@link IllegalStateException}. * </p> * <p> * Implementations should silently fail if not all resources can be freed. * </p> */ @Override void close(); /** * Gets the number of instances currently borrowed from this pool. Returns * a negative value if this information is not available. * @return the number of instances currently borrowed from this pool. */ int getNumActive(); /** * Gets the number of instances currently idle in this pool. This may be * considered an approximation of the number of objects that can be * {@link #borrowObject borrowed} without creating any new instances. * Returns a negative value if this information is not available. * @return the number of instances currently idle in this pool. */ int getNumIdle(); /** * Invalidates an object from the pool. * <p> * By contract, {@code obj} <strong>must</strong> have been obtained * using {@link #borrowObject} or a related method as defined in an * implementation or sub-interface. * </p> * <p> * This method should be used when an object that has been borrowed is * determined (due to an exception or other problem) to be invalid. * </p> * * @param obj a {@link #borrowObject borrowed} instance to be disposed. * * @throws E if the instance cannot be invalidated */ void invalidateObject(T obj) throws E; /** * Invalidates an object from the pool, using the provided * {@link DestroyMode} * <p> * By contract, {@code obj} <strong>must</strong> have been obtained * using {@link #borrowObject} or a related method as defined in an * implementation or sub-interface. * </p> * <p> * This method should be used when an object that has been borrowed is * determined (due to an exception or other problem) to be invalid. * </p> * * @param obj a {@link #borrowObject borrowed} instance to be disposed. * @param destroyMode destroy activation context provided to the factory * @throws E if the instance cannot be invalidated * @since 2.9.0 */ default void invalidateObject(final T obj, final DestroyMode destroyMode) throws E { invalidateObject(obj); } /** * Returns an instance to the pool. By contract, {@code obj} * <strong>must</strong> have been obtained using {@link #borrowObject()} or * a related method as defined in an implementation or sub-interface. * * @param obj a {@link #borrowObject borrowed} instance to be returned. * * @throws IllegalStateException * if an attempt is made to return an object to the pool that * is in any state other than allocated (i.e. borrowed). * Attempting to return an object more than once or attempting * to return an object that was never borrowed from the pool * will trigger this exception. * * @throws E if an instance cannot be returned to the pool */ void returnObject(T obj) throws E; }
5,262
0
Create_ds/commons-pool/src/main/java/org/apache/commons
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3/PoolUtils.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock; import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock; import java.util.function.Function; import java.util.stream.Collectors; /** * This class consists exclusively of static methods that operate on or return * ObjectPool or KeyedObjectPool related interfaces. * * @since 2.0 */ public final class PoolUtils { /** * Encapsulate the logic for when the next poolable object should be * discarded. Each time update is called, the next time to shrink is * recomputed, based on the float factor, number of idle instances in the * pool and high water mark. Float factor is assumed to be between 0 and 1. * Values closer to 1 cause less frequent erosion events. Erosion event * timing also depends on numIdle. When this value is relatively high (close * to previously established high water mark), erosion occurs more * frequently. */ private static final class ErodingFactor { /** Determines frequency of "erosion" events */ private final float factor; /** Time of next shrink event */ private transient volatile long nextShrinkMillis; /** High water mark - largest numIdle encountered */ private transient volatile int idleHighWaterMark; /** * Creates a new ErodingFactor with the given erosion factor. * * @param factor * erosion factor */ public ErodingFactor(final float factor) { this.factor = factor; nextShrinkMillis = System.currentTimeMillis() + (long) (900000 * factor); // now + 15 min * factor idleHighWaterMark = 1; } /** * Gets the time of the next erosion event. * * @return next shrink time */ public long getNextShrink() { return nextShrinkMillis; } /** * {@inheritDoc} */ @Override public String toString() { return "ErodingFactor{" + "factor=" + factor + ", idleHighWaterMark=" + idleHighWaterMark + '}'; } /** * Updates internal state using the supplied time and numIdle. * * @param nowMillis * current time * @param numIdle * number of idle elements in the pool */ public void update(final long nowMillis, final int numIdle) { final int idle = Math.max(0, numIdle); idleHighWaterMark = Math.max(idle, idleHighWaterMark); final float maxInterval = 15f; final float minutes = maxInterval + (1f - maxInterval) / idleHighWaterMark * idle; nextShrinkMillis = nowMillis + (long) (minutes * 60000f * factor); } } /** * Decorates a keyed object pool, adding "eroding" behavior. Based on the * configured erosion factor, objects returning to the pool * may be invalidated instead of being added to idle capacity. * * @param <K> object pool key type * @param <V> object pool value type * @param <E> exception thrown by this pool */ private static class ErodingKeyedObjectPool<K, V, E extends Exception> implements KeyedObjectPool<K, V, E> { /** Underlying pool */ private final KeyedObjectPool<K, V, E> keyedPool; /** Erosion factor */ private final ErodingFactor erodingFactor; /** * Creates an ErodingObjectPool wrapping the given pool using the * specified erosion factor. * * @param keyedPool * underlying pool - must not be null * @param erodingFactor * erosion factor - determines the frequency of erosion * events * @see #erodingFactor */ protected ErodingKeyedObjectPool(final KeyedObjectPool<K, V, E> keyedPool, final ErodingFactor erodingFactor) { if (keyedPool == null) { throw new IllegalArgumentException( MSG_NULL_KEYED_POOL); } this.keyedPool = keyedPool; this.erodingFactor = erodingFactor; } /** * Creates an ErodingObjectPool wrapping the given pool using the * specified erosion factor. * * @param keyedPool * underlying pool * @param factor * erosion factor - determines the frequency of erosion * events * @see #erodingFactor */ public ErodingKeyedObjectPool(final KeyedObjectPool<K, V, E> keyedPool, final float factor) { this(keyedPool, new ErodingFactor(factor)); } /** * {@inheritDoc} */ @Override public void addObject(final K key) throws E, IllegalStateException, UnsupportedOperationException { keyedPool.addObject(key); } /** * {@inheritDoc} */ @Override public V borrowObject(final K key) throws E, NoSuchElementException, IllegalStateException { return keyedPool.borrowObject(key); } /** * {@inheritDoc} */ @Override public void clear() throws E, UnsupportedOperationException { keyedPool.clear(); } /** * {@inheritDoc} */ @Override public void clear(final K key) throws E, UnsupportedOperationException { keyedPool.clear(key); } /** * {@inheritDoc} */ @Override public void close() { try { keyedPool.close(); } catch (final Exception ignored) { // ignored } } /** * Gets the eroding factor for the given key * * @param key * key * @return eroding factor for the given keyed pool */ protected ErodingFactor getErodingFactor(final K key) { return erodingFactor; } /** * Gets the underlying pool * * @return the keyed pool that this ErodingKeyedObjectPool wraps */ protected KeyedObjectPool<K, V, E> getKeyedPool() { return keyedPool; } /** * {@inheritDoc} */ @Override public List<K> getKeys() { return keyedPool.getKeys(); } /** * {@inheritDoc} */ @Override public int getNumActive() { return keyedPool.getNumActive(); } /** * {@inheritDoc} */ @Override public int getNumActive(final K key) { return keyedPool.getNumActive(key); } /** * {@inheritDoc} */ @Override public int getNumIdle() { return keyedPool.getNumIdle(); } /** * {@inheritDoc} */ @Override public int getNumIdle(final K key) { return keyedPool.getNumIdle(key); } /** * {@inheritDoc} */ @Override public void invalidateObject(final K key, final V obj) { try { keyedPool.invalidateObject(key, obj); } catch (final Exception ignored) { // ignored } } /** * Returns obj to the pool, unless erosion is triggered, in which case * obj is invalidated. Erosion is triggered when there are idle * instances in the pool associated with the given key and more than the * configured {@link #erodingFactor erosion factor} time has elapsed * since the last returnObject activation. * * @param obj * object to return or invalidate * @param key * key * @see #erodingFactor */ @Override public void returnObject(final K key, final V obj) throws E { boolean discard = false; final long nowMillis = System.currentTimeMillis(); final ErodingFactor factor = getErodingFactor(key); synchronized (keyedPool) { if (factor.getNextShrink() < nowMillis) { final int numIdle = getNumIdle(key); if (numIdle > 0) { discard = true; } factor.update(nowMillis, numIdle); } } try { if (discard) { keyedPool.invalidateObject(key, obj); } else { keyedPool.returnObject(key, obj); } } catch (final Exception ignored) { // ignored } } /** * {@inheritDoc} */ @Override public String toString() { return "ErodingKeyedObjectPool{" + "factor=" + erodingFactor + ", keyedPool=" + keyedPool + '}'; } } /** * Decorates an object pool, adding "eroding" behavior. Based on the * configured {@link #factor erosion factor}, objects returning to the pool * may be invalidated instead of being added to idle capacity. * * @param <T> type of objects in the pool * @param <E> type of exceptions from the pool */ private static final class ErodingObjectPool<T, E extends Exception> implements ObjectPool<T, E> { /** Underlying object pool */ private final ObjectPool<T, E> pool; /** Erosion factor */ private final ErodingFactor factor; /** * Creates an ErodingObjectPool wrapping the given pool using the * specified erosion factor. * * @param pool * underlying pool * @param factor * erosion factor - determines the frequency of erosion * events * @see #factor */ public ErodingObjectPool(final ObjectPool<T, E> pool, final float factor) { this.pool = pool; this.factor = new ErodingFactor(factor); } /** * {@inheritDoc} */ @Override public void addObject() throws E, IllegalStateException, UnsupportedOperationException{ pool.addObject(); } /** * {@inheritDoc} */ @Override public T borrowObject() throws E, NoSuchElementException, IllegalStateException { return pool.borrowObject(); } /** * {@inheritDoc} */ @Override public void clear() throws E, UnsupportedOperationException { pool.clear(); } /** * {@inheritDoc} */ @Override public void close() { try { pool.close(); } catch (final Exception ignored) { // ignored } } /** * {@inheritDoc} */ @Override public int getNumActive() { return pool.getNumActive(); } /** * {@inheritDoc} */ @Override public int getNumIdle() { return pool.getNumIdle(); } /** * {@inheritDoc} */ @Override public void invalidateObject(final T obj) { try { pool.invalidateObject(obj); } catch (final Exception ignored) { // ignored } } /** * Returns * Gets obj to the pool, unless erosion is triggered, in which case * obj is invalidated. Erosion is triggered when there are idle * instances in the pool and more than the {@link #factor erosion * factor}-determined time has elapsed since the last returnObject * activation. * * @param obj * object to return or invalidate * @see #factor */ @Override public void returnObject(final T obj) { boolean discard = false; final long nowMillis = System.currentTimeMillis(); synchronized (pool) { if (factor.getNextShrink() < nowMillis) { // XXX: Pool 3: move test // out of sync block final int numIdle = pool.getNumIdle(); if (numIdle > 0) { discard = true; } factor.update(nowMillis, numIdle); } } try { if (discard) { pool.invalidateObject(obj); } else { pool.returnObject(obj); } } catch (final Exception ignored) { // ignored } } /** * {@inheritDoc} */ @Override public String toString() { return "ErodingObjectPool{" + "factor=" + factor + ", pool=" + pool + '}'; } } /** * Extends ErodingKeyedObjectPool to allow erosion to take place on a * per-key basis. Timing of erosion events is tracked separately for * separate keyed pools. * * @param <K> object pool key type * @param <V> object pool value type * @param <E> exception thrown by this pool */ private static final class ErodingPerKeyKeyedObjectPool<K, V, E extends Exception> extends ErodingKeyedObjectPool<K, V, E> { /** Erosion factor - same for all pools */ private final float factor; /** Map of ErodingFactor instances keyed on pool keys */ private final Map<K, ErodingFactor> factors = Collections.synchronizedMap(new HashMap<>()); /** * Creates a new ErordingPerKeyKeyedObjectPool decorating the given keyed * pool with the specified erosion factor. * * @param keyedPool * underlying keyed pool * @param factor * erosion factor */ public ErodingPerKeyKeyedObjectPool(final KeyedObjectPool<K, V, E> keyedPool, final float factor) { super(keyedPool, null); this.factor = factor; } /** * {@inheritDoc} */ @Override protected ErodingFactor getErodingFactor(final K key) { // This may result in two ErodingFactors being created for a key // since they are small and cheap this is okay. return factors.computeIfAbsent(key, k -> new ErodingFactor(this.factor)); } /** * {@inheritDoc} */ @SuppressWarnings("resource") // getKeyedPool(): ivar access @Override public String toString() { return "ErodingPerKeyKeyedObjectPool{" + "factor=" + factor + ", keyedPool=" + getKeyedPool() + '}'; } } /** * Timer task that adds objects to the pool until the number of idle * instances for the given key reaches the configured minIdle. Note that * this is not the same as the pool's minIdle setting. * * @param <K> object pool key type * @param <V> object pool value type * @param <E> exception thrown by this pool */ private static final class KeyedObjectPoolMinIdleTimerTask<K, V, E extends Exception> extends TimerTask { /** Minimum number of idle instances. Not the same as pool.getMinIdle(). */ private final int minIdle; /** Key to ensure minIdle for */ private final K key; /** Keyed object pool */ private final KeyedObjectPool<K, V, E> keyedPool; /** * Creates a new KeyedObjecPoolMinIdleTimerTask. * * @param keyedPool * keyed object pool * @param key * key to ensure minimum number of idle instances * @param minIdle * minimum number of idle instances * @throws IllegalArgumentException * if the key is null */ KeyedObjectPoolMinIdleTimerTask(final KeyedObjectPool<K, V, E> keyedPool, final K key, final int minIdle) throws IllegalArgumentException { if (keyedPool == null) { throw new IllegalArgumentException( MSG_NULL_KEYED_POOL); } this.keyedPool = keyedPool; this.key = key; this.minIdle = minIdle; } /** * {@inheritDoc} */ @Override public void run() { boolean success = false; try { if (keyedPool.getNumIdle(key) < minIdle) { keyedPool.addObject(key); } success = true; } catch (final Exception e) { cancel(); } finally { // detect other types of Throwable and cancel this Timer if (!success) { cancel(); } } } /** * {@inheritDoc} */ @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("KeyedObjectPoolMinIdleTimerTask"); sb.append("{minIdle=").append(minIdle); sb.append(", key=").append(key); sb.append(", keyedPool=").append(keyedPool); sb.append('}'); return sb.toString(); } } /** * Timer task that adds objects to the pool until the number of idle * instances reaches the configured minIdle. Note that this is not the same * as the pool's minIdle setting. * * @param <T> type of objects in the pool * @param <E> type of exceptions from the pool */ private static final class ObjectPoolMinIdleTimerTask<T, E extends Exception> extends TimerTask { /** Minimum number of idle instances. Not the same as pool.getMinIdle(). */ private final int minIdle; /** Object pool */ private final ObjectPool<T, E> pool; /** * Constructs a new ObjectPoolMinIdleTimerTask for the given pool with the * given minIdle setting. * * @param pool * object pool * @param minIdle * number of idle instances to maintain * @throws IllegalArgumentException * if the pool is null */ ObjectPoolMinIdleTimerTask(final ObjectPool<T, E> pool, final int minIdle) throws IllegalArgumentException { if (pool == null) { throw new IllegalArgumentException(MSG_NULL_POOL); } this.pool = pool; this.minIdle = minIdle; } /** * {@inheritDoc} */ @Override public void run() { boolean success = false; try { if (pool.getNumIdle() < minIdle) { pool.addObject(); } success = true; } catch (final Exception e) { cancel(); } finally { // detect other types of Throwable and cancel this Timer if (!success) { cancel(); } } } /** * {@inheritDoc} */ @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("ObjectPoolMinIdleTimerTask"); sb.append("{minIdle=").append(minIdle); sb.append(", pool=").append(pool); sb.append('}'); return sb.toString(); } } /** * A synchronized (thread-safe) KeyedObjectPool backed by the specified * KeyedObjectPool. * <p> * <b>Note:</b> This should not be used on pool implementations that already * provide proper synchronization such as the pools provided in the Commons * Pool library. Wrapping a pool that {@link #wait() waits} for poolable * objects to be returned before allowing another one to be borrowed with * another layer of synchronization will cause liveliness issues or a * deadlock. * </p> * * @param <K> object pool key type * @param <V> object pool value type * @param <E> exception thrown by this pool */ static final class SynchronizedKeyedObjectPool<K, V, E extends Exception> implements KeyedObjectPool<K, V, E> { /** * Object whose monitor is used to synchronize methods on the wrapped * pool. */ private final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock(); /** Underlying object pool */ private final KeyedObjectPool<K, V, E> keyedPool; /** * Creates a new SynchronizedKeyedObjectPool wrapping the given pool * * @param keyedPool * KeyedObjectPool to wrap * @throws IllegalArgumentException * if keyedPool is null */ SynchronizedKeyedObjectPool(final KeyedObjectPool<K, V, E> keyedPool) throws IllegalArgumentException { if (keyedPool == null) { throw new IllegalArgumentException( MSG_NULL_KEYED_POOL); } this.keyedPool = keyedPool; } /** * {@inheritDoc} */ @Override public void addObject(final K key) throws E, IllegalStateException, UnsupportedOperationException { final WriteLock writeLock = readWriteLock.writeLock(); writeLock.lock(); try { keyedPool.addObject(key); } finally { writeLock.unlock(); } } /** * {@inheritDoc} */ @Override public V borrowObject(final K key) throws E, NoSuchElementException, IllegalStateException { final WriteLock writeLock = readWriteLock.writeLock(); writeLock.lock(); try { return keyedPool.borrowObject(key); } finally { writeLock.unlock(); } } /** * {@inheritDoc} */ @Override public void clear() throws E, UnsupportedOperationException { final WriteLock writeLock = readWriteLock.writeLock(); writeLock.lock(); try { keyedPool.clear(); } finally { writeLock.unlock(); } } /** * {@inheritDoc} */ @Override public void clear(final K key) throws E, UnsupportedOperationException { final WriteLock writeLock = readWriteLock.writeLock(); writeLock.lock(); try { keyedPool.clear(key); } finally { writeLock.unlock(); } } /** * {@inheritDoc} */ @Override public void close() { final WriteLock writeLock = readWriteLock.writeLock(); writeLock.lock(); try { keyedPool.close(); } catch (final Exception ignored) { // ignored as of Pool 2 } finally { writeLock.unlock(); } } /** * {@inheritDoc} */ @Override public List<K> getKeys() { final ReadLock readLock = readWriteLock.readLock(); readLock.lock(); try { return keyedPool.getKeys(); } finally { readLock.unlock(); } } /** * {@inheritDoc} */ @Override public int getNumActive() { final ReadLock readLock = readWriteLock.readLock(); readLock.lock(); try { return keyedPool.getNumActive(); } finally { readLock.unlock(); } } /** * {@inheritDoc} */ @Override public int getNumActive(final K key) { final ReadLock readLock = readWriteLock.readLock(); readLock.lock(); try { return keyedPool.getNumActive(key); } finally { readLock.unlock(); } } /** * {@inheritDoc} */ @Override public int getNumIdle() { final ReadLock readLock = readWriteLock.readLock(); readLock.lock(); try { return keyedPool.getNumIdle(); } finally { readLock.unlock(); } } /** * {@inheritDoc} */ @Override public int getNumIdle(final K key) { final ReadLock readLock = readWriteLock.readLock(); readLock.lock(); try { return keyedPool.getNumIdle(key); } finally { readLock.unlock(); } } /** * {@inheritDoc} */ @Override public void invalidateObject(final K key, final V obj) { final WriteLock writeLock = readWriteLock.writeLock(); writeLock.lock(); try { keyedPool.invalidateObject(key, obj); } catch (final Exception ignored) { // ignored as of Pool 2 } finally { writeLock.unlock(); } } /** * {@inheritDoc} */ @Override public void returnObject(final K key, final V obj) { final WriteLock writeLock = readWriteLock.writeLock(); writeLock.lock(); try { keyedPool.returnObject(key, obj); } catch (final Exception ignored) { // ignored } finally { writeLock.unlock(); } } /** * {@inheritDoc} */ @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("SynchronizedKeyedObjectPool"); sb.append("{keyedPool=").append(keyedPool); sb.append('}'); return sb.toString(); } } /** * A fully synchronized KeyedPooledObjectFactory that wraps a * KeyedPooledObjectFactory and synchronizes access to the wrapped factory * methods. * <p> * <b>Note:</b> This should not be used on pool implementations that already * provide proper synchronization such as the pools provided in the Commons * Pool library. * </p> * * @param <K> pooled object factory key type * @param <V> pooled object factory value type * @param <E> pooled object factory exception type */ private static final class SynchronizedKeyedPooledObjectFactory<K, V, E extends Exception> implements KeyedPooledObjectFactory<K, V, E> { /** Synchronization lock */ private final WriteLock writeLock = new ReentrantReadWriteLock().writeLock(); /** Wrapped factory */ private final KeyedPooledObjectFactory<K, V, E> keyedFactory; /** * Creates a SynchronizedKeyedPooledObjectFactory wrapping the given * factory. * * @param keyedFactory * underlying factory to wrap * @throws IllegalArgumentException * if the factory is null */ SynchronizedKeyedPooledObjectFactory(final KeyedPooledObjectFactory<K, V, E> keyedFactory) throws IllegalArgumentException { if (keyedFactory == null) { throw new IllegalArgumentException( "keyedFactory must not be null."); } this.keyedFactory = keyedFactory; } /** * {@inheritDoc} */ @Override public void activateObject(final K key, final PooledObject<V> p) throws E { writeLock.lock(); try { keyedFactory.activateObject(key, p); } finally { writeLock.unlock(); } } /** * {@inheritDoc} */ @Override public void destroyObject(final K key, final PooledObject<V> p) throws E { writeLock.lock(); try { keyedFactory.destroyObject(key, p); } finally { writeLock.unlock(); } } /** * {@inheritDoc} */ @Override public PooledObject<V> makeObject(final K key) throws E { writeLock.lock(); try { return keyedFactory.makeObject(key); } finally { writeLock.unlock(); } } /** * {@inheritDoc} */ @Override public void passivateObject(final K key, final PooledObject<V> p) throws E { writeLock.lock(); try { keyedFactory.passivateObject(key, p); } finally { writeLock.unlock(); } } /** * {@inheritDoc} */ @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("SynchronizedKeyedPooledObjectFactory"); sb.append("{keyedFactory=").append(keyedFactory); sb.append('}'); return sb.toString(); } /** * {@inheritDoc} */ @Override public boolean validateObject(final K key, final PooledObject<V> p) { writeLock.lock(); try { return keyedFactory.validateObject(key, p); } finally { writeLock.unlock(); } } } /** * A synchronized (thread-safe) ObjectPool backed by the specified * ObjectPool. * <p> * <b>Note:</b> This should not be used on pool implementations that already * provide proper synchronization such as the pools provided in the Commons * Pool library. Wrapping a pool that {@link #wait() waits} for poolable * objects to be returned before allowing another one to be borrowed with * another layer of synchronization will cause liveliness issues or a * deadlock. * </p> * * @param <T> type of objects in the pool * @param <E> type of exceptions from the pool */ private static final class SynchronizedObjectPool<T, E extends Exception> implements ObjectPool<T, E> { /** * Object whose monitor is used to synchronize methods on the wrapped * pool. */ private final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock(); /** the underlying object pool */ private final ObjectPool<T, E> pool; /** * Creates a new SynchronizedObjectPool wrapping the given pool. * * @param pool * the ObjectPool to be "wrapped" in a synchronized * ObjectPool. * @throws IllegalArgumentException * if the pool is null */ SynchronizedObjectPool(final ObjectPool<T, E> pool) throws IllegalArgumentException { if (pool == null) { throw new IllegalArgumentException(MSG_NULL_POOL); } this.pool = pool; } /** * {@inheritDoc} */ @Override public void addObject() throws E, IllegalStateException, UnsupportedOperationException { final WriteLock writeLock = readWriteLock.writeLock(); writeLock.lock(); try { pool.addObject(); } finally { writeLock.unlock(); } } /** * {@inheritDoc} */ @Override public T borrowObject() throws E, NoSuchElementException, IllegalStateException { final WriteLock writeLock = readWriteLock.writeLock(); writeLock.lock(); try { return pool.borrowObject(); } finally { writeLock.unlock(); } } /** * {@inheritDoc} */ @Override public void clear() throws E, UnsupportedOperationException { final WriteLock writeLock = readWriteLock.writeLock(); writeLock.lock(); try { pool.clear(); } finally { writeLock.unlock(); } } /** * {@inheritDoc} */ @Override public void close() { final WriteLock writeLock = readWriteLock.writeLock(); writeLock.lock(); try { pool.close(); } catch (final Exception ignored) { // ignored as of Pool 2 } finally { writeLock.unlock(); } } /** * {@inheritDoc} */ @Override public int getNumActive() { final ReadLock readLock = readWriteLock.readLock(); readLock.lock(); try { return pool.getNumActive(); } finally { readLock.unlock(); } } /** * {@inheritDoc} */ @Override public int getNumIdle() { final ReadLock readLock = readWriteLock.readLock(); readLock.lock(); try { return pool.getNumIdle(); } finally { readLock.unlock(); } } /** * {@inheritDoc} */ @Override public void invalidateObject(final T obj) { final WriteLock writeLock = readWriteLock.writeLock(); writeLock.lock(); try { pool.invalidateObject(obj); } catch (final Exception ignored) { // ignored as of Pool 2 } finally { writeLock.unlock(); } } /** * {@inheritDoc} */ @Override public void returnObject(final T obj) { final WriteLock writeLock = readWriteLock.writeLock(); writeLock.lock(); try { pool.returnObject(obj); } catch (final Exception ignored) { // ignored as of Pool 2 } finally { writeLock.unlock(); } } /** * {@inheritDoc} */ @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("SynchronizedObjectPool"); sb.append("{pool=").append(pool); sb.append('}'); return sb.toString(); } } /** * A fully synchronized PooledObjectFactory that wraps a * PooledObjectFactory and synchronizes access to the wrapped factory * methods. * <p> * <b>Note:</b> This should not be used on pool implementations that already * provide proper synchronization such as the pools provided in the Commons * Pool library. * </p> * * @param <T> pooled object factory type * @param <E> exception type */ private static final class SynchronizedPooledObjectFactory<T, E extends Exception> implements PooledObjectFactory<T, E> { /** Synchronization lock */ private final WriteLock writeLock = new ReentrantReadWriteLock().writeLock(); /** Wrapped factory */ private final PooledObjectFactory<T, E> factory; /** * Creates a SynchronizedPoolableObjectFactory wrapping the given * factory. * * @param factory * underlying factory to wrap * @throws IllegalArgumentException * if the factory is null */ SynchronizedPooledObjectFactory(final PooledObjectFactory<T, E> factory) throws IllegalArgumentException { if (factory == null) { throw new IllegalArgumentException("factory must not be null."); } this.factory = factory; } /** * {@inheritDoc} */ @Override public void activateObject(final PooledObject<T> p) throws E { writeLock.lock(); try { factory.activateObject(p); } finally { writeLock.unlock(); } } /** * {@inheritDoc} */ @Override public void destroyObject(final PooledObject<T> p) throws E { writeLock.lock(); try { factory.destroyObject(p); } finally { writeLock.unlock(); } } /** * {@inheritDoc} */ @Override public PooledObject<T> makeObject() throws E { writeLock.lock(); try { return factory.makeObject(); } finally { writeLock.unlock(); } } /** * {@inheritDoc} */ @Override public void passivateObject(final PooledObject<T> p) throws E { writeLock.lock(); try { factory.passivateObject(p); } finally { writeLock.unlock(); } } /** * {@inheritDoc} */ @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("SynchronizedPoolableObjectFactory"); sb.append("{factory=").append(factory); sb.append('}'); return sb.toString(); } /** * {@inheritDoc} */ @Override public boolean validateObject(final PooledObject<T> p) { writeLock.lock(); try { return factory.validateObject(p); } finally { writeLock.unlock(); } } } /** * Timer used to periodically check pools idle object count. Because a * {@link Timer} creates a {@link Thread}, an IODH is used. */ static class TimerHolder { static final Timer MIN_IDLE_TIMER = new Timer(true); } private static final String MSG_FACTOR_NEGATIVE = "factor must be positive."; private static final String MSG_MIN_IDLE = "minIdle must be non-negative."; static final String MSG_NULL_KEY = "key must not be null."; private static final String MSG_NULL_KEYED_POOL = "keyedPool must not be null."; static final String MSG_NULL_KEYS = "keys must not be null."; private static final String MSG_NULL_POOL = "pool must not be null."; /** * Periodically check the idle object count for each key in the * {@code Collection keys} in the keyedPool. At most one idle object will be * added per period. * * @param keyedPool * the keyedPool to check periodically. * @param keys * a collection of keys to check the idle object count. * @param minIdle * if the {@link KeyedObjectPool#getNumIdle(Object)} is less than * this then add an idle object. * @param periodMillis * the frequency in milliseconds to check the number of idle objects in a * keyedPool, see {@link Timer#schedule(TimerTask, long, long)}. * @param <K> the type of the pool key * @param <V> the type of pool entries * @param <E> the type of exception thrown by a pool * @return a {@link Map} of key and {@link TimerTask} pairs that will * periodically check the pools idle object count. * @throws IllegalArgumentException * when {@code keyedPool}, {@code keys}, or any of the values in * the collection is {@code null} or when {@code minIdle} is * negative or when {@code period} isn't valid for * {@link Timer#schedule(TimerTask, long, long)}. * @see #checkMinIdle(KeyedObjectPool, Object, int, long) */ public static <K, V, E extends Exception> Map<K, TimerTask> checkMinIdle( final KeyedObjectPool<K, V, E> keyedPool, final Collection<K> keys, final int minIdle, final long periodMillis) throws IllegalArgumentException { if (keys == null) { throw new IllegalArgumentException(MSG_NULL_KEYS); } return keys.stream().collect(Collectors.toMap(Function.identity(), k -> checkMinIdle(keyedPool, k, minIdle, periodMillis), (k, v) -> v)); } /** * Periodically check the idle object count for the key in the keyedPool. At * most one idle object will be added per period. If there is an exception * when calling {@link KeyedObjectPool#addObject(Object)} then no more * checks for that key will be performed. * * @param keyedPool * the keyedPool to check periodically. * @param key * the key to check the idle count of. * @param minIdle * if the {@link KeyedObjectPool#getNumIdle(Object)} is less than * this then add an idle object. * @param periodMillis * the frequency in milliseconds to check the number of idle objects in a * keyedPool, see {@link Timer#schedule(TimerTask, long, long)}. * @param <K> the type of the pool key * @param <V> the type of pool entries * @param <E> the type of exception thrown by a pool * @return the {@link TimerTask} that will periodically check the pools idle * object count. * @throws IllegalArgumentException * when {@code keyedPool}, {@code key} is {@code null} or * when {@code minIdle} is negative or when {@code period} isn't * valid for {@link Timer#schedule(TimerTask, long, long)}. */ public static <K, V, E extends Exception> TimerTask checkMinIdle( final KeyedObjectPool<K, V, E> keyedPool, final K key, final int minIdle, final long periodMillis) throws IllegalArgumentException { if (keyedPool == null) { throw new IllegalArgumentException(MSG_NULL_KEYED_POOL); } if (key == null) { throw new IllegalArgumentException(MSG_NULL_KEY); } if (minIdle < 0) { throw new IllegalArgumentException(MSG_MIN_IDLE); } final TimerTask task = new KeyedObjectPoolMinIdleTimerTask<>( keyedPool, key, minIdle); getMinIdleTimer().schedule(task, 0L, periodMillis); return task; } /** * Periodically check the idle object count for the pool. At most one idle * object will be added per period. If there is an exception when calling * {@link ObjectPool#addObject()} then no more checks will be performed. * * @param pool * the pool to check periodically. * @param minIdle * if the {@link ObjectPool#getNumIdle()} is less than this then * add an idle object. * @param periodMillis * the frequency in milliseconds to check the number of idle objects in a pool, * see {@link Timer#schedule(TimerTask, long, long)}. * @param <T> the type of objects in the pool * @param <E> type of exceptions from the pool * @return the {@link TimerTask} that will periodically check the pools idle * object count. * @throws IllegalArgumentException * when {@code pool} is {@code null} or when {@code minIdle} is * negative or when {@code period} isn't valid for * {@link Timer#schedule(TimerTask, long, long)} */ public static <T, E extends Exception> TimerTask checkMinIdle(final ObjectPool<T, E> pool, final int minIdle, final long periodMillis) throws IllegalArgumentException { if (pool == null) { throw new IllegalArgumentException(MSG_NULL_KEYED_POOL); } if (minIdle < 0) { throw new IllegalArgumentException(MSG_MIN_IDLE); } final TimerTask task = new ObjectPoolMinIdleTimerTask<>(pool, minIdle); getMinIdleTimer().schedule(task, 0L, periodMillis); return task; } /** * Should the supplied Throwable be re-thrown (eg if it is an instance of * one of the Throwables that should never be swallowed). Used by the pool * error handling for operations that throw exceptions that normally need to * be ignored. * * @param t * The Throwable to check * @throws ThreadDeath * if that is passed in * @throws VirtualMachineError * if that is passed in */ public static void checkRethrow(final Throwable t) { if (t instanceof ThreadDeath) { throw (ThreadDeath) t; } if (t instanceof VirtualMachineError) { throw (VirtualMachineError) t; } // All other instances of Throwable will be silently swallowed } /** * Returns a pool that adaptively decreases its size when idle objects are * no longer needed. This is intended as an always thread-safe alternative * to using an idle object evictor provided by many pool implementations. * This is also an effective way to shrink FIFO ordered pools that * experience load spikes. * * @param keyedPool * the KeyedObjectPool to be decorated so it shrinks its idle * count when possible. * @param <K> the type of the pool key * @param <V> the type of pool entries * @param <E> the type of exception thrown by a pool * @throws IllegalArgumentException * when {@code keyedPool} is {@code null}. * @return a pool that adaptively decreases its size when idle objects are * no longer needed. * @see #erodingPool(KeyedObjectPool, float) * @see #erodingPool(KeyedObjectPool, float, boolean) */ public static <K, V, E extends Exception> KeyedObjectPool<K, V, E> erodingPool(final KeyedObjectPool<K, V, E> keyedPool) { return erodingPool(keyedPool, 1f); } /** * Returns a pool that adaptively decreases its size when idle objects are * no longer needed. This is intended as an always thread-safe alternative * to using an idle object evictor provided by many pool implementations. * This is also an effective way to shrink FIFO ordered pools that * experience load spikes. * <p> * The factor parameter provides a mechanism to tweak the rate at which the * pool tries to shrink its size. Values between 0 and 1 cause the pool to * try to shrink its size more often. Values greater than 1 cause the pool * to less frequently try to shrink its size. * </p> * * @param keyedPool * the KeyedObjectPool to be decorated so it shrinks its idle * count when possible. * @param factor * a positive value to scale the rate at which the pool tries to * reduce its size. If 0 &lt; factor &lt; 1 then the pool * shrinks more aggressively. If 1 &lt; factor then the pool * shrinks less aggressively. * @param <K> the type of the pool key * @param <V> the type of pool entries * @param <E> the type of exception thrown by a pool * @throws IllegalArgumentException * when {@code keyedPool} is {@code null} or when {@code factor} * is not positive. * @return a pool that adaptively decreases its size when idle objects are * no longer needed. * @see #erodingPool(KeyedObjectPool, float, boolean) */ public static <K, V, E extends Exception> KeyedObjectPool<K, V, E> erodingPool(final KeyedObjectPool<K, V, E> keyedPool, final float factor) { return erodingPool(keyedPool, factor, false); } /** * Returns a pool that adaptively decreases its size when idle objects are * no longer needed. This is intended as an always thread-safe alternative * to using an idle object evictor provided by many pool implementations. * This is also an effective way to shrink FIFO ordered pools that * experience load spikes. * <p> * The factor parameter provides a mechanism to tweak the rate at which the * pool tries to shrink its size. Values between 0 and 1 cause the pool to * try to shrink its size more often. Values greater than 1 cause the pool * to less frequently try to shrink its size. * </p> * <p> * The perKey parameter determines if the pool shrinks on a whole pool basis * or a per key basis. When perKey is false, the keys do not have an effect * on the rate at which the pool tries to shrink its size. When perKey is * true, each key is shrunk independently. * </p> * * @param keyedPool * the KeyedObjectPool to be decorated so it shrinks its idle * count when possible. * @param factor * a positive value to scale the rate at which the pool tries to * reduce its size. If 0 &lt; factor &lt; 1 then the pool * shrinks more aggressively. If 1 &lt; factor then the pool * shrinks less aggressively. * @param perKey * when true, each key is treated independently. * @param <K> the type of the pool key * @param <V> the type of pool entries * @param <E> the type of exception thrown by a pool * @throws IllegalArgumentException * when {@code keyedPool} is {@code null} or when {@code factor} * is not positive. * @return a pool that adaptively decreases its size when idle objects are * no longer needed. * @see #erodingPool(KeyedObjectPool) * @see #erodingPool(KeyedObjectPool, float) */ public static <K, V, E extends Exception> KeyedObjectPool<K, V, E> erodingPool( final KeyedObjectPool<K, V, E> keyedPool, final float factor, final boolean perKey) { if (keyedPool == null) { throw new IllegalArgumentException(MSG_NULL_KEYED_POOL); } if (factor <= 0f) { throw new IllegalArgumentException(MSG_FACTOR_NEGATIVE); } if (perKey) { return new ErodingPerKeyKeyedObjectPool<>(keyedPool, factor); } return new ErodingKeyedObjectPool<>(keyedPool, factor); } /** * Returns a pool that adaptively decreases its size when idle objects are * no longer needed. This is intended as an always thread-safe alternative * to using an idle object evictor provided by many pool implementations. * This is also an effective way to shrink FIFO ordered pools that * experience load spikes. * * @param pool * the ObjectPool to be decorated so it shrinks its idle count * when possible. * @param <T> the type of objects in the pool * @param <E> type of exceptions from the pool * @throws IllegalArgumentException * when {@code pool} is {@code null}. * @return a pool that adaptively decreases its size when idle objects are * no longer needed. * @see #erodingPool(ObjectPool, float) */ public static <T, E extends Exception> ObjectPool<T, E> erodingPool(final ObjectPool<T, E> pool) { return erodingPool(pool, 1f); } /** * Returns a pool that adaptively decreases its size when idle objects are * no longer needed. This is intended as an always thread-safe alternative * to using an idle object evictor provided by many pool implementations. * This is also an effective way to shrink FIFO ordered pools that * experience load spikes. * <p> * The factor parameter provides a mechanism to tweak the rate at which the * pool tries to shrink its size. Values between 0 and 1 cause the pool to * try to shrink its size more often. Values greater than 1 cause the pool * to less frequently try to shrink its size. * </p> * * @param pool * the ObjectPool to be decorated so it shrinks its idle count * when possible. * @param factor * a positive value to scale the rate at which the pool tries to * reduce its size. If 0 &lt; factor &lt; 1 then the pool * shrinks more aggressively. If 1 &lt; factor then the pool * shrinks less aggressively. * @param <T> the type of objects in the pool * @param <E> type of exceptions from the pool * @throws IllegalArgumentException * when {@code pool} is {@code null} or when {@code factor} is * not positive. * @return a pool that adaptively decreases its size when idle objects are * no longer needed. * @see #erodingPool(ObjectPool) */ public static <T, E extends Exception> ObjectPool<T, E> erodingPool(final ObjectPool<T, E> pool, final float factor) { if (pool == null) { throw new IllegalArgumentException(MSG_NULL_POOL); } if (factor <= 0f) { throw new IllegalArgumentException(MSG_FACTOR_NEGATIVE); } return new ErodingObjectPool<>(pool, factor); } /** * Gets the {@code Timer} for checking keyedPool's idle count. * * @return the {@link Timer} for checking keyedPool's idle count. */ private static Timer getMinIdleTimer() { return TimerHolder.MIN_IDLE_TIMER; } /** * Returns a synchronized (thread-safe) KeyedPooledObjectFactory backed by * the specified KeyedPooledObjectFactory. * * @param keyedFactory * the KeyedPooledObjectFactory to be "wrapped" in a * synchronized KeyedPooledObjectFactory. * @param <K> the type of the pool key * @param <V> the type of pool entries * @param <E> the type of pool exceptions * @return a synchronized view of the specified KeyedPooledObjectFactory. */ public static <K, V, E extends Exception> KeyedPooledObjectFactory<K, V, E> synchronizedKeyedPooledFactory( final KeyedPooledObjectFactory<K, V, E> keyedFactory) { return new SynchronizedKeyedPooledObjectFactory<>(keyedFactory); } /** * Returns a synchronized (thread-safe) KeyedObjectPool backed by the * specified KeyedObjectPool. * <p> * <b>Note:</b> This should not be used on pool implementations that already * provide proper synchronization such as the pools provided in the Commons * Pool library. Wrapping a pool that {@link #wait() waits} for poolable * objects to be returned before allowing another one to be borrowed with * another layer of synchronization will cause liveliness issues or a * deadlock. * </p> * * @param keyedPool * the KeyedObjectPool to be "wrapped" in a synchronized * KeyedObjectPool. * @param <K> the type of the pool key * @param <V> the type of pool entries * @param <E> the type of exception thrown by a pool * @return a synchronized view of the specified KeyedObjectPool. */ public static <K, V, E extends Exception> KeyedObjectPool<K, V, E> synchronizedPool(final KeyedObjectPool<K, V, E> keyedPool) { /* * assert !(keyedPool instanceof GenericKeyedObjectPool) : * "GenericKeyedObjectPool is already thread-safe"; assert !(keyedPool * instanceof StackKeyedObjectPool) : * "StackKeyedObjectPool is already thread-safe"; assert * !"org.apache.commons.pool.composite.CompositeKeyedObjectPool" * .equals(keyedPool.getClass().getName()) : * "CompositeKeyedObjectPools are already thread-safe"; */ return new SynchronizedKeyedObjectPool<>(keyedPool); } /** * Returns a synchronized (thread-safe) ObjectPool backed by the specified * ObjectPool. * <p> * <b>Note:</b> This should not be used on pool implementations that already * provide proper synchronization such as the pools provided in the Commons * Pool library. Wrapping a pool that {@link #wait() waits} for poolable * objects to be returned before allowing another one to be borrowed with * another layer of synchronization will cause liveliness issues or a * deadlock. * </p> * * @param <T> the type of objects in the pool * @param <E> the type of exceptions thrown by the pool * @param pool * the ObjectPool to be "wrapped" in a synchronized ObjectPool. * @throws IllegalArgumentException * when {@code pool} is {@code null}. * @return a synchronized view of the specified ObjectPool. */ public static <T, E extends Exception> ObjectPool<T, E> synchronizedPool(final ObjectPool<T, E> pool) { if (pool == null) { throw new IllegalArgumentException(MSG_NULL_POOL); } /* * assert !(pool instanceof GenericObjectPool) : * "GenericObjectPool is already thread-safe"; assert !(pool instanceof * SoftReferenceObjectPool) : * "SoftReferenceObjectPool is already thread-safe"; assert !(pool * instanceof StackObjectPool) : * "StackObjectPool is already thread-safe"; assert * !"org.apache.commons.pool.composite.CompositeObjectPool" * .equals(pool.getClass().getName()) : * "CompositeObjectPools are already thread-safe"; */ return new SynchronizedObjectPool<>(pool); } /** * Returns a synchronized (thread-safe) PooledObjectFactory backed by the * specified PooledObjectFactory. * * @param factory * the PooledObjectFactory to be "wrapped" in a synchronized * PooledObjectFactory. * @param <T> the type of objects in the pool * @param <E> the type of exceptions thrown by the pool * @return a synchronized view of the specified PooledObjectFactory. */ public static <T, E extends Exception> PooledObjectFactory<T, E> synchronizedPooledFactory(final PooledObjectFactory<T, E> factory) { return new SynchronizedPooledObjectFactory<>(factory); } /** * PoolUtils instances should NOT be constructed in standard programming. * Instead, the class should be used procedurally: PoolUtils.adapt(aPool);. * This constructor is public to permit tools that require a JavaBean * instance to operate. */ public PoolUtils() { } }
5,263
0
Create_ds/commons-pool/src/main/java/org/apache/commons
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3/TrackedUse.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3; import java.time.Instant; /** * Allows pooled objects to make information available about when and how they were used available to the object pool. * The object pool may, but is not required, to use this information to make more informed decisions when determining * the state of a pooled object - for instance whether or not the object has been abandoned. * * @since 2.0 */ public interface TrackedUse { /** * Gets the last Instant this object was used. * <p> * Starting with Java 9, the JRE {@code SystemClock} precision is increased usually down to microseconds, or tenth * of microseconds, depending on the OS, Hardware, and JVM implementation. * </p> * * @return the last Instant this object was used. * @since 2.11.0 */ Instant getLastUsedInstant(); }
5,264
0
Create_ds/commons-pool/src/main/java/org/apache/commons
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3/PooledObjectState.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3; /** * Provides all possible states of a {@link PooledObject}. * * @since 2.0 */ public enum PooledObjectState { /** * In the queue, not in use. */ IDLE, /** * In use. */ ALLOCATED, /** * In the queue, currently being tested for possible eviction. */ EVICTION, /** * Not in the queue, currently being tested for possible eviction. An attempt to borrow the object was made while * being tested which removed it from the queue. It should be returned to the head of the queue once eviction * testing completes. * <p> * TODO: Consider allocating object and ignoring the result of the eviction test. * </p> */ EVICTION_RETURN_TO_HEAD, /** * In the queue, currently being validated. */ VALIDATION, /** * Not in queue, currently being validated. The object was borrowed while being validated and since testOnBorrow was * configured, it was removed from the queue and pre-allocated. It should be allocated once validation completes. */ VALIDATION_PREALLOCATED, /** * Not in queue, currently being validated. An attempt to borrow the object was made while previously being tested * for eviction which removed it from the queue. It should be returned to the head of the queue once validation * completes. */ VALIDATION_RETURN_TO_HEAD, /** * Failed maintenance (e.g. eviction test or validation) and will be / has been destroyed */ INVALID, /** * Deemed abandoned, to be invalidated. */ ABANDONED, /** * Returning to the pool. */ RETURNING }
5,265
0
Create_ds/commons-pool/src/main/java/org/apache/commons
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3/BaseObjectPool.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3; /** * A simple base implementation of {@link ObjectPool}. * Optional operations are implemented to either do nothing, return a value * indicating it is unsupported or throw {@link UnsupportedOperationException}. * <p> * This class is intended to be thread-safe. * </p> * * @param <T> Type of element pooled in this pool. * @param <E> Type of exception thrown by this pool. * * @since 2.0 */ public abstract class BaseObjectPool<T, E extends Exception> extends BaseObject implements ObjectPool<T, E> { private volatile boolean closed; /** * Not supported in this base implementation. Subclasses should override * this behavior. * * @throws UnsupportedOperationException if the pool does not implement this * method */ @Override public void addObject() throws E, UnsupportedOperationException { throw new UnsupportedOperationException(); } /** * Throws an {@code IllegalStateException} when this pool has been * closed. * * @throws IllegalStateException when this pool has been closed. * * @see #isClosed() */ protected final void assertOpen() throws IllegalStateException { if (isClosed()) { throw new IllegalStateException("Pool not open"); } } @Override public abstract T borrowObject() throws E; /** * Not supported in this base implementation. * * @throws UnsupportedOperationException if the pool does not implement this * method */ @Override public void clear() throws E, UnsupportedOperationException { throw new UnsupportedOperationException(); } /** * {@inheritDoc} * <p> * This affects the behavior of {@code isClosed} and * {@code assertOpen}. * </p> */ @Override public void close() { closed = true; } /** * Not supported in this base implementation. * * @return a negative value. */ @Override public int getNumActive() { return -1; } /** * Not supported in this base implementation. * * @return a negative value. */ @Override public int getNumIdle() { return -1; } @Override public abstract void invalidateObject(T obj) throws E; /** * Has this pool instance been closed. * * @return {@code true} when this pool has been closed. */ public final boolean isClosed() { return closed; } @Override public abstract void returnObject(T obj) throws E; @Override protected void toStringAppendFields(final StringBuilder builder) { builder.append("closed="); builder.append(closed); } }
5,266
0
Create_ds/commons-pool/src/main/java/org/apache/commons
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3/package-info.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Object pooling API. * <p> * The <code>org.apache.commons.pool3</code> package defines a simple interface for a pool of object instances, and a handful of base classes that may be useful * when creating pool implementations. * </p> * <p> * The <code>pool</code> package itself doesn't define a specific object pooling implementation, but rather a contract that implementations may support in order * to be fully interchangeable. * </p> * <p> * The <code>pool</code> package separates the way in which instances are pooled from the way in which they are created, resulting in a pair of interfaces: * </p> * <dl> * <dt>{@link org.apache.commons.pool3.ObjectPool ObjectPool}</dt> * <dd>defines a simple object pooling interface, with methods for borrowing instances from and returning them to the pool.</dd> * <dt>{@link org.apache.commons.pool3.PooledObjectFactory PooledObjectFactory}</dt> * <dd>defines lifecycle methods for object instances contained within a pool. By associating a factory with a pool, the pool can create new object instances as * needed.</dd> * </dl> * <p> * The <code>pool</code> package also provides a keyed pool interface, which pools instances of multiple types, accessed according to an arbitrary key. See * {@link org.apache.commons.pool3.KeyedObjectPool KeyedObjectPool} and {@link org.apache.commons.pool3.KeyedPooledObjectFactory KeyedPooledObjectFactory}. * </p> */ package org.apache.commons.pool3;
5,267
0
Create_ds/commons-pool/src/main/java/org/apache/commons
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3/BaseObject.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3; /** * A base class for common functionality. * * @since 2.4.3 */ public abstract class BaseObject { @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append(getClass().getSimpleName()); builder.append(" ["); toStringAppendFields(builder); builder.append("]"); return builder.toString(); } /** * Used by sub-classes to include the fields defined by the sub-class in the * {@link #toString()} output. * * @param builder Field names and values are appended to this object */ protected void toStringAppendFields(final StringBuilder builder) { // do nothing by default, needed for b/w compatibility. } }
5,268
0
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3/impl/AbandonedConfig.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.impl; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.nio.charset.Charset; import java.time.Duration; import org.apache.commons.pool3.TrackedUse; import org.apache.commons.pool3.UsageTracking; /** * Configuration settings for abandoned object removal. * * @since 2.0 */ public class AbandonedConfig { /** * The 5 minutes Duration. */ private static final Duration DEFAULT_REMOVE_ABANDONED_TIMEOUT_DURATION = Duration.ofMinutes(5); /** * Creates a new instance with values from the given instance. * * @param abandonedConfig the source, may be null. * @return A new instance or null if the input is null. * @since 2.11.0 */ public static AbandonedConfig copy(final AbandonedConfig abandonedConfig) { return abandonedConfig == null ? null : new AbandonedConfig(abandonedConfig); } /** * Whether or not borrowObject performs abandoned object removal. */ private boolean removeAbandonedOnBorrow; /** * Whether or not pool maintenance (evictor) performs abandoned object * removal. */ private boolean removeAbandonedOnMaintenance; /** * Timeout before an abandoned object can be removed. */ private Duration removeAbandonedTimeoutDuration = DEFAULT_REMOVE_ABANDONED_TIMEOUT_DURATION; /** * Determines whether or not to log stack traces for application code * which abandoned an object. */ private boolean logAbandoned; /** * Determines whether or not to log full stack traces when logAbandoned is true. * If disabled, then a faster method for logging stack traces with only class data * may be used if possible. * * @since 2.5 */ private boolean requireFullStackTrace = true; /** * PrintWriter to use to log information on abandoned objects. * Use of default system encoding is deliberate. */ private PrintWriter logWriter = new PrintWriter(new OutputStreamWriter(System.out, Charset.defaultCharset())); /** * If the pool implements {@link UsageTracking}, should the pool record a * stack trace every time a method is called on a pooled object and retain * the most recent stack trace to aid debugging of abandoned objects? */ private boolean useUsageTracking; /** * Creates a new instance. */ public AbandonedConfig() { // empty } /** * Creates a new instance with values from the given instance. * * @param abandonedConfig the source. */ @SuppressWarnings("resource") private AbandonedConfig(final AbandonedConfig abandonedConfig) { this.setLogAbandoned(abandonedConfig.getLogAbandoned()); this.setLogWriter(abandonedConfig.getLogWriter()); this.setRemoveAbandonedOnBorrow(abandonedConfig.getRemoveAbandonedOnBorrow()); this.setRemoveAbandonedOnMaintenance(abandonedConfig.getRemoveAbandonedOnMaintenance()); this.setRemoveAbandonedTimeout(abandonedConfig.getRemoveAbandonedTimeoutDuration()); this.setUseUsageTracking(abandonedConfig.getUseUsageTracking()); this.setRequireFullStackTrace(abandonedConfig.getRequireFullStackTrace()); } /** * Flag to log stack traces for application code which abandoned * an object. * * Defaults to false. * Logging of abandoned objects adds overhead for every object created * because a stack trace has to be generated. * * @return boolean true if stack trace logging is turned on for abandoned * objects * */ public boolean getLogAbandoned() { return this.logAbandoned; } /** * Gets the log writer being used by this configuration to log * information on abandoned objects. If not set, a PrintWriter based on * System.out with the system default encoding is used. * * @return log writer in use */ public PrintWriter getLogWriter() { return logWriter; } /** * <p>Flag to remove abandoned objects if they exceed the * removeAbandonedTimeout when borrowObject is invoked.</p> * * <p>The default value is false.</p> * * <p>If set to true, abandoned objects are removed by borrowObject if * there are fewer than 2 idle objects available in the pool and * {@code getNumActive() &gt; getMaxTotal() - 3}</p> * * @return true if abandoned objects are to be removed by borrowObject */ public boolean getRemoveAbandonedOnBorrow() { return this.removeAbandonedOnBorrow; } /** * <p>Flag to remove abandoned objects if they exceed the * removeAbandonedTimeout when pool maintenance (the "evictor") * runs.</p> * * <p>The default value is false.</p> * * <p>If set to true, abandoned objects are removed by the pool * maintenance thread when it runs. This setting has no effect * unless maintenance is enabled by setting *{@link GenericObjectPool#getDurationBetweenEvictionRuns() durationBetweenEvictionRuns} * to a positive number.</p> * * @return true if abandoned objects are to be removed by the evictor */ public boolean getRemoveAbandonedOnMaintenance() { return this.removeAbandonedOnMaintenance; } /** * <p>Timeout before an abandoned object can be removed.</p> * * <p>The time of most recent use of an object is the maximum (latest) of * {@link TrackedUse#getLastUsedInstant()} (if this class of the object implements * TrackedUse) and the time when the object was borrowed from the pool.</p> * * <p>The default value is 300 seconds.</p> * * @return the abandoned object timeout. * @since 2.10.0 */ public Duration getRemoveAbandonedTimeoutDuration() { return this.removeAbandonedTimeoutDuration; } /** * Indicates if full stack traces are required when {@link #getLogAbandoned() logAbandoned} * is true. Defaults to true. Logging of abandoned objects requiring a full stack trace will * generate an entire stack trace to generate for every object created. If this is disabled, * a faster but less informative stack walking mechanism may be used if available. * * @return true if full stack traces are required for logging abandoned connections, or false * if abbreviated stack traces are acceptable * @see CallStack * @since 2.5 */ public boolean getRequireFullStackTrace() { return requireFullStackTrace; } /** * If the pool implements {@link UsageTracking}, should the pool record a * stack trace every time a method is called on a pooled object and retain * the most recent stack trace to aid debugging of abandoned objects? * * @return {@code true} if usage tracking is enabled */ public boolean getUseUsageTracking() { return useUsageTracking; } /** * Sets the flag to log stack traces for application code which abandoned * an object. * * @param logAbandoned true turns on abandoned stack trace logging * @see #getLogAbandoned() * */ public void setLogAbandoned(final boolean logAbandoned) { this.logAbandoned = logAbandoned; } /** * Sets the log writer to be used by this configuration to log * information on abandoned objects. * * @param logWriter The new log writer */ public void setLogWriter(final PrintWriter logWriter) { this.logWriter = logWriter; } /** * Flag to remove abandoned objects if they exceed the * removeAbandonedTimeout when borrowObject is invoked. * * @param removeAbandonedOnBorrow true means abandoned objects will be * removed by borrowObject * @see #getRemoveAbandonedOnBorrow() */ public void setRemoveAbandonedOnBorrow(final boolean removeAbandonedOnBorrow) { this.removeAbandonedOnBorrow = removeAbandonedOnBorrow; } /** * Flag to remove abandoned objects if they exceed the * removeAbandonedTimeout when pool maintenance runs. * * @param removeAbandonedOnMaintenance true means abandoned objects will be * removed by pool maintenance * @see #getRemoveAbandonedOnMaintenance */ public void setRemoveAbandonedOnMaintenance(final boolean removeAbandonedOnMaintenance) { this.removeAbandonedOnMaintenance = removeAbandonedOnMaintenance; } /** * Sets the timeout before an abandoned object can be * removed. * * <p>Setting this property has no effect if * {@link #getRemoveAbandonedOnBorrow() removeAbandonedOnBorrow} and * {@link #getRemoveAbandonedOnMaintenance() removeAbandonedOnMaintenance} * are both false.</p> * * @param removeAbandonedTimeout new abandoned timeout * @see #getRemoveAbandonedTimeoutDuration() * @since 2.10.0 */ public void setRemoveAbandonedTimeout(final Duration removeAbandonedTimeout) { this.removeAbandonedTimeoutDuration = PoolImplUtils.nonNull(removeAbandonedTimeout, DEFAULT_REMOVE_ABANDONED_TIMEOUT_DURATION); } /** * Sets the flag to require full stack traces for logging abandoned connections when enabled. * * @param requireFullStackTrace indicates whether or not full stack traces are required in * abandoned connection logs * @see CallStack * @see #getRequireFullStackTrace() * @since 2.5 */ public void setRequireFullStackTrace(final boolean requireFullStackTrace) { this.requireFullStackTrace = requireFullStackTrace; } /** * If the pool implements {@link UsageTracking}, configure whether the pool * should record a stack trace every time a method is called on a pooled * object and retain the most recent stack trace to aid debugging of * abandoned objects. * * @param useUsageTracking A value of {@code true} will enable * the recording of a stack trace on every use * of a pooled object */ public void setUseUsageTracking(final boolean useUsageTracking) { this.useUsageTracking = useUsageTracking; } /** * @since 2.4.3 */ @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("AbandonedConfig [removeAbandonedOnBorrow="); builder.append(removeAbandonedOnBorrow); builder.append(", removeAbandonedOnMaintenance="); builder.append(removeAbandonedOnMaintenance); builder.append(", removeAbandonedTimeoutDuration="); builder.append(removeAbandonedTimeoutDuration); builder.append(", logAbandoned="); builder.append(logAbandoned); builder.append(", logWriter="); builder.append(logWriter); builder.append(", useUsageTracking="); builder.append(useUsageTracking); builder.append("]"); return builder.toString(); } }
5,269
0
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3/impl/DefaultPooledObjectInfo.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.impl; import java.io.PrintWriter; import java.io.StringWriter; import java.text.SimpleDateFormat; import java.util.Objects; import org.apache.commons.pool3.PooledObject; /** * Implementation of object that is used to provide information on pooled * objects via JMX. * * @since 2.0 */ public class DefaultPooledObjectInfo implements DefaultPooledObjectInfoMBean { private static final String PATTERN = "yyyy-MM-dd HH:mm:ss Z"; private final PooledObject<?> pooledObject; /** * Constructs a new instance for the given pooled object. * * @param pooledObject The pooled object that this instance will represent * @throws NullPointerException if {@code obj} is {@code null} */ public DefaultPooledObjectInfo(final PooledObject<?> pooledObject) { this.pooledObject = Objects.requireNonNull(pooledObject, "pooledObject"); } @Override public long getBorrowedCount() { return pooledObject.getBorrowedCount(); } @Override public long getCreateTime() { return pooledObject.getCreateInstant().toEpochMilli(); } @Override public String getCreateTimeFormatted() { return getTimeMillisFormatted(getCreateTime()); } @Override public long getLastBorrowTime() { return pooledObject.getLastBorrowInstant().toEpochMilli(); } @Override public String getLastBorrowTimeFormatted() { return getTimeMillisFormatted(getLastBorrowTime()); } @Override public String getLastBorrowTrace() { final StringWriter sw = new StringWriter(); pooledObject.printStackTrace(new PrintWriter(sw)); return sw.toString(); } @Override public long getLastReturnTime() { return pooledObject.getLastReturnInstant().toEpochMilli(); } @Override public String getLastReturnTimeFormatted() { return getTimeMillisFormatted(getLastReturnTime()); } @Override public String getPooledObjectToString() { return Objects.toString(pooledObject.getObject(), null); } @Override public String getPooledObjectType() { final Object object = pooledObject.getObject(); return object != null ? object.getClass().getName() : null; } private String getTimeMillisFormatted(final long millis) { return new SimpleDateFormat(PATTERN).format(Long.valueOf(millis)); } /** * @since 2.4.3 */ @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("DefaultPooledObjectInfo [pooledObject="); builder.append(pooledObject); builder.append("]"); return builder.toString(); } }
5,270
0
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3/impl/BaseGenericObjectPool.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.impl; import java.io.PrintWriter; import java.io.StringWriter; import java.io.Writer; import java.lang.management.ManagementFactory; import java.lang.ref.WeakReference; import java.lang.reflect.InvocationTargetException; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; import java.util.Deque; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.TimerTask; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Collectors; import javax.management.InstanceAlreadyExistsException; import javax.management.InstanceNotFoundException; import javax.management.MBeanRegistrationException; import javax.management.MBeanServer; import javax.management.MalformedObjectNameException; import javax.management.NotCompliantMBeanException; import javax.management.ObjectName; import org.apache.commons.pool3.BaseObject; import org.apache.commons.pool3.PooledObject; import org.apache.commons.pool3.PooledObjectState; import org.apache.commons.pool3.SwallowedExceptionListener; /** * Base class that provides common functionality for {@link GenericObjectPool} * and {@link GenericKeyedObjectPool}. The primary reason this class exists is * reduce code duplication between the two pool implementations. * * @param <T> Type of element pooled in this pool. * @param <E> Type of exception thrown in this pool. * * This class is intended to be thread-safe. * * @since 2.0 */ public abstract class BaseGenericObjectPool<T, E extends Exception> extends BaseObject implements AutoCloseable { /** * The idle object eviction iterator. Holds a reference to the idle objects. */ final class EvictionIterator implements Iterator<PooledObject<T>> { private final Deque<PooledObject<T>> idleObjects; private final Iterator<PooledObject<T>> idleObjectIterator; /** * Constructs 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(); } } /** * Gets the idle object deque referenced by this iterator. * @return the idle object deque */ public Deque<PooledObject<T>> getIdleObjects() { return idleObjects; } /** {@inheritDoc} */ @Override public boolean hasNext() { return idleObjectIterator.hasNext(); } /** {@inheritDoc} */ @Override public PooledObject<T> next() { return idleObjectIterator.next(); } /** {@inheritDoc} */ @Override public void remove() { idleObjectIterator.remove(); } } /** * The idle object evictor {@link TimerTask}. * * @see GenericKeyedObjectPool#setTimeBetweenEvictionRunsMillis */ final class Evictor implements Runnable { private ScheduledFuture<?> scheduledFuture; /** * Cancels the scheduled future. */ void cancel() { scheduledFuture.cancel(false); } BaseGenericObjectPool<T, E> owner() { return BaseGenericObjectPool.this; } /** * Run pool maintenance. Evict objects qualifying for eviction and then * ensure that the minimum number of idle instances are available. * Since the Timer that invokes Evictors is shared for all Pools but * pools may exist in different class loaders, the Evictor ensures that * any actions taken are under the class loader of the factory * associated with the pool. */ @Override public void run() { final ClassLoader savedClassLoader = Thread.currentThread().getContextClassLoader(); try { if (factoryClassLoader != null) { // Set the class loader for the factory final ClassLoader cl = factoryClassLoader.get(); if (cl == null) { // The pool has been dereferenced and the class loader // GC'd. Cancel this timer so the pool can be GC'd as // well. cancel(); return; } Thread.currentThread().setContextClassLoader(cl); } // Evict from the pool try { evict(); } catch (final Exception e) { swallowException(e); } catch (final OutOfMemoryError oome) { // Log problem but give evictor thread a chance to continue // in case error is recoverable oome.printStackTrace(System.err); } // Re-create idle instances. try { ensureMinIdle(); } catch (final Exception e) { swallowException(e); } } finally { // Restore the previous CCL Thread.currentThread().setContextClassLoader(savedClassLoader); } } /** * Sets the scheduled future. * * @param scheduledFuture the scheduled future. */ void setScheduledFuture(final ScheduledFuture<?> scheduledFuture) { this.scheduledFuture = scheduledFuture; } @Override public String toString() { return getClass().getName() + " [scheduledFuture=" + scheduledFuture + "]"; } } /** * Wrapper for objects under management by the pool. * * GenericObjectPool and GenericKeyedObjectPool maintain references to all * objects under management using maps keyed on the objects. This wrapper * class ensures that objects can work as hash keys. * * @param <T> type of objects in the pool. */ static class IdentityWrapper<T> { /** * Constructs a wrapper for the object in the {@link PooledObject}. * * @param <T> type of objects in the {@link PooledObject}. * @param pooledObject contains the object to wrap. * @return a new instance wrapping the object in the {@link PooledObject}. */ static <T> IdentityWrapper<T> on(final PooledObject<T> pooledObject) { return new IdentityWrapper<>(pooledObject.getObject()); } /** Wrapped object */ private final T instance; /** * Constructs a wrapper for an instance. * * @param instance object to wrap. */ public IdentityWrapper(final T instance) { this.instance = instance; } @Override @SuppressWarnings("rawtypes") public boolean equals(final Object other) { return other instanceof IdentityWrapper && ((IdentityWrapper) other).instance == instance; } /** * @return the wrapped object */ public T getObject() { return instance; } @Override public int hashCode() { return System.identityHashCode(instance); } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("IdentityWrapper [instance="); builder.append(instance); builder.append("]"); return builder.toString(); } } /** * Maintains a cache of values for a single metric and reports * statistics on the cached values. */ private static final class StatsStore { private static final int NULL = -1; private final AtomicLong[] values; private final int size; private int index; /** * Constructs a StatsStore with the given cache size. * * @param size number of values to maintain in the cache. */ StatsStore(final int size) { this.size = size; values = new AtomicLong[size]; Arrays.setAll(values, i -> new AtomicLong(NULL)); } void add(final Duration value) { add(value.toMillis()); } /** * Adds a value to the cache. If the cache is full, one of the * existing values is replaced by the new value. * * @param value new value to add to the cache. */ synchronized void add(final long value) { values[index].set(value); index++; if (index == size) { index = 0; } } /** * Gets the mean of the cached values. * * @return the mean of the cache, truncated to long */ public long getMean() { double result = 0; int counter = 0; for (int i = 0; i < size; i++) { final long value = values[i].get(); if (value != NULL) { counter++; result = result * ((counter - 1) / (double) counter) + value / (double) counter; } } return (long) result; } /** * Gets the mean Duration of the cached values. * * @return the mean Duration of the cache, truncated to long milliseconds of a Duration. */ Duration getMeanDuration() { return Duration.ofMillis(getMean()); } /** * Gets the current values as a List. * * @return the current values as a List. */ synchronized List<AtomicLong> getValues() { return Arrays.stream(values, 0, index).collect(Collectors.toList()); } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("StatsStore ["); // Only append what's been filled in. builder.append(getValues()); builder.append("], size="); builder.append(size); builder.append(", index="); builder.append(index); builder.append("]"); return builder.toString(); } } // Constants /** * The size of the caches used to store historical data for some attributes * so that rolling means may be calculated. */ public static final int MEAN_TIMING_STATS_CACHE_SIZE = 100; private static final String EVICTION_POLICY_TYPE_NAME = EvictionPolicy.class.getName(); private static final Duration DEFAULT_REMOVE_ABANDONED_TIMEOUT = Duration.ofSeconds(Integer.MAX_VALUE); // Configuration attributes private volatile int maxTotal = GenericKeyedObjectPoolConfig.DEFAULT_MAX_TOTAL; private volatile boolean blockWhenExhausted = BaseObjectPoolConfig.DEFAULT_BLOCK_WHEN_EXHAUSTED; private volatile Duration maxWaitDuration = BaseObjectPoolConfig.DEFAULT_MAX_WAIT; private volatile boolean lifo = BaseObjectPoolConfig.DEFAULT_LIFO; private final boolean fairness; private volatile boolean testOnCreate = BaseObjectPoolConfig.DEFAULT_TEST_ON_CREATE; private volatile boolean testOnBorrow = BaseObjectPoolConfig.DEFAULT_TEST_ON_BORROW; private volatile boolean testOnReturn = BaseObjectPoolConfig.DEFAULT_TEST_ON_RETURN; private volatile boolean testWhileIdle = BaseObjectPoolConfig.DEFAULT_TEST_WHILE_IDLE; private volatile Duration durationBetweenEvictionRuns = BaseObjectPoolConfig.DEFAULT_DURATION_BETWEEN_EVICTION_RUNS; private volatile int numTestsPerEvictionRun = BaseObjectPoolConfig.DEFAULT_NUM_TESTS_PER_EVICTION_RUN; private volatile Duration minEvictableIdleDuration = BaseObjectPoolConfig.DEFAULT_MIN_EVICTABLE_IDLE_DURATION; private volatile Duration softMinEvictableIdleDuration = BaseObjectPoolConfig.DEFAULT_SOFT_MIN_EVICTABLE_IDLE_DURATION; private volatile EvictionPolicy<T> evictionPolicy; private volatile Duration evictorShutdownTimeoutDuration = BaseObjectPoolConfig.DEFAULT_EVICTOR_SHUTDOWN_TIMEOUT; // Internal (primarily state) attributes final Object closeLock = new Object(); volatile boolean closed; final Object evictionLock = new Object(); private Evictor evictor; // @GuardedBy("evictionLock") EvictionIterator evictionIterator; // @GuardedBy("evictionLock") /** * Class loader for evictor thread to use since, in a JavaEE or similar * environment, the context class loader for the evictor thread may not have * visibility of the correct factory. See POOL-161. Uses a weak reference to * avoid potential memory leaks if the Pool is discarded rather than closed. */ private final WeakReference<ClassLoader> factoryClassLoader; // Monitoring (primarily JMX) attributes private final ObjectName objectName; private final String creationStackTrace; private final AtomicLong borrowedCount = new AtomicLong(); private final AtomicLong returnedCount = new AtomicLong(); final AtomicLong createdCount = new AtomicLong(); final AtomicLong destroyedCount = new AtomicLong(); final AtomicLong destroyedByEvictorCount = new AtomicLong(); final AtomicLong destroyedByBorrowValidationCount = new AtomicLong(); private final StatsStore activeTimes = new StatsStore(MEAN_TIMING_STATS_CACHE_SIZE); private final StatsStore idleTimes = new StatsStore(MEAN_TIMING_STATS_CACHE_SIZE); private final StatsStore waitTimes = new StatsStore(MEAN_TIMING_STATS_CACHE_SIZE); private final AtomicReference<Duration> maxBorrowWaitDuration = new AtomicReference<>(Duration.ZERO); private volatile SwallowedExceptionListener swallowedExceptionListener; private volatile boolean messageStatistics; /** Additional configuration properties for abandoned object tracking. */ protected volatile AbandonedConfig abandonedConfig; /** * Handles JMX registration (if required) and the initialization required for * monitoring. * * @param config Pool configuration * @param jmxNameBase The default base JMX name for the new pool unless * overridden by the config * @param jmxNamePrefix Prefix to be used for JMX name for the new pool */ public BaseGenericObjectPool(final BaseObjectPoolConfig<T> config, final String jmxNameBase, final String jmxNamePrefix) { if (config.getJmxEnabled()) { this.objectName = jmxRegister(config, jmxNameBase, jmxNamePrefix); } else { this.objectName = null; } // Populate the creation stack trace this.creationStackTrace = getStackTrace(new Exception()); // save the current TCCL (if any) to be used later by the evictor Thread final ClassLoader cl = Thread.currentThread().getContextClassLoader(); if (cl == null) { factoryClassLoader = null; } else { factoryClassLoader = new WeakReference<>(cl); } fairness = config.getFairness(); } /** * Appends statistics if enabled. * <p> * Statistics may not accurately reflect snapshot state at the time of the exception because we do not want to lock the pool when gathering this * information. * </p> * * @param string The root string. * @return The root string plus statistics. */ String appendStats(final String string) { return messageStatistics ? string + ", " + getStatsString() : string; } /** * Verifies that the pool is open. * @throws IllegalStateException if the pool is closed. */ final void assertOpen() throws IllegalStateException { if (isClosed()) { throw new IllegalStateException("Pool not open"); } } /** * Casts the given throwable to {@code E}. * * @param throwable the throwable. * @return the input. * @since 2.12.0 */ @SuppressWarnings("unchecked") protected E cast(final Throwable throwable) { return (E) throwable; } /** * Closes the pool, destroys the remaining idle objects and, if registered * in JMX, deregisters it. */ @Override public abstract void close(); /** * Creates a list of pooled objects to remove based on their state. * @param abandonedConfig The abandoned configuration. * @param allObjects PooledObject instances to consider. * @return a list of pooled objects to remove based on their state. */ ArrayList<PooledObject<T>> createRemoveList(final AbandonedConfig abandonedConfig, final Map<IdentityWrapper<T>, PooledObject<T>> allObjects) { final Instant timeout = Instant.now().minus(abandonedConfig.getRemoveAbandonedTimeoutDuration()); final ArrayList<PooledObject<T>> remove = new ArrayList<>(); allObjects.values().forEach(pooledObject -> { synchronized (pooledObject) { if (pooledObject.getState() == PooledObjectState.ALLOCATED && pooledObject.getLastUsedInstant().compareTo(timeout) <= 0) { pooledObject.markAbandoned(); remove.add(pooledObject); } } }); return remove; } /** * Tries to ensure that the configured minimum number of idle instances are * available in the pool. * @throws E if an error occurs creating idle instances */ abstract void ensureMinIdle() throws E; /** * Perform {@code numTests} idle object eviction tests, evicting * examined objects that meet the criteria for eviction. If * {@code testWhileIdle} is true, examined objects are validated * when visited (and removed if invalid); otherwise only objects that * have been idle for more than {@code minEvicableIdleTimeMillis} * are removed. * * @throws E when there is a problem evicting idle objects. */ public abstract void evict() throws E; /** * Gets whether to block when the {@code borrowObject()} method is * invoked when the pool is exhausted (the maximum number of "active" * objects has been reached). * * @return {@code true} if {@code borrowObject()} should block * when the pool is exhausted * * @see #setBlockWhenExhausted */ public final boolean getBlockWhenExhausted() { return blockWhenExhausted; } /** * Gets the total number of objects successfully borrowed from this pool over the * lifetime of the pool. * @return the borrowed object count */ public final long getBorrowedCount() { return borrowedCount.get(); } /** * Gets the total number of objects created for this pool over the lifetime of * the pool. * @return the created object count */ public final long getCreatedCount() { return createdCount.get(); } /** * Gets the stack trace for the call that created this pool. JMX * registration may trigger a memory leak so it is important that pools are * deregistered when no longer used by calling the {@link #close()} method. * This method is provided to assist with identifying code that creates but * does not close it thereby creating a memory leak. * @return pool creation stack trace */ public final String getCreationStackTrace() { return creationStackTrace; } /** * Gets the total number of objects destroyed by this pool as a result of failing * validation during {@code borrowObject()} over the lifetime of the * pool. * @return validation destroyed object count */ public final long getDestroyedByBorrowValidationCount() { return destroyedByBorrowValidationCount.get(); } /** * Gets the total number of objects destroyed by the evictor associated with this * pool over the lifetime of the pool. * @return the evictor destroyed object count */ public final long getDestroyedByEvictorCount() { return destroyedByEvictorCount.get(); } /** * Gets the total number of objects destroyed by this pool over the lifetime of * the pool. * @return the destroyed object count */ public final long getDestroyedCount() { return destroyedCount.get(); } /** * Gets the duration to sleep between runs of the idle * object evictor thread. When non-positive, no idle object evictor thread * will be run. * * @return duration to sleep between evictor runs * * @see #setDurationBetweenEvictionRuns(Duration) * @since 2.11.0 */ public final Duration getDurationBetweenEvictionRuns() { return durationBetweenEvictionRuns; } /** * Gets the {@link EvictionPolicy} defined for this pool. * * @return the eviction policy * @since 2.4 * @since 2.6.0 Changed access from protected to public. */ public EvictionPolicy<T> getEvictionPolicy() { return evictionPolicy; } /** * Gets the name of the {@link EvictionPolicy} implementation that is * used by this pool. * * @return The fully qualified class name of the {@link EvictionPolicy} * * @see #setEvictionPolicyClassName(String) */ public final String getEvictionPolicyClassName() { return evictionPolicy.getClass().getName(); } /** * Gets the timeout that will be used when waiting for the Evictor to * shutdown if this pool is closed and it is the only pool still using the * the value for the Evictor. * * @return The timeout that will be used while waiting for * the Evictor to shut down. * @since 2.11.0 */ public final Duration getEvictorShutdownTimeoutDuration() { return evictorShutdownTimeoutDuration; } /** * Gets whether or not the pool serves threads waiting to borrow objects fairly. * True means that waiting threads are served as if waiting in a FIFO queue. * * @return {@code true} if waiting threads are to be served * by the pool in arrival order */ public final boolean getFairness() { return fairness; } /** * Gets the name under which the pool has been registered with the * platform MBean server or {@code null} if the pool has not been * registered. * @return the JMX name */ public final ObjectName getJmxName() { return objectName; } /** * Gets whether the pool has LIFO (last in, first out) behavior with * respect to idle objects - always returning the most recently used object * from the pool, or as a FIFO (first in, first out) queue, where the pool * always returns the oldest object in the idle object pool. * * @return {@code true} if the pool is configured with LIFO behavior * or {@code false} if the pool is configured with FIFO * behavior * * @see #setLifo */ public final boolean getLifo() { return lifo; } /** * Gets whether this pool identifies and logs any abandoned objects. * * @return {@code true} if abandoned object removal is configured for this * pool and removal events are to be logged otherwise {@code false} * * @see AbandonedConfig#getLogAbandoned() * @since 2.11.0 */ public boolean getLogAbandoned() { final AbandonedConfig ac = this.abandonedConfig; return ac != null && ac.getLogAbandoned(); } /** * Gets the maximum time a thread has waited to borrow objects from the pool. * @return maximum wait time in milliseconds since the pool was created */ public final long getMaxBorrowWaitTimeMillis() { return maxBorrowWaitDuration.get().toMillis(); } /** * Gets the maximum number of objects that can be allocated by the pool * (checked out to clients, or idle awaiting checkout) at a given time. When * negative, there is no limit to the number of objects that can be * managed by the pool at one time. * * @return the cap on the total number of object instances managed by the * pool. * * @see #setMaxTotal */ public final int getMaxTotal() { return maxTotal; } /** * Gets the maximum duration the * {@code borrowObject()} method should block before throwing an * exception when the pool is exhausted and * {@link #getBlockWhenExhausted} is true. When less than 0, the * {@code borrowObject()} method may block indefinitely. * * @return the maximum number of milliseconds {@code borrowObject()} * will block. * * @see #setMaxWait * @see #setBlockWhenExhausted * @since 2.11.0 */ public final Duration getMaxWaitDuration() { return maxWaitDuration; } /** * Gets the maximum amount of time (in milliseconds) the * {@code borrowObject()} method should block before throwing an * exception when the pool is exhausted and * {@link #getBlockWhenExhausted} is true. When less than 0, the * {@code borrowObject()} method may block indefinitely. * * @return the maximum number of milliseconds {@code borrowObject()} * will block. * @see #setMaxWait * @see #setBlockWhenExhausted * @deprecated Use {@link #getMaxWaitDuration()}. */ @Deprecated public final long getMaxWaitMillis() { return maxWaitDuration.toMillis(); } /** * Gets the mean time objects are active for based on the last {@link * #MEAN_TIMING_STATS_CACHE_SIZE} objects returned to the pool. * @return mean time an object has been checked out from the pool among * recently returned objects */ public final Duration getMeanActiveDuration() { return activeTimes.getMeanDuration(); } /** * Gets the mean time objects are active for based on the last {@link * #MEAN_TIMING_STATS_CACHE_SIZE} objects returned to the pool. * @return mean time an object has been checked out from the pool among * recently returned objects */ public final long getMeanActiveTimeMillis() { return activeTimes.getMean(); } /** * Gets the mean time threads wait to borrow an object based on the last {@link * #MEAN_TIMING_STATS_CACHE_SIZE} objects borrowed from the pool. * * @return mean time in milliseconds that a recently served thread has had * to wait to borrow an object from the pool. * @since 2.12.0 */ public final Duration getMeanBorrowWaitDuration() { return waitTimes.getMeanDuration(); } /** * Gets the mean time threads wait to borrow an object based on the last {@link * #MEAN_TIMING_STATS_CACHE_SIZE} objects borrowed from the pool. * @return mean time in milliseconds that a recently served thread has had * to wait to borrow an object from the pool */ public final long getMeanBorrowWaitTimeMillis() { return waitTimes.getMean(); } /** * Gets the mean time objects are idle for based on the last {@link * #MEAN_TIMING_STATS_CACHE_SIZE} objects borrowed from the pool. * @return mean time an object has been idle in the pool among recently * borrowed objects */ public final Duration getMeanIdleDuration() { return idleTimes.getMeanDuration(); } /** * Gets the mean time objects are idle for based on the last {@link * #MEAN_TIMING_STATS_CACHE_SIZE} objects borrowed from the pool. * * @return mean time an object has been idle in the pool among recently * borrowed objects. * @deprecated Use {@link #getMeanIdleDuration()}. */ @Deprecated public final long getMeanIdleTimeMillis() { return idleTimes.getMean(); } /** * Gets whether to include statistics in exception messages. * <p> * Statistics may not accurately reflect snapshot state at the time of the exception because we do not want to lock the pool when gathering this * information. * </p> * * @return whether to include statistics in exception messages. * @since 2.11.0 */ public boolean getMessageStatistics() { return messageStatistics; } /** * Gets the minimum amount of time an object may sit idle in the pool * before it is eligible for eviction by the idle object evictor (if any - * see {@link #setDurationBetweenEvictionRuns(Duration)}). When non-positive, * no objects will be evicted from the pool due to idle time alone. * * @return minimum amount of time an object may sit idle in the pool before * it is eligible for eviction * * @see #setMinEvictableIdleDuration(Duration) * @see #setDurationBetweenEvictionRuns(Duration) * @since 2.11.0 */ public final Duration getMinEvictableIdleDuration() { return minEvictableIdleDuration; } /** * Gets the minimum amount of time an object may sit idle in the pool * before it is eligible for eviction by the idle object evictor (if any - * see {@link #setDurationBetweenEvictionRuns(Duration)}). When non-positive, * no objects will be evicted from the pool due to idle time alone. * * @return minimum amount of time an object may sit idle in the pool before * it is eligible for eviction * * @see #setMinEvictableIdleDuration(Duration) * @see #setDurationBetweenEvictionRuns(Duration) * @deprecated Use {@link #getMinEvictableIdleDuration()}. */ @Deprecated public final long getMinEvictableIdleTimeMillis() { return minEvictableIdleDuration.toMillis(); } /** * Gets the number of instances currently idle in this pool. * @return count of instances available for checkout from the pool */ public abstract int getNumIdle(); /** * Gets the maximum number of objects to examine during each run (if any) * of the idle object evictor thread. When positive, the number of tests * performed for a run will be the minimum of the configured value and the * number of idle instances in the pool. When negative, the number of tests * performed will be <code>ceil({@link #getNumIdle}/ * abs({@link #getNumTestsPerEvictionRun}))</code> which means that when the * value is {@code -n} roughly one nth of the idle objects will be * tested per run. * * @return max number of objects to examine during each evictor run * * @see #setNumTestsPerEvictionRun * @see #setDurationBetweenEvictionRuns(Duration) */ public final int getNumTestsPerEvictionRun() { return numTestsPerEvictionRun; } /** * Gets whether a check is made for abandoned objects when an object is borrowed * from this pool. * * @return {@code true} if abandoned object removal is configured to be * activated by borrowObject otherwise {@code false} * * @see AbandonedConfig#getRemoveAbandonedOnBorrow() * @since 2.11.0 */ public boolean getRemoveAbandonedOnBorrow() { final AbandonedConfig ac = this.abandonedConfig; return ac != null && ac.getRemoveAbandonedOnBorrow(); } /** * Gets whether a check is made for abandoned objects when the evictor runs. * * @return {@code true} if abandoned object removal is configured to be * activated when the evictor runs otherwise {@code false} * * @see AbandonedConfig#getRemoveAbandonedOnMaintenance() * @since 2.11.0 */ public boolean getRemoveAbandonedOnMaintenance() { final AbandonedConfig ac = this.abandonedConfig; return ac != null && ac.getRemoveAbandonedOnMaintenance(); } /** * Gets the timeout before which an object will be considered to be * abandoned by this pool. * * @return The abandoned object timeout in seconds if abandoned object * removal is configured for this pool; Integer.MAX_VALUE otherwise. * * @see AbandonedConfig#getRemoveAbandonedTimeoutDuration() * @see AbandonedConfig#getRemoveAbandonedTimeoutDuration() * @deprecated Use {@link #getRemoveAbandonedTimeoutDuration()}. * @since 2.11.0 */ @Deprecated public int getRemoveAbandonedTimeout() { return (int) getRemoveAbandonedTimeoutDuration().getSeconds(); } /** * Gets the timeout before which an object will be considered to be * abandoned by this pool. * * @return The abandoned object timeout in seconds if abandoned object * removal is configured for this pool; Integer.MAX_VALUE otherwise. * * @see AbandonedConfig#getRemoveAbandonedTimeoutDuration() * @since 2.11.0 */ public Duration getRemoveAbandonedTimeoutDuration() { final AbandonedConfig ac = this.abandonedConfig; return ac != null ? ac.getRemoveAbandonedTimeoutDuration() : DEFAULT_REMOVE_ABANDONED_TIMEOUT; } /** * Gets the total number of objects returned to this pool over the lifetime of * the pool. This excludes attempts to return the same object multiple * times. * @return the returned object count */ public final long getReturnedCount() { return returnedCount.get(); } /** * Gets the minimum amount of time an object may sit idle in the pool * before it is eligible for eviction by the idle object evictor (if any - * see {@link #setDurationBetweenEvictionRuns(Duration)}), * with the extra condition that at least {@code minIdle} object * instances remain in the pool. This setting is overridden by * {@link #getMinEvictableIdleDuration} (that is, if * {@link #getMinEvictableIdleDuration} is positive, then * {@link #getSoftMinEvictableIdleDuration()} is ignored). * * @return minimum amount of time an object may sit idle in the pool before * it is eligible for eviction if minIdle instances are available * * @see #setSoftMinEvictableIdleDuration(Duration) * @since 2.11.0 */ public final Duration getSoftMinEvictableIdleDuration() { return softMinEvictableIdleDuration; } /** * Gets the stack trace of an exception as a string. * @param e exception to trace * @return exception stack trace as a string */ private String getStackTrace(final Exception e) { // Need the exception in string form to prevent the retention of // references to classes in the stack trace that could trigger a memory // leak in a container environment. final Writer w = new StringWriter(); final PrintWriter pw = new PrintWriter(w); e.printStackTrace(pw); return w.toString(); } /** * Gets a statistics string. * * @return a statistics string. */ String getStatsString() { // Simply listed in AB order. return String.format( "activeTimes=%s, blockWhenExhausted=%s, borrowedCount=%,d, closed=%s, createdCount=%,d, destroyedByBorrowValidationCount=%,d, " + "destroyedByEvictorCount=%,d, evictorShutdownTimeoutDuration=%s, fairness=%s, idleTimes=%s, lifo=%s, maxBorrowWaitDuration=%s, " + "maxTotal=%s, maxWaitDuration=%s, minEvictableIdleDuration=%s, numTestsPerEvictionRun=%s, returnedCount=%s, " + "softMinEvictableIdleDuration=%s, testOnBorrow=%s, testOnCreate=%s, testOnReturn=%s, testWhileIdle=%s, " + "durationBetweenEvictionRuns=%s, waitTimes=%s", activeTimes.getValues(), blockWhenExhausted, borrowedCount.get(), closed, createdCount.get(), destroyedByBorrowValidationCount.get(), destroyedByEvictorCount.get(), evictorShutdownTimeoutDuration, fairness, idleTimes.getValues(), lifo, maxBorrowWaitDuration.get(), maxTotal, maxWaitDuration, minEvictableIdleDuration, numTestsPerEvictionRun, returnedCount, softMinEvictableIdleDuration, testOnBorrow, testOnCreate, testOnReturn, testWhileIdle, durationBetweenEvictionRuns, waitTimes.getValues()); } /** * Gets the listener used (if any) to receive notifications of exceptions * unavoidably swallowed by the pool. * * @return The listener or {@code null} for no listener */ public final SwallowedExceptionListener getSwallowedExceptionListener() { return swallowedExceptionListener; } /** * Gets whether objects borrowed from the pool will be validated before * being returned from the {@code borrowObject()} method. Validation is * performed by the {@code validateObject()} method of the factory * associated with the pool. If the object fails to validate, it will be * removed from the pool and destroyed, and a new attempt will be made to * borrow an object from the pool. * * @return {@code true} if objects are validated before being returned * from the {@code borrowObject()} method * * @see #setTestOnBorrow */ public final boolean getTestOnBorrow() { return testOnBorrow; } /** * Gets whether objects created for the pool will be validated before * being returned from the {@code borrowObject()} method. Validation is * performed by the {@code validateObject()} method of the factory * associated with the pool. If the object fails to validate, then * {@code borrowObject()} will fail. * * @return {@code true} if newly created objects are validated before * being returned from the {@code borrowObject()} method * * @see #setTestOnCreate * * @since 2.2 */ public final boolean getTestOnCreate() { return testOnCreate; } /** * Gets whether objects borrowed from the pool will be validated when * they are returned to the pool via the {@code returnObject()} method. * Validation is performed by the {@code validateObject()} method of * the factory associated with the pool. Returning objects that fail validation * are destroyed rather then being returned the pool. * * @return {@code true} if objects are validated on return to * the pool via the {@code returnObject()} method * * @see #setTestOnReturn */ public final boolean getTestOnReturn() { return testOnReturn; } /** * Gets whether objects sitting idle in the pool will be validated by the * idle object evictor (if any - see * {@link #setDurationBetweenEvictionRuns(Duration)}). Validation is performed * by the {@code validateObject()} method of the factory associated * with the pool. If the object fails to validate, it will be removed from * the pool and destroyed. * * @return {@code true} if objects will be validated by the evictor * * @see #setTestWhileIdle * @see #setDurationBetweenEvictionRuns(Duration) */ public final boolean getTestWhileIdle() { return testWhileIdle; } /** * Gets the number of milliseconds to sleep between runs of the idle * object evictor thread. When non-positive, no idle object evictor thread * will be run. * * @return number of milliseconds to sleep between evictor runs * * @see #setDurationBetweenEvictionRuns(Duration) * @deprecated Use {@link #getDurationBetweenEvictionRuns()}. */ @Deprecated public final long getTimeBetweenEvictionRunsMillis() { return durationBetweenEvictionRuns.toMillis(); } /** * Tests whether or not abandoned object removal is configured for this pool. * * @return true if this pool is configured to detect and remove * abandoned objects * @since 2.11.0 */ public boolean isAbandonedConfig() { return abandonedConfig != null; } /** * Tests whether this pool instance been closed. * @return {@code true} when this pool has been closed. */ public final boolean isClosed() { return closed; } /** * Registers the pool with the platform MBean server. * The registered name will be * {@code jmxNameBase + jmxNamePrefix + i} where i is the least * integer greater than or equal to 1 such that the name is not already * registered. Swallows MBeanRegistrationException, NotCompliantMBeanException * returning null. * * @param config Pool configuration * @param jmxNameBase default base JMX name for this pool * @param jmxNamePrefix name prefix * @return registered ObjectName, null if registration fails */ private ObjectName jmxRegister(final BaseObjectPoolConfig<T> config, final String jmxNameBase, String jmxNamePrefix) { ObjectName newObjectName = null; final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); int i = 1; boolean registered = false; String base = config.getJmxNameBase(); if (base == null) { base = jmxNameBase; } while (!registered) { try { ObjectName objName; // Skip the numeric suffix for the first pool in case there is // only one so the names are cleaner. if (i == 1) { objName = new ObjectName(base + jmxNamePrefix); } else { objName = new ObjectName(base + jmxNamePrefix + i); } if (!mbs.isRegistered(objName)) { mbs.registerMBean(this, objName); newObjectName = objName; registered = true; } else { // Increment the index and try again i++; } } catch (final MalformedObjectNameException e) { if (BaseObjectPoolConfig.DEFAULT_JMX_NAME_PREFIX.equals( jmxNamePrefix) && jmxNameBase.equals(base)) { // Shouldn't happen. Skip registration if it does. registered = true; } else { // Must be an invalid name. Use the defaults instead. jmxNamePrefix = BaseObjectPoolConfig.DEFAULT_JMX_NAME_PREFIX; base = jmxNameBase; } } catch (final InstanceAlreadyExistsException e) { // Increment the index and try again i++; } catch (final MBeanRegistrationException | NotCompliantMBeanException e) { // Shouldn't happen. Skip registration if it does. registered = true; } } return newObjectName; } /** * Unregisters this pool's MBean. */ final void jmxUnregister() { if (objectName != null) { try { ManagementFactory.getPlatformMBeanServer().unregisterMBean(objectName); } catch (final MBeanRegistrationException | InstanceNotFoundException e) { swallowException(e); } } } /** * Marks the object as returning to the pool. * @param pooledObject instance to return to the keyed pool */ protected void markReturningState(final PooledObject<T> pooledObject) { synchronized (pooledObject) { if (pooledObject.getState() != PooledObjectState.ALLOCATED) { throw new IllegalStateException("Object has already been returned to this pool or is invalid"); } pooledObject.markReturning(); // Keep from being marked abandoned } } /** * Sets the abandoned object removal configuration. * * @param abandonedConfig the new configuration to use. This is used by value. * * @see AbandonedConfig * @since 2.11.0 */ public void setAbandonedConfig(final AbandonedConfig abandonedConfig) { this.abandonedConfig = AbandonedConfig.copy(abandonedConfig); } /** * Sets whether to block when the {@code borrowObject()} method is * invoked when the pool is exhausted (the maximum number of "active" * objects has been reached). * * @param blockWhenExhausted {@code true} if * {@code borrowObject()} should block * when the pool is exhausted * * @see #getBlockWhenExhausted */ public final void setBlockWhenExhausted(final boolean blockWhenExhausted) { this.blockWhenExhausted = blockWhenExhausted; } /** * Sets the receiver with the given configuration. * * @param config Initialization source. */ protected void setConfig(final BaseObjectPoolConfig<T> config) { setLifo(config.getLifo()); setMaxWait(config.getMaxWaitDuration()); setBlockWhenExhausted(config.getBlockWhenExhausted()); setTestOnCreate(config.getTestOnCreate()); setTestOnBorrow(config.getTestOnBorrow()); setTestOnReturn(config.getTestOnReturn()); setTestWhileIdle(config.getTestWhileIdle()); setNumTestsPerEvictionRun(config.getNumTestsPerEvictionRun()); setMinEvictableIdleDuration(config.getMinEvictableIdleDuration()); setDurationBetweenEvictionRuns(config.getDurationBetweenEvictionRuns()); setSoftMinEvictableIdleDuration(config.getSoftMinEvictableIdleDuration()); final EvictionPolicy<T> policy = config.getEvictionPolicy(); if (policy == null) { // Use the class name (pre-2.6.0 compatible) setEvictionPolicyClassName(config.getEvictionPolicyClassName()); } else { // Otherwise, use the class (2.6.0 feature) setEvictionPolicy(policy); } setEvictorShutdownTimeout(config.getEvictorShutdownTimeoutDuration()); } /** * Sets the number of milliseconds to sleep between runs of the idle object evictor thread. * <ul> * <li>When positive, the idle object evictor thread starts.</li> * <li>When non-positive, no idle object evictor thread runs.</li> * </ul> * * @param timeBetweenEvictionRuns * duration to sleep between evictor runs * * @see #getDurationBetweenEvictionRuns() */ public final void setDurationBetweenEvictionRuns(final Duration timeBetweenEvictionRuns) { this.durationBetweenEvictionRuns = PoolImplUtils.nonNull(timeBetweenEvictionRuns, BaseObjectPoolConfig.DEFAULT_DURATION_BETWEEN_EVICTION_RUNS); startEvictor(this.durationBetweenEvictionRuns); } /** * Sets the eviction policy for this pool. * * @param evictionPolicy * the eviction policy for this pool. * @since 2.6.0 */ public void setEvictionPolicy(final EvictionPolicy<T> evictionPolicy) { this.evictionPolicy = evictionPolicy; } /** * Sets the eviction policy. * * @param className Eviction policy class name. * @param classLoader Load the class from this class loader. * @throws LinkageError if the linkage fails * @throws ExceptionInInitializerError if the initialization provoked by this method fails * @throws ClassNotFoundException if the class cannot be located by the specified class loader * @throws IllegalAccessException if this {@code Constructor} object is enforcing Java language access control and the underlying constructor is * inaccessible. * @throws IllegalArgumentException if the number of actual and formal parameters differ; if an unwrapping conversion for primitive arguments fails; or if, * after possible unwrapping, a parameter value cannot be converted to the corresponding formal parameter type by a method invocation conversion; if * this constructor pertains to an enum type. * @throws InstantiationException if the class that declares the underlying constructor represents an abstract class. * @throws InvocationTargetException if the underlying constructor throws an exception. * @throws ExceptionInInitializerError if the initialization provoked by this method fails. * @throws NoSuchMethodException if a matching method is not found. * @throws SecurityException If a security manage is present and the caller's class loader is not the same as or an ancestor of the class loader for the * current class and invocation of {@link SecurityManager#checkPackageAccess s.checkPackageAccess()} denies access to the package of this class. */ @SuppressWarnings("unchecked") private void setEvictionPolicy(final String className, final ClassLoader classLoader) throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { final Class<?> clazz = Class.forName(className, true, classLoader); final Object policy = clazz.getConstructor().newInstance(); this.evictionPolicy = (EvictionPolicy<T>) policy; } /** * Sets the name of the {@link EvictionPolicy} implementation that is used by this pool. The Pool will attempt to * load the class using the thread context class loader. If that fails, the use the class loader for the * {@link EvictionPolicy} interface. * * @param evictionPolicyClassName * the fully qualified class name of the new eviction policy * * @see #getEvictionPolicyClassName() * @since 2.6.0 If loading the class using the thread context class loader fails, use the class loader for the * {@link EvictionPolicy} interface. */ public final void setEvictionPolicyClassName(final String evictionPolicyClassName) { setEvictionPolicyClassName(evictionPolicyClassName, Thread.currentThread().getContextClassLoader()); } /** * Sets the name of the {@link EvictionPolicy} implementation that is used by this pool. The Pool will attempt to * load the class using the given class loader. If that fails, use the class loader for the {@link EvictionPolicy} * interface. * * @param evictionPolicyClassName * the fully qualified class name of the new eviction policy * @param classLoader * the class loader to load the given {@code evictionPolicyClassName}. * * @see #getEvictionPolicyClassName() * @since 2.6.0 If loading the class using the given class loader fails, use the class loader for the * {@link EvictionPolicy} interface. */ public final void setEvictionPolicyClassName(final String evictionPolicyClassName, final ClassLoader classLoader) { // Getting epClass here and now best matches the caller's environment final Class<?> epClass = EvictionPolicy.class; final ClassLoader epClassLoader = epClass.getClassLoader(); try { try { setEvictionPolicy(evictionPolicyClassName, classLoader); } catch (final ClassCastException | ClassNotFoundException e) { setEvictionPolicy(evictionPolicyClassName, epClassLoader); } } catch (final ClassCastException e) { throw new IllegalArgumentException("Class " + evictionPolicyClassName + " from class loaders [" + classLoader + ", " + epClassLoader + "] do not implement " + EVICTION_POLICY_TYPE_NAME); } catch (final ClassNotFoundException | InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { throw new IllegalArgumentException( "Unable to create " + EVICTION_POLICY_TYPE_NAME + " instance of type " + evictionPolicyClassName, e); } } /** * Sets the timeout that will be used when waiting for the Evictor to shutdown if this pool is closed and it is the * only pool still using the value for the Evictor. * * @param evictorShutdownTimeout the timeout in milliseconds that will be used while waiting for the Evictor * to shut down. * @since 2.10.0 */ public final void setEvictorShutdownTimeout(final Duration evictorShutdownTimeout) { this.evictorShutdownTimeoutDuration = PoolImplUtils.nonNull(evictorShutdownTimeout, BaseObjectPoolConfig.DEFAULT_EVICTOR_SHUTDOWN_TIMEOUT); } /** * Sets whether the pool has LIFO (last in, first out) behavior with * respect to idle objects - always returning the most recently used object * from the pool, or as a FIFO (first in, first out) queue, where the pool * always returns the oldest object in the idle object pool. * * @param lifo {@code true} if the pool is to be configured with LIFO * behavior or {@code false} if the pool is to be * configured with FIFO behavior * * @see #getLifo() */ public final void setLifo(final boolean lifo) { this.lifo = lifo; } /** * Sets the cap on the number of objects that can be allocated by the pool * (checked out to clients, or idle awaiting checkout) at a given time. Use * a negative value for no limit. * * @param maxTotal The cap on the total number of object instances managed * by the pool. Negative values mean that there is no limit * to the number of objects allocated by the pool. * * @see #getMaxTotal */ public final void setMaxTotal(final int maxTotal) { this.maxTotal = maxTotal; } /** * Sets the maximum duration the * {@code borrowObject()} method should block before throwing an * exception when the pool is exhausted and * {@link #getBlockWhenExhausted} is true. When less than 0, the * {@code borrowObject()} method may block indefinitely. * * @param maxWaitDuration the maximum duration * {@code borrowObject()} will block or negative * for indefinitely. * * @see #getMaxWaitDuration * @see #setBlockWhenExhausted * @since 2.11.0 */ public final void setMaxWait(final Duration maxWaitDuration) { this.maxWaitDuration = PoolImplUtils.nonNull(maxWaitDuration, BaseObjectPoolConfig.DEFAULT_MAX_WAIT); } /** * Sets whether to include statistics in exception messages. * <p> * Statistics may not accurately reflect snapshot state at the time of the exception because we do not want to lock the pool when gathering this * information. * </p> * * @param messagesDetails whether to include statistics in exception messages. * @since 2.11.0 */ public void setMessagesStatistics(final boolean messagesDetails) { this.messageStatistics = messagesDetails; } /** * Sets the minimum amount of time an object may sit idle in the pool * before it is eligible for eviction by the idle object evictor (if any - * see {@link #setDurationBetweenEvictionRuns(Duration)}). When non-positive, * no objects will be evicted from the pool due to idle time alone. * * @param minEvictableIdleTime * minimum amount of time an object may sit idle in the pool * before it is eligible for eviction * * @see #getMinEvictableIdleDuration * @see #setDurationBetweenEvictionRuns(Duration) */ public final void setMinEvictableIdleDuration(final Duration minEvictableIdleTime) { this.minEvictableIdleDuration = PoolImplUtils.nonNull(minEvictableIdleTime, BaseObjectPoolConfig.DEFAULT_MIN_EVICTABLE_IDLE_DURATION); } /** * Sets the maximum number of objects to examine during each run (if any) * of the idle object evictor thread. When positive, the number of tests * performed for a run will be the minimum of the configured value and the * number of idle instances in the pool. When negative, the number of tests * performed will be <code>ceil({@link #getNumIdle}/ * abs({@link #getNumTestsPerEvictionRun}))</code> which means that when the * value is {@code -n} roughly one nth of the idle objects will be * tested per run. * * @param numTestsPerEvictionRun * max number of objects to examine during each evictor run * * @see #getNumTestsPerEvictionRun * @see #setDurationBetweenEvictionRuns(Duration) */ public final void setNumTestsPerEvictionRun(final int numTestsPerEvictionRun) { this.numTestsPerEvictionRun = numTestsPerEvictionRun; } /** * Sets the minimum amount of time an object may sit idle in the pool * before it is eligible for eviction by the idle object evictor (if any - * see {@link #setDurationBetweenEvictionRuns(Duration)}), * with the extra condition that at least {@code minIdle} object * instances remain in the pool. This setting is overridden by * {@link #getMinEvictableIdleDuration} (that is, if * {@link #getMinEvictableIdleDuration} is positive, then * {@link #getSoftMinEvictableIdleDuration} is ignored). * * @param softMinEvictableIdleTime * minimum amount of time an object may sit idle in the pool * before it is eligible for eviction if minIdle instances are * available * * @see #getSoftMinEvictableIdleDuration * @since 2.11.0 */ public final void setSoftMinEvictableIdleDuration(final Duration softMinEvictableIdleTime) { this.softMinEvictableIdleDuration = PoolImplUtils.nonNull(softMinEvictableIdleTime, BaseObjectPoolConfig.DEFAULT_SOFT_MIN_EVICTABLE_IDLE_DURATION); } /** * Sets the listener used (if any) to receive notifications of exceptions * unavoidably swallowed by the pool. * * @param swallowedExceptionListener The listener or {@code null} * for no listener */ public final void setSwallowedExceptionListener( final SwallowedExceptionListener swallowedExceptionListener) { this.swallowedExceptionListener = swallowedExceptionListener; } /** * Sets whether objects borrowed from the pool will be validated before * being returned from the {@code borrowObject()} method. Validation is * performed by the {@code validateObject()} method of the factory * associated with the pool. If the object fails to validate, it will be * removed from the pool and destroyed, and a new attempt will be made to * borrow an object from the pool. * * @param testOnBorrow {@code true} if objects should be validated * before being returned from the * {@code borrowObject()} method * * @see #getTestOnBorrow */ public final void setTestOnBorrow(final boolean testOnBorrow) { this.testOnBorrow = testOnBorrow; } /** * Sets whether objects created for the pool will be validated before * being returned from the {@code borrowObject()} method. Validation is * performed by the {@code validateObject()} method of the factory * associated with the pool. If the object fails to validate, then * {@code borrowObject()} will fail. * * @param testOnCreate {@code true} if newly created objects should be * validated before being returned from the * {@code borrowObject()} method * * @see #getTestOnCreate * * @since 2.2 */ public final void setTestOnCreate(final boolean testOnCreate) { this.testOnCreate = testOnCreate; } /** * Sets whether objects borrowed from the pool will be validated when * they are returned to the pool via the {@code returnObject()} method. * Validation is performed by the {@code validateObject()} method of * the factory associated with the pool. Returning objects that fail validation * are destroyed rather then being returned the pool. * * @param testOnReturn {@code true} if objects are validated on * return to the pool via the * {@code returnObject()} method * * @see #getTestOnReturn */ public final void setTestOnReturn(final boolean testOnReturn) { this.testOnReturn = testOnReturn; } /** * Sets whether objects sitting idle in the pool will be validated by the * idle object evictor (if any - see * {@link #setDurationBetweenEvictionRuns(Duration)}). Validation is performed * by the {@code validateObject()} method of the factory associated * with the pool. If the object fails to validate, it will be removed from * the pool and destroyed. Note that setting this property has no effect * unless the idle object evictor is enabled by setting * {@code timeBetweenEvictionRunsMillis} to a positive value. * * @param testWhileIdle * {@code true} so objects will be validated by the evictor * * @see #getTestWhileIdle * @see #setDurationBetweenEvictionRuns(Duration) */ public final void setTestWhileIdle(final boolean testWhileIdle) { this.testWhileIdle = testWhileIdle; } /** * <p>Starts the evictor with the given delay. If there is an evictor * running when this method is called, it is stopped and replaced with a * new evictor with the specified delay.</p> * * <p>This method needs to be final, since it is called from a constructor. * See POOL-195.</p> * * @param delay duration before start and between eviction runs. */ final void startEvictor(final Duration delay) { synchronized (evictionLock) { final boolean isPositiverDelay = PoolImplUtils.isPositive(delay); if (evictor == null) { // Starting evictor for the first time or after a cancel if (isPositiverDelay) { // Starting new evictor evictor = new Evictor(); EvictionTimer.schedule(evictor, delay, delay); } } else if (isPositiverDelay) { // Stop or restart of existing evictor: Restart synchronized (EvictionTimer.class) { // Ensure no cancel can happen between cancel / schedule calls EvictionTimer.cancel(evictor, evictorShutdownTimeoutDuration, true); evictor = null; evictionIterator = null; evictor = new Evictor(); EvictionTimer.schedule(evictor, delay, delay); } } else { // Stopping evictor EvictionTimer.cancel(evictor, evictorShutdownTimeoutDuration, false); } } } /** * Stops the evictor. */ void stopEvictor() { startEvictor(Duration.ofMillis(-1L)); } /** * Swallows an exception and notifies the configured listener for swallowed * exceptions queue. * * @param swallowException exception to be swallowed */ final void swallowException(final Exception swallowException) { final SwallowedExceptionListener listener = getSwallowedExceptionListener(); if (listener == null) { return; } try { listener.onSwallowException(swallowException); } catch (final VirtualMachineError e) { throw e; } catch (final Throwable ignored) { // Ignore. Enjoy the irony. } } @Override protected void toStringAppendFields(final StringBuilder builder) { builder.append("maxTotal="); builder.append(maxTotal); builder.append(", blockWhenExhausted="); builder.append(blockWhenExhausted); builder.append(", maxWaitDuration="); builder.append(maxWaitDuration); builder.append(", lifo="); builder.append(lifo); builder.append(", fairness="); builder.append(fairness); builder.append(", testOnCreate="); builder.append(testOnCreate); builder.append(", testOnBorrow="); builder.append(testOnBorrow); builder.append(", testOnReturn="); builder.append(testOnReturn); builder.append(", testWhileIdle="); builder.append(testWhileIdle); builder.append(", durationBetweenEvictionRuns="); builder.append(durationBetweenEvictionRuns); builder.append(", numTestsPerEvictionRun="); builder.append(numTestsPerEvictionRun); builder.append(", minEvictableIdleTimeDuration="); builder.append(minEvictableIdleDuration); builder.append(", softMinEvictableIdleTimeDuration="); builder.append(softMinEvictableIdleDuration); builder.append(", evictionPolicy="); builder.append(evictionPolicy); builder.append(", closeLock="); builder.append(closeLock); builder.append(", closed="); builder.append(closed); builder.append(", evictionLock="); builder.append(evictionLock); builder.append(", evictor="); builder.append(evictor); builder.append(", evictionIterator="); builder.append(evictionIterator); builder.append(", factoryClassLoader="); builder.append(factoryClassLoader); builder.append(", oname="); builder.append(objectName); builder.append(", creationStackTrace="); builder.append(creationStackTrace); builder.append(", borrowedCount="); builder.append(borrowedCount); builder.append(", returnedCount="); builder.append(returnedCount); builder.append(", createdCount="); builder.append(createdCount); builder.append(", destroyedCount="); builder.append(destroyedCount); builder.append(", destroyedByEvictorCount="); builder.append(destroyedByEvictorCount); builder.append(", destroyedByBorrowValidationCount="); builder.append(destroyedByBorrowValidationCount); builder.append(", activeTimes="); builder.append(activeTimes); builder.append(", idleTimes="); builder.append(idleTimes); builder.append(", waitTimes="); builder.append(waitTimes); builder.append(", maxBorrowWaitDuration="); builder.append(maxBorrowWaitDuration); builder.append(", swallowedExceptionListener="); builder.append(swallowedExceptionListener); } /** * Updates statistics after an object is borrowed from the pool. * * @param p object borrowed from the pool * @param waitDuration that the borrowing thread had to wait */ final void updateStatsBorrow(final PooledObject<T> p, final Duration waitDuration) { borrowedCount.incrementAndGet(); idleTimes.add(p.getIdleDuration()); waitTimes.add(waitDuration); // lock-free optimistic-locking maximum Duration currentMaxDuration; do { currentMaxDuration = maxBorrowWaitDuration.get(); // if (currentMaxDuration >= waitDuration) { // break; // } if (currentMaxDuration.compareTo(waitDuration) >= 0) { break; } } while (!maxBorrowWaitDuration.compareAndSet(currentMaxDuration, waitDuration)); } /** * Updates statistics after an object is returned to the pool. * * @param activeTime the amount of time (in milliseconds) that the returning * object was checked out */ final void updateStatsReturn(final Duration activeTime) { returnedCount.incrementAndGet(); activeTimes.add(activeTime); } }
5,271
0
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3/impl/CallStack.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.impl; import java.io.PrintWriter; import org.apache.commons.pool3.PooledObject; import org.apache.commons.pool3.UsageTracking; /** * Strategy for obtaining and printing the current call stack. This is primarily useful for * {@linkplain UsageTracking usage tracking} so that different JVMs and configurations can use more efficient strategies * for obtaining the current call stack depending on metadata needs. * * @see CallStackUtils * @since 2.4.3 */ public interface CallStack { /** * Clears the current stack trace snapshot. Subsequent calls to {@link #printStackTrace(PrintWriter)} will be * no-ops until another call to {@link #fillInStackTrace()}. */ void clear(); /** * Takes a snapshot of the current call stack. Subsequent calls to {@link #printStackTrace(PrintWriter)} will print * out that stack trace until it is {@linkplain #clear() cleared}. */ void fillInStackTrace(); /** * Prints the current stack trace if available to a PrintWriter. The format is undefined and is primarily useful * for debugging issues with {@link PooledObject} usage in user code. * * @param writer a PrintWriter to write the current stack trace to if available * @return true if a stack trace was available to print or false if nothing was printed */ boolean printStackTrace(final PrintWriter writer); }
5,272
0
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3/impl/GenericObjectPoolConfig.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.impl; /** * A simple structure encapsulating the configuration for a * {@link GenericObjectPool}. * * <p> * This class is not thread-safe; it is only intended to be used to provide * attributes used when creating a pool. * </p> * * @param <T> Type of element pooled. * @since 2.0 */ public class GenericObjectPoolConfig<T> extends BaseObjectPoolConfig<T> { /** * The default value for the {@code maxTotal} configuration attribute. * @see GenericObjectPool#getMaxTotal() */ public static final int DEFAULT_MAX_TOTAL = 8; /** * The default value for the {@code maxIdle} configuration attribute. * @see GenericObjectPool#getMaxIdle() */ public static final int DEFAULT_MAX_IDLE = 8; /** * The default value for the {@code minIdle} configuration attribute. * @see GenericObjectPool#getMinIdle() */ public static final int DEFAULT_MIN_IDLE = 0; private int maxTotal = DEFAULT_MAX_TOTAL; private int maxIdle = DEFAULT_MAX_IDLE; private int minIdle = DEFAULT_MIN_IDLE; @SuppressWarnings("unchecked") @Override public GenericObjectPoolConfig<T> clone() { try { return (GenericObjectPoolConfig<T>) super.clone(); } catch (final CloneNotSupportedException e) { throw new AssertionError(); // Can't happen } } /** * Gets the value for the {@code maxIdle} configuration attribute * for pools created with this configuration instance. * * @return The current setting of {@code maxIdle} for this * configuration instance * * @see GenericObjectPool#getMaxIdle() */ public int getMaxIdle() { return maxIdle; } /** * Gets the value for the {@code maxTotal} configuration attribute * for pools created with this configuration instance. * * @return The current setting of {@code maxTotal} for this * configuration instance * * @see GenericObjectPool#getMaxTotal() */ public int getMaxTotal() { return maxTotal; } /** * Gets the value for the {@code minIdle} configuration attribute * for pools created with this configuration instance. * * @return The current setting of {@code minIdle} for this * configuration instance * * @see GenericObjectPool#getMinIdle() */ public int getMinIdle() { return minIdle; } /** * Sets the value for the {@code maxIdle} configuration attribute for * pools created with this configuration instance. * * @param maxIdle The new setting of {@code maxIdle} * for this configuration instance * * @see GenericObjectPool#setMaxIdle(int) */ public void setMaxIdle(final int maxIdle) { this.maxIdle = maxIdle; } /** * Sets the value for the {@code maxTotal} configuration attribute for * pools created with this configuration instance. * * @param maxTotal The new setting of {@code maxTotal} * for this configuration instance * * @see GenericObjectPool#setMaxTotal(int) */ public void setMaxTotal(final int maxTotal) { this.maxTotal = maxTotal; } /** * Sets the value for the {@code minIdle} configuration attribute for * pools created with this configuration instance. * * @param minIdle The new setting of {@code minIdle} * for this configuration instance * * @see GenericObjectPool#setMinIdle(int) */ public void setMinIdle(final int minIdle) { this.minIdle = minIdle; } @Override protected void toStringAppendFields(final StringBuilder builder) { super.toStringAppendFields(builder); builder.append(", maxTotal="); builder.append(maxTotal); builder.append(", maxIdle="); builder.append(maxIdle); builder.append(", minIdle="); builder.append(minIdle); } }
5,273
0
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3/impl/DefaultEvictionPolicy.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.impl; import org.apache.commons.pool3.PooledObject; /** * Provides the default implementation of {@link EvictionPolicy} used by the pools. * <p> * Objects will be evicted if the following conditions are met: * </p> * <ul> * <li>The object has been idle longer than * {@link GenericObjectPool#getMinEvictableIdleDuration()} / * {@link GenericKeyedObjectPool#getMinEvictableIdleDuration()}</li> * <li>There are more than {@link GenericObjectPool#getMinIdle()} / * {@link GenericKeyedObjectPoolConfig#getMinIdlePerKey()} idle objects in * the pool and the object has been idle for longer than * {@link GenericObjectPool#getSoftMinEvictableIdleDuration()} / * {@link GenericKeyedObjectPool#getSoftMinEvictableIdleDuration()} * </ul> * <p> * This class is immutable and thread-safe. * </p> * * @param <T> the type of objects in the pool. * * @since 2.0 */ public class DefaultEvictionPolicy<T> implements EvictionPolicy<T> { @Override public boolean evict(final EvictionConfig config, final PooledObject<T> underTest, final int idleCount) { // @formatter:off return config.getIdleSoftEvictDuration().compareTo(underTest.getIdleDuration()) < 0 && config.getMinIdle() < idleCount || config.getIdleEvictDuration().compareTo(underTest.getIdleDuration()) < 0; // @formatter:on } }
5,274
0
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3/impl/GenericObjectPoolMXBean.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.impl; import java.util.Set; /** * Defines the methods that will be made available via JMX. * <h2>Note</h2> * <p> * This interface exists only to define those attributes and methods that will be made available via JMX. It must not be implemented by clients as it is subject * to change between major, minor and patch version releases of commons pool. Clients that implement this interface may not, therefore, be able to upgrade to a * new minor or patch release without requiring code changes. * </p> * * @since 2.0 */ public interface GenericObjectPoolMXBean { /** * See {@link GenericObjectPool#getBlockWhenExhausted()}. * * @return See {@link GenericObjectPool#getBlockWhenExhausted()}. */ boolean getBlockWhenExhausted(); /** * See {@link GenericObjectPool#getBorrowedCount()}. * * @return See {@link GenericObjectPool#getBorrowedCount()}. */ long getBorrowedCount(); /** * See {@link GenericObjectPool#getCreatedCount()}. * * @return See {@link GenericObjectPool#getCreatedCount()}. */ long getCreatedCount(); /** * See {@link GenericObjectPool#getCreationStackTrace()}. * * @return See {@link GenericObjectPool#getCreationStackTrace()}. */ String getCreationStackTrace(); /** * See {@link GenericObjectPool#getDestroyedByBorrowValidationCount()}. * * @return See {@link GenericObjectPool#getDestroyedByBorrowValidationCount()}. */ long getDestroyedByBorrowValidationCount(); /** * See {@link GenericObjectPool#getDestroyedByEvictorCount()}. * * @return See {@link GenericObjectPool#getDestroyedByEvictorCount()}. */ long getDestroyedByEvictorCount(); /** * See {@link GenericObjectPool#getDestroyedCount()}. * * @return See {@link GenericObjectPool#getDestroyedCount()}. */ long getDestroyedCount(); /** * See {@link GenericObjectPool#getFactoryType()}. * * @return See {@link GenericObjectPool#getFactoryType()}. */ String getFactoryType(); /** * See {@link GenericObjectPool#getLifo()}. * * @return See {@link GenericObjectPool#getLifo()}. */ boolean getFairness(); /** * See {@link GenericObjectPool#getFairness()}. * * @return See {@link GenericObjectPool#getFairness()}. */ boolean getLifo(); /** * See {@link GenericObjectPool#getLogAbandoned()}. * * @return See {@link GenericObjectPool#getLogAbandoned()}. */ boolean getLogAbandoned(); /** * See {@link GenericObjectPool#getMaxBorrowWaitTimeMillis()}. * * @return See {@link GenericObjectPool#getMaxBorrowWaitTimeMillis()}. */ long getMaxBorrowWaitTimeMillis(); /** * See {@link GenericObjectPool#getMaxIdle()}. * * @return See {@link GenericObjectPool#getMaxIdle()}. */ int getMaxIdle(); /** * See {@link GenericObjectPool#getMaxTotal()}. * * @return See {@link GenericObjectPool#getMaxTotal()}. */ int getMaxTotal(); /** * See {@link GenericObjectPool#getMaxWaitDuration()}. * * @return See {@link GenericObjectPool#getMaxWaitDuration()}. */ long getMaxWaitMillis(); /** * See {@link GenericObjectPool#getMeanActiveTimeMillis()}. * * @return See {@link GenericObjectPool#getMeanActiveTimeMillis()}. */ long getMeanActiveTimeMillis(); /** * See {@link GenericObjectPool#getMeanBorrowWaitTimeMillis()}. * * @return See {@link GenericObjectPool#getMeanBorrowWaitTimeMillis()}. */ long getMeanBorrowWaitTimeMillis(); /** * See {@link GenericObjectPool#getMeanIdleTimeMillis()}. * * @return See {@link GenericObjectPool#getMeanIdleTimeMillis()}. */ long getMeanIdleTimeMillis(); /** * See {@link GenericObjectPool#getMinEvictableIdleDuration()}. * * @return See {@link GenericObjectPool#getMinEvictableIdleDuration()}. */ long getMinEvictableIdleTimeMillis(); /** * See {@link GenericObjectPool#getMinIdle()}. * * @return See {@link GenericObjectPool#getMinIdle()}. */ int getMinIdle(); /** * See {@link GenericObjectPool#getNumActive()}. * * @return See {@link GenericObjectPool#getNumActive()}. */ int getNumActive(); /** * See {@link GenericObjectPool#getNumIdle()}. * * @return See {@link GenericObjectPool#getNumIdle()}. */ int getNumIdle(); /** * See {@link GenericObjectPool#getNumTestsPerEvictionRun()}. * * @return See {@link GenericObjectPool#getNumTestsPerEvictionRun()}. */ int getNumTestsPerEvictionRun(); /** * See {@link GenericObjectPool#getNumWaiters()}. * * @return See {@link GenericObjectPool#getNumWaiters()}. */ int getNumWaiters(); /** * See {@link GenericObjectPool#getRemoveAbandonedOnBorrow()}. * * @return See {@link GenericObjectPool#getRemoveAbandonedOnBorrow()}. */ boolean getRemoveAbandonedOnBorrow(); /** * See {@link GenericObjectPool#getRemoveAbandonedOnMaintenance()}. * * @return See {@link GenericObjectPool#getRemoveAbandonedOnMaintenance()}. */ boolean getRemoveAbandonedOnMaintenance(); /** * See {@link GenericObjectPool#getRemoveAbandonedTimeoutDuration()}. * * @return See {@link GenericObjectPool#getRemoveAbandonedTimeoutDuration()}. */ int getRemoveAbandonedTimeout(); /** * See {@link GenericObjectPool#getReturnedCount()}. * * @return See {@link GenericObjectPool#getReturnedCount()}. */ long getReturnedCount(); /** * See {@link GenericObjectPool#getTestOnBorrow()}. * * @return See {@link GenericObjectPool#getTestOnBorrow()}. */ boolean getTestOnBorrow(); /** * See {@link GenericObjectPool#getTestOnCreate()}. * * @return See {@link GenericObjectPool#getTestOnCreate()}. * @since 2.2 */ boolean getTestOnCreate(); /** * See {@link GenericObjectPool#getTestOnReturn()}. * * @return See {@link GenericObjectPool#getTestOnReturn()}. */ boolean getTestOnReturn(); /** * See {@link GenericObjectPool#getTestWhileIdle()}. * * @return See {@link GenericObjectPool#getTestWhileIdle()}. */ boolean getTestWhileIdle(); /** * See {@link GenericObjectPool#getDurationBetweenEvictionRuns()}. * * @return See {@link GenericObjectPool#getDurationBetweenEvictionRuns()}. */ long getTimeBetweenEvictionRunsMillis(); /** * See {@link GenericObjectPool#isAbandonedConfig()}. * * @return See {@link GenericObjectPool#isAbandonedConfig()}. */ boolean isAbandonedConfig(); /** * See {@link GenericObjectPool#isClosed()}. * * @return See {@link GenericObjectPool#isClosed()}. */ boolean isClosed(); /** * See {@link GenericObjectPool#listAllObjects()}. * * @return See {@link GenericObjectPool#listAllObjects()}. */ Set<DefaultPooledObjectInfo> listAllObjects(); }
5,275
0
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3/impl/GenericKeyedObjectPool.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.impl; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; import java.util.Deque; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.NoSuchElementException; import java.util.Objects; import java.util.TreeMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.stream.Collectors; import org.apache.commons.pool3.DestroyMode; import org.apache.commons.pool3.KeyedObjectPool; import org.apache.commons.pool3.KeyedPooledObjectFactory; import org.apache.commons.pool3.PoolUtils; import org.apache.commons.pool3.PooledObject; import org.apache.commons.pool3.PooledObjectState; import org.apache.commons.pool3.SwallowedExceptionListener; import org.apache.commons.pool3.UsageTracking; /** * A configurable {@code KeyedObjectPool} implementation. * <p> * When coupled with the appropriate {@link KeyedPooledObjectFactory}, * {@code GenericKeyedObjectPool} provides robust pooling functionality for * keyed objects. A {@code GenericKeyedObjectPool} can be viewed as a map * of sub-pools, keyed on the (unique) key values provided to the * {@link #preparePool preparePool}, {@link #addObject addObject} or * {@link #borrowObject borrowObject} methods. Each time a new key value is * provided to one of these methods, a sub-new pool is created under the given * key to be managed by the containing {@code GenericKeyedObjectPool.} * </p> * <p> * Note that the current implementation uses a ConcurrentHashMap which uses * equals() to compare keys. * This means that distinct instance keys must be distinguishable using equals. * </p> * <p> * Optionally, one may configure the pool to examine and possibly evict objects * as they sit idle in the pool and to ensure that a minimum number of idle * objects is maintained for each key. This is performed by an "idle object * eviction" thread, which runs asynchronously. Caution should be used when * configuring this optional feature. Eviction runs contend with client threads * for access to objects in the pool, so if they run too frequently performance * issues may result. * </p> * <p> * Implementation note: To prevent possible deadlocks, care has been taken to * ensure that no call to a factory method will occur within a synchronization * block. See POOL-125 and DBCP-44 for more information. * </p> * <p> * This class is intended to be thread-safe. * </p> * * @see GenericObjectPool * * @param <K> The type of keys maintained by this pool. * @param <T> Type of element pooled in this pool. * @param <E> Type of exception thrown in this pool. * * @since 2.0 */ public class GenericKeyedObjectPool<K, T, E extends Exception> extends BaseGenericObjectPool<T, E> implements KeyedObjectPool<K, T, E>, GenericKeyedObjectPoolMXBean<K>, UsageTracking<T> { /** * Maintains information on the per key queue for a given key. * * @param <S> type of objects in the pool */ private static final class ObjectDeque<S> { private final LinkedBlockingDeque<PooledObject<S>> idleObjects; /* * Number of instances created - number destroyed. * Invariant: createCount <= maxTotalPerKey */ private final AtomicInteger createCount = new AtomicInteger(0); private long makeObjectCount; private final Object makeObjectCountLock = new Object(); /* * The map is keyed on pooled instances, wrapped to ensure that * they work properly as keys. */ private final Map<IdentityWrapper<S>, PooledObject<S>> allObjects = new ConcurrentHashMap<>(); /* * Number of threads with registered interest in this key. * register(K) increments this counter and deRegister(K) decrements it. * Invariant: empty keyed pool will not be dropped unless numInterested * is 0. */ private final AtomicLong numInterested = new AtomicLong(); /** * Constructs a new ObjectDeque with the given fairness policy. * @param fairness true means client threads waiting to borrow / return instances * will be served as if waiting in a FIFO queue. */ public ObjectDeque(final boolean fairness) { idleObjects = new LinkedBlockingDeque<>(fairness); } /** * Gets all the objects for the current key. * * @return All the objects */ public Map<IdentityWrapper<S>, PooledObject<S>> getAllObjects() { return allObjects; } /** * Gets the number of instances created - number destroyed. * Should always be less than or equal to maxTotalPerKey. * * @return The net instance addition count for this deque */ public AtomicInteger getCreateCount() { return createCount; } /** * Gets the idle objects for the current key. * * @return The idle objects */ public LinkedBlockingDeque<PooledObject<S>> getIdleObjects() { return idleObjects; } /** * Gets the number of threads with an interest registered in this key. * * @return The number of threads with a registered interest in this key */ public AtomicLong getNumInterested() { return numInterested; } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("ObjectDeque [idleObjects="); builder.append(idleObjects); builder.append(", createCount="); builder.append(createCount); builder.append(", allObjects="); builder.append(allObjects); builder.append(", numInterested="); builder.append(numInterested); builder.append("]"); return builder.toString(); } } private static final Integer ZERO = Integer.valueOf(0); // JMX specific attributes private static final String ONAME_BASE = "org.apache.commons.pool3:type=GenericKeyedObjectPool,name="; private volatile int maxIdlePerKey = GenericKeyedObjectPoolConfig.DEFAULT_MAX_IDLE_PER_KEY; private volatile int minIdlePerKey = GenericKeyedObjectPoolConfig.DEFAULT_MIN_IDLE_PER_KEY; private volatile int maxTotalPerKey = GenericKeyedObjectPoolConfig.DEFAULT_MAX_TOTAL_PER_KEY; private final KeyedPooledObjectFactory<K, T, E> factory; private final boolean fairness; /* * My hash of sub-pools (ObjectQueue). The list of keys <b>must</b> be kept * in step with {@link #poolKeyList} using {@link #keyLock} to ensure any * changes to the list of current keys is made in a thread-safe manner. */ private final Map<K, ObjectDeque<T>> poolMap = new ConcurrentHashMap<>(); // @GuardedBy("keyLock") for write access (and some read access) /* * List of pool keys - used to control eviction order. The list of keys * <b>must</b> be kept in step with {@link #poolMap} using {@link #keyLock} * to ensure any changes to the list of current keys is made in a * thread-safe manner. */ private final ArrayList<K> poolKeyList = new ArrayList<>(); // @GuardedBy("keyLock") private final ReadWriteLock keyLock = new ReentrantReadWriteLock(true); /* * The combined count of the currently active objects for all keys and those * in the process of being created. Under load, it may exceed * {@link #maxTotal} but there will never be more than {@link #maxTotal} * created at any one time. */ private final AtomicInteger numTotal = new AtomicInteger(0); private Iterator<K> evictionKeyIterator; // @GuardedBy("evictionLock") private K evictionKey; // @GuardedBy("evictionLock") /** * Constructs a new {@code GenericKeyedObjectPool} using defaults from * {@link GenericKeyedObjectPoolConfig}. * @param factory the factory to be used to create entries */ public GenericKeyedObjectPool(final KeyedPooledObjectFactory<K, T, E> factory) { this(factory, new GenericKeyedObjectPoolConfig<>()); } /** * Constructs a new {@code GenericKeyedObjectPool} using a specific * configuration. * * @param factory the factory to be used to create entries * @param config The configuration to use for this pool instance. The * configuration is used by value. Subsequent changes to * the configuration object will not be reflected in the * pool. */ public GenericKeyedObjectPool(final KeyedPooledObjectFactory<K, T, E> factory, final GenericKeyedObjectPoolConfig<T> config) { super(config, ONAME_BASE, config.getJmxNamePrefix()); if (factory == null) { jmxUnregister(); // tidy up throw new IllegalArgumentException("Factory may not be null"); } this.factory = factory; this.fairness = config.getFairness(); setConfig(config); } /** * Creates a new {@code GenericKeyedObjectPool} that tracks and destroys * objects that are checked out, but never returned to the pool. * * @param factory The object factory to be used to create object instances * used by this pool * @param config The base pool configuration to use for this pool instance. * The configuration is used by value. Subsequent changes to * the configuration object will not be reflected in the * pool. * @param abandonedConfig Configuration for abandoned object identification * and removal. The configuration is used by value. * @since 2.10.0 */ public GenericKeyedObjectPool(final KeyedPooledObjectFactory<K, T, E> factory, final GenericKeyedObjectPoolConfig<T> config, final AbandonedConfig abandonedConfig) { this(factory, config); setAbandonedConfig(abandonedConfig); } /** * Add an object to the set of idle objects for a given key. * If the object is null this is a no-op. * * @param key The key to associate with the idle object * @param p The wrapped object to add. * * @throws E If the associated factory fails to passivate the object */ private void addIdleObject(final K key, final PooledObject<T> p) throws E { if (!PooledObject.isNull(p)) { factory.passivateObject(key, p); final LinkedBlockingDeque<PooledObject<T>> idleObjects = poolMap.get(key).getIdleObjects(); if (getLifo()) { idleObjects.addFirst(p); } else { idleObjects.addLast(p); } } } /** * Create an object using the {@link KeyedPooledObjectFactory#makeObject * factory}, passivate it, and then place it in the idle object pool. * {@code addObject} is useful for "pre-loading" a pool with idle * objects. * <p> * If there is no capacity available to add to the pool under the given key, * this is a no-op (no exception, no impact to the pool). * </p> * <p> * If the factory returns null when creating an instance, * a {@code NullPointerException} is thrown. * </p> * * @param key the key a new instance should be added to * * @throws E when {@link KeyedPooledObjectFactory#makeObject} * fails. */ @Override public void addObject(final K key) throws E { assertOpen(); register(key); try { addIdleObject(key, create(key)); } finally { deregister(key); } } /** * Equivalent to <code>{@link #borrowObject(Object, long) borrowObject}(key, * {@link #getMaxWaitDuration()})</code>. * * {@inheritDoc} */ @Override public T borrowObject(final K key) throws E { return borrowObject(key, getMaxWaitDuration().toMillis()); } /** * Borrows an object from the sub-pool associated with the given key using * the specified waiting time which only applies if * {@link #getBlockWhenExhausted()} is true. * <p> * If there is one or more idle instances available in the sub-pool * associated with the given key, then an idle instance will be selected * based on the value of {@link #getLifo()}, activated and returned. If * activation fails, or {@link #getTestOnBorrow() testOnBorrow} is set to * {@code true} and validation fails, the instance is destroyed and the * next available instance is examined. This continues until either a valid * instance is returned or there are no more idle instances available. * </p> * <p> * If there are no idle instances available in the sub-pool associated with * the given key, behavior depends on the {@link #getMaxTotalPerKey() * maxTotalPerKey}, {@link #getMaxTotal() maxTotal}, and (if applicable) * {@link #getBlockWhenExhausted()} and the value passed in to the * {@code borrowMaxWaitMillis} parameter. If the number of instances checked * out from the sub-pool under the given key is less than * {@code maxTotalPerKey} and the total number of instances in * circulation (under all keys) is less than {@code maxTotal}, a new * instance is created, activated and (if applicable) validated and returned * to the caller. If validation fails, a {@code NoSuchElementException} * will be thrown. If the factory returns null when creating an instance, * a {@code NullPointerException} is thrown. * </p> * <p> * If the associated sub-pool is exhausted (no available idle instances and * no capacity to create new ones), this method will either block * ({@link #getBlockWhenExhausted()} is true) or throw a * {@code NoSuchElementException} * ({@link #getBlockWhenExhausted()} is false). * The length of time that this method will block when * {@link #getBlockWhenExhausted()} is true is determined by the value * passed in to the {@code borrowMaxWait} parameter. * </p> * <p> * When {@code maxTotal} is set to a positive value and this method is * invoked when at the limit with no idle instances available under the requested * key, an attempt is made to create room by clearing the oldest 15% of the * elements from the keyed sub-pools. * </p> * <p> * When the pool is exhausted, multiple calling threads may be * simultaneously blocked waiting for instances to become available. A * "fairness" algorithm has been implemented to ensure that threads receive * available instances in request arrival order. * </p> * * @param key pool key * @param borrowMaxWaitMillis The time to wait in milliseconds for an object * to become available * * @return object instance from the keyed pool * * @throws NoSuchElementException if a keyed object instance cannot be * returned because the pool is exhausted. * * @throws E if a keyed object instance cannot be returned due to an * error */ public T borrowObject(final K key, final long borrowMaxWaitMillis) throws E { assertOpen(); final AbandonedConfig ac = this.abandonedConfig; if (ac != null && ac.getRemoveAbandonedOnBorrow() && getNumIdle() < 2 && getNumActive() > getMaxTotal() - 3) { removeAbandoned(ac); } PooledObject<T> p = null; // Get local copy of current config so it is consistent for entire // method execution final boolean blockWhenExhausted = getBlockWhenExhausted(); boolean create; final Instant waitTime = Instant.now(); final ObjectDeque<T> objectDeque = register(key); try { while (p == null) { create = false; p = objectDeque.getIdleObjects().pollFirst(); if (p == null) { p = create(key); if (!PooledObject.isNull(p)) { create = true; } } if (blockWhenExhausted) { if (PooledObject.isNull(p)) { try { p = borrowMaxWaitMillis < 0 ? objectDeque.getIdleObjects().takeFirst() : objectDeque.getIdleObjects().pollFirst(borrowMaxWaitMillis, TimeUnit.MILLISECONDS); } catch (final InterruptedException e) { throw cast(e); } } if (PooledObject.isNull(p)) { throw new NoSuchElementException(appendStats( "Timeout waiting for idle object, borrowMaxWaitMillis=" + borrowMaxWaitMillis)); } } else if (PooledObject.isNull(p)) { throw new NoSuchElementException(appendStats("Pool exhausted")); } if (!p.allocate()) { p = null; } if (!PooledObject.isNull(p)) { try { factory.activateObject(key, p); } catch (final Exception e) { try { destroy(key, p, true, DestroyMode.NORMAL); } catch (final Exception ignored) { // ignored - activation failure is more important } p = null; if (create) { final NoSuchElementException nsee = new NoSuchElementException(appendStats("Unable to activate object")); nsee.initCause(e); throw nsee; } } if (!PooledObject.isNull(p) && getTestOnBorrow()) { boolean validate = false; Throwable validationThrowable = null; try { validate = factory.validateObject(key, p); } catch (final Throwable t) { PoolUtils.checkRethrow(t); validationThrowable = t; } if (!validate) { try { destroy(key, p, true, DestroyMode.NORMAL); destroyedByBorrowValidationCount.incrementAndGet(); } catch (final Exception ignored) { // ignored - validation failure is more important } p = null; if (create) { final NoSuchElementException nsee = new NoSuchElementException( appendStats("Unable to validate object")); nsee.initCause(validationThrowable); throw nsee; } } } } } } finally { deregister(key); } updateStatsBorrow(p, Duration.between(waitTime, Instant.now())); return p.getObject(); } /** * Calculate the number of objects that need to be created to attempt to * maintain the minimum number of idle objects while not exceeded the limits * on the maximum number of objects either per key or totally. * * @param objectDeque The set of objects to check * * @return The number of new objects to create */ private int calculateDeficit(final ObjectDeque<T> objectDeque) { if (objectDeque == null) { return getMinIdlePerKey(); } // Used more than once so keep a local copy so the value is consistent final int maxTotal = getMaxTotal(); final int maxTotalPerKeySave = getMaxTotalPerKey(); // Calculate no of objects needed to be created, in order to have // the number of pooled objects < maxTotalPerKey(); int objectDefecit = getMinIdlePerKey() - objectDeque.getIdleObjects().size(); if (maxTotalPerKeySave > 0) { final int growLimit = Math.max(0, maxTotalPerKeySave - objectDeque.getIdleObjects().size()); objectDefecit = Math.min(objectDefecit, growLimit); } // Take the maxTotal limit into account if (maxTotal > 0) { final int growLimit = Math.max(0, maxTotal - getNumActive() - getNumIdle()); objectDefecit = Math.min(objectDefecit, growLimit); } return objectDefecit; } /** * Clears any objects sitting idle in the pool by removing them from the * idle instance sub-pools and then invoking the configured * PoolableObjectFactory's * {@link KeyedPooledObjectFactory#destroyObject(Object, PooledObject)} * method on each idle instance. * <p> * Implementation notes: * <ul> * <li>This method does not destroy or effect in any way instances that are * checked out when it is invoked.</li> * <li>Invoking this method does not prevent objects being returned to the * idle instance pool, even during its execution. Additional instances may * be returned while removed items are being destroyed.</li> * <li>Exceptions encountered destroying idle instances are swallowed * but notified via a {@link SwallowedExceptionListener}.</li> * </ul> */ @Override public void clear() { poolMap.keySet().forEach(key -> clear(key, false)); } /** * 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}. * <p> * If there are clients waiting to borrow objects, this method will * attempt to reuse the capacity freed by this operation, adding * instances to the most loaded keyed pools. To avoid triggering * possible object creation, use {@link #clear(Object, boolean)}. * * @param key the key to clear */ @Override public void clear(final K key) { clear(key, true); } /** * 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}. * <p> * If reuseCapacity is true and there are clients waiting to * borrow objects, this method will attempt to reuse the capacity freed * by this operation, adding instances to the most loaded keyed pools. * </p> * * @param key the key to clear * @param reuseCapacity whether or not to reuse freed capacity * @since 2.12.0 */ public void clear(final K key, final boolean reuseCapacity) { // Return immediately if there is no pool under this key. if (!poolMap.containsKey(key)) { return; } final ObjectDeque<T> objectDeque = register(key); int freedCapacity = 0; try { final LinkedBlockingDeque<PooledObject<T>> idleObjects = objectDeque.getIdleObjects(); PooledObject<T> p = idleObjects.poll(); while (p != null) { try { if (destroy(key, p, true, DestroyMode.NORMAL)) { freedCapacity++; } } catch (final Exception e) { swallowException(e); } p = idleObjects.poll(); } } finally { deregister(key); } if (reuseCapacity) { reuseCapacity(freedCapacity); } } /** * Clears oldest 15% of objects in pool. The method sorts the objects into * a TreeMap and then iterates the first 15% for removal. */ public void clearOldest() { // build sorted map of idle objects final TreeMap<PooledObject<T>, K> map = new TreeMap<>(); poolMap.forEach((key, value) -> { // Each item into the map using the PooledObject object as the // key. It then gets sorted based on the idle time value.getIdleObjects().forEach(p -> map.put(p, key)); }); // Now iterate created map and kill the first 15% plus one to account // for zero int itemsToRemove = (int) (map.size() * 0.15) + 1; final Iterator<Entry<PooledObject<T>, K>> iter = map.entrySet().iterator(); while (iter.hasNext() && itemsToRemove > 0) { final Entry<PooledObject<T>, K> entry = iter.next(); // kind of backwards on naming. In the map, each key is the // PooledObject because it has the ordering with the timestamp // value. Each value that the key references is the key of the // list it belongs to. final K key = entry.getValue(); final PooledObject<T> p = entry.getKey(); // Assume the destruction succeeds boolean destroyed = true; try { destroyed = destroy(key, p, false, DestroyMode.NORMAL); } catch (final Exception e) { swallowException(e); } if (destroyed) { itemsToRemove--; } } } /** * Closes the keyed object pool. Once the pool is closed, * {@link #borrowObject(Object)} will fail with IllegalStateException, but * {@link #returnObject(Object, Object)} and * {@link #invalidateObject(Object, Object)} will continue to work, with * returned objects destroyed on return. * <p> * Destroys idle instances in the pool by invoking {@link #clear()}. * </p> */ @Override public void close() { if (isClosed()) { return; } synchronized (closeLock) { if (isClosed()) { return; } // Stop the evictor before the pool is closed since evict() calls // assertOpen() stopEvictor(); closed = true; // This clear removes any idle objects clear(); jmxUnregister(); // Release any threads that were waiting for an object poolMap.values().forEach(e -> e.getIdleObjects().interuptTakeWaiters()); // This clear cleans up the keys now any waiting threads have been // interrupted clear(); } } /** * Creates a new pooled object or null. * * @param key Key associated with new pooled object. * * @return The new, wrapped pooled object. May return null. * * @throws E If the objection creation fails. */ private PooledObject<T> create(final K key) throws E { int maxTotalPerKeySave = getMaxTotalPerKey(); // Per key if (maxTotalPerKeySave < 0) { maxTotalPerKeySave = Integer.MAX_VALUE; } final int maxTotal = getMaxTotal(); // All keys final ObjectDeque<T> objectDeque = poolMap.get(key); // Check against the overall limit boolean loop = true; while (loop) { final int newNumTotal = numTotal.incrementAndGet(); if (maxTotal > -1 && newNumTotal > maxTotal) { numTotal.decrementAndGet(); if (getNumIdle() == 0) { return null; } clearOldest(); } else { loop = false; } } // Flag that indicates if create should: // - TRUE: call the factory to create an object // - FALSE: return null // - null: loop and re-test the condition that determines whether to // call the factory Boolean create = null; while (create == null) { synchronized (objectDeque.makeObjectCountLock) { final long newCreateCount = objectDeque.getCreateCount().incrementAndGet(); // Check against the per key limit if (newCreateCount > maxTotalPerKeySave) { // The key is currently at capacity or in the process of // making enough new objects to take it to capacity. objectDeque.getCreateCount().decrementAndGet(); if (objectDeque.makeObjectCount == 0) { // There are no makeObject() calls in progress for this // key so the key is at capacity. Do not attempt to // create a new object. Return and wait for an object to // be returned. create = Boolean.FALSE; } else { // There are makeObject() calls in progress that might // bring the pool to capacity. Those calls might also // fail so wait until they complete and then re-test if // the pool is at capacity or not. try { objectDeque.makeObjectCountLock.wait(); } catch (final InterruptedException e) { throw cast(e); } } } else { // The pool is not at capacity. Create a new object. objectDeque.makeObjectCount++; create = Boolean.TRUE; } } } if (!create.booleanValue()) { numTotal.decrementAndGet(); return null; } PooledObject<T> p = null; try { p = factory.makeObject(key); if (PooledObject.isNull(p)) { numTotal.decrementAndGet(); objectDeque.getCreateCount().decrementAndGet(); throw new NullPointerException(String.format("%s.makeObject() = null", factory.getClass().getSimpleName())); } if (getTestOnCreate() && !factory.validateObject(key, p)) { numTotal.decrementAndGet(); objectDeque.getCreateCount().decrementAndGet(); return null; } } catch (final Exception e) { numTotal.decrementAndGet(); objectDeque.getCreateCount().decrementAndGet(); throw e; } finally { synchronized (objectDeque.makeObjectCountLock) { objectDeque.makeObjectCount--; objectDeque.makeObjectCountLock.notifyAll(); } } final AbandonedConfig ac = this.abandonedConfig; if (ac != null && ac.getLogAbandoned()) { p.setLogAbandoned(true); p.setRequireFullStackTrace(ac.getRequireFullStackTrace()); } createdCount.incrementAndGet(); objectDeque.getAllObjects().put(IdentityWrapper.on(p), p); return p; } /** * De-register the use of a key by an object. * <p> * {@link #register(Object)} and {@link #deregister(Object)} must always be used as a pair. * </p> * * @param k The key to de-register */ private void deregister(final K k) { Lock lock = keyLock.readLock(); try { lock.lock(); final ObjectDeque<T> objectDeque = poolMap.get(k); if (objectDeque != null) { // Potential to remove key // Upgrade to write lock lock.unlock(); lock = keyLock.writeLock(); lock.lock(); if (objectDeque.getNumInterested().decrementAndGet() == 0 && objectDeque.getCreateCount().get() == 0) { // NOTE: Keys must always be removed from both poolMap and // poolKeyList at the same time while protected by // keyLock.writeLock() poolMap.remove(k); poolKeyList.remove(k); } } } finally { lock.unlock(); } } /** * Destroy the wrapped, pooled object. * * @param key The key associated with the object to destroy. * @param toDestroy The wrapped object to be destroyed * @param always Should the object be destroyed even if it is not currently * in the set of idle objects for the given key * @param destroyMode DestroyMode context provided to the factory * * @return {@code true} if the object was destroyed, otherwise {@code false} * @throws E If the object destruction failed */ private boolean destroy(final K key, final PooledObject<T> toDestroy, final boolean always, final DestroyMode destroyMode) throws E { final ObjectDeque<T> objectDeque = register(key); try { boolean isIdle; synchronized (toDestroy) { // Check idle state directly isIdle = toDestroy.getState().equals(PooledObjectState.IDLE); // If idle, not under eviction test, or always is true, remove instance, // updating isIdle if instance is found in idle objects if (isIdle || always) { isIdle = objectDeque.getIdleObjects().remove(toDestroy); } } if (isIdle || always) { objectDeque.getAllObjects().remove(IdentityWrapper.on(toDestroy)); toDestroy.invalidate(); try { factory.destroyObject(key, toDestroy, destroyMode); } finally { objectDeque.getCreateCount().decrementAndGet(); destroyedCount.incrementAndGet(); numTotal.decrementAndGet(); } return true; } return false; } finally { deregister(key); } } @Override void ensureMinIdle() throws E { final int minIdlePerKeySave = getMinIdlePerKey(); if (minIdlePerKeySave < 1) { return; } for (final K k : poolMap.keySet()) { ensureMinIdle(k); } } /** * Try to ensure that the configured number of minimum idle objects is available in * the pool for the given key. * <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> * <p> * If the factory returns null when creating an object, a {@code NullPointerException} * is thrown. * </p> * * @param key The key to check for idle objects * * @throws E If a new object is required and cannot be created */ private void ensureMinIdle(final K key) throws E { // Calculate current pool objects ObjectDeque<T> objectDeque = poolMap.get(key); // objectDeque == null is OK here. It is handled correctly by both // methods called below. // this method isn't synchronized so the // calculateDeficit is done at the beginning // as a loop limit and a second time inside the loop // to stop when another thread already returned the // needed objects final int deficit = calculateDeficit(objectDeque); for (int i = 0; i < deficit && calculateDeficit(objectDeque) > 0; i++) { addObject(key); // If objectDeque was null, it won't be any more. Obtain a reference // to it so the deficit can be correctly calculated. It needs to // take account of objects created in other threads. if (objectDeque == null) { objectDeque = poolMap.get(key); } } } /** * {@inheritDoc} * <p> * Successive activations of this method examine objects in keyed sub-pools * in sequence, cycling through the keys and examining objects in * oldest-to-youngest order within the keyed sub-pools. * </p> */ @Override public void evict() throws E { assertOpen(); if (getNumIdle() > 0) { PooledObject<T> underTest = null; final EvictionPolicy<T> evictionPolicy = getEvictionPolicy(); synchronized (evictionLock) { final EvictionConfig evictionConfig = new EvictionConfig( getMinEvictableIdleDuration(), getSoftMinEvictableIdleDuration(), getMinIdlePerKey()); final boolean testWhileIdle = getTestWhileIdle(); for (int i = 0, m = getNumTests(); i < m; i++) { if (evictionIterator == null || !evictionIterator.hasNext()) { if (evictionKeyIterator == null || !evictionKeyIterator.hasNext()) { final List<K> keyCopy = new ArrayList<>(); final Lock readLock = keyLock.readLock(); readLock.lock(); try { keyCopy.addAll(poolKeyList); } finally { readLock.unlock(); } evictionKeyIterator = keyCopy.iterator(); } while (evictionKeyIterator.hasNext()) { evictionKey = evictionKeyIterator.next(); final ObjectDeque<T> objectDeque = poolMap.get(evictionKey); if (objectDeque == null) { continue; } final Deque<PooledObject<T>> idleObjects = objectDeque.getIdleObjects(); evictionIterator = new EvictionIterator(idleObjects); if (evictionIterator.hasNext()) { break; } evictionIterator = null; } } if (evictionIterator == null) { // Pools exhausted return; } final Deque<PooledObject<T>> idleObjects; try { underTest = evictionIterator.next(); idleObjects = evictionIterator.getIdleObjects(); } catch (final NoSuchElementException nsee) { // Object was borrowed in another thread // Don't count this as an eviction test so reduce i; i--; evictionIterator = null; continue; } if (!underTest.startEvictionTest()) { // Object was borrowed in another thread // Don't count this as an eviction test so reduce i; i--; continue; } // User provided eviction policy could throw all sorts of // crazy exceptions. Protect against such an exception // killing the eviction thread. boolean evict; try { evict = evictionPolicy.evict(evictionConfig, underTest, poolMap.get(evictionKey).getIdleObjects().size()); } catch (final Throwable t) { // Slightly convoluted as SwallowedExceptionListener // uses Exception rather than Throwable PoolUtils.checkRethrow(t); swallowException(new Exception(t)); // Don't evict on error conditions evict = false; } if (evict) { destroy(evictionKey, underTest, true, DestroyMode.NORMAL); destroyedByEvictorCount.incrementAndGet(); } else { if (testWhileIdle) { boolean active = false; try { factory.activateObject(evictionKey, underTest); active = true; } catch (final Exception e) { destroy(evictionKey, underTest, true, DestroyMode.NORMAL); destroyedByEvictorCount.incrementAndGet(); } if (active) { boolean validate = false; Throwable validationThrowable = null; try { validate = factory.validateObject(evictionKey, underTest); } catch (final Throwable t) { PoolUtils.checkRethrow(t); validationThrowable = t; } if (!validate) { destroy(evictionKey, underTest, true, DestroyMode.NORMAL); destroyedByEvictorCount.incrementAndGet(); if (validationThrowable != null) { if (validationThrowable instanceof RuntimeException) { throw (RuntimeException) validationThrowable; } throw (Error) validationThrowable; } } else { try { factory.passivateObject(evictionKey, underTest); } catch (final Exception e) { destroy(evictionKey, underTest, true, DestroyMode.NORMAL); destroyedByEvictorCount.incrementAndGet(); } } } } underTest.endEvictionTest(idleObjects); // TODO - May need to add code here once additional // states are used } } } } final AbandonedConfig ac = this.abandonedConfig; if (ac != null && ac.getRemoveAbandonedOnMaintenance()) { removeAbandoned(ac); } } /** * Gets a reference to the factory used to create, destroy and validate * the objects used by this pool. * * @return the factory */ public KeyedPooledObjectFactory<K, T, E> getFactory() { return factory; } /** * Gets a copy of the pool key list. * * @return a copy of the pool key list. * @since 2.12.0 */ @Override @SuppressWarnings("unchecked") public List<K> getKeys() { return (List<K>) poolKeyList.clone(); } /** * Gets the cap on the number of "idle" instances per key in the pool. * If maxIdlePerKey is set too low on heavily loaded systems it is possible * you will see objects being destroyed and almost immediately new objects * being created. This is a result of the active threads momentarily * returning objects faster than they are requesting them, causing the * number of idle objects to rise above maxIdlePerKey. The best value for * maxIdlePerKey for heavily loaded system will vary but the default is a * good starting point. * * @return the maximum number of "idle" instances that can be held in a * given keyed sub-pool or a negative value if there is no limit * * @see #setMaxIdlePerKey */ @Override public int getMaxIdlePerKey() { return maxIdlePerKey; } /** * Gets the limit on the number of object instances allocated by the pool * (checked out or idle), per key. When the limit is reached, the sub-pool * is said to be exhausted. A negative value indicates no limit. * * @return the limit on the number of active instances per key * * @see #setMaxTotalPerKey */ @Override public int getMaxTotalPerKey() { return maxTotalPerKey; } /** * Gets the target for the minimum number of idle objects to maintain in * each of the keyed sub-pools. This setting only has an effect if it is * positive and {@link #getDurationBetweenEvictionRuns()} is greater than * zero. If this is the case, an attempt is made to ensure that each * sub-pool has the required minimum number of instances during idle object * eviction runs. * <p> * If the configured value of minIdlePerKey is greater than the configured * value for maxIdlePerKey then the value of maxIdlePerKey will be used * instead. * </p> * * @return minimum size of the each keyed pool * @see #setDurationBetweenEvictionRuns(Duration) */ @Override public int getMinIdlePerKey() { final int maxIdlePerKeySave = getMaxIdlePerKey(); return Math.min(this.minIdlePerKey, maxIdlePerKeySave); } @Override public int getNumActive() { return numTotal.get() - getNumIdle(); } @Override public int getNumActive(final K key) { final ObjectDeque<T> objectDeque = poolMap.get(key); if (objectDeque != null) { return objectDeque.getAllObjects().size() - objectDeque.getIdleObjects().size(); } return 0; } @Override public Map<String, Integer> getNumActivePerKey() { return poolMap.entrySet().stream().collect(Collectors.toMap( e -> e.getKey().toString(), e -> Integer.valueOf(e.getValue().getAllObjects().size() - e.getValue().getIdleObjects().size()), (t, u) -> u)); } @Override public int getNumIdle() { return poolMap.values().stream().mapToInt(e -> e.getIdleObjects().size()).sum(); } @Override public int getNumIdle(final K key) { final ObjectDeque<T> objectDeque = poolMap.get(key); return objectDeque != null ? objectDeque.getIdleObjects().size() : 0; } /** * Gets the number of objects to test in a run of the idle object * evictor. * * @return The number of objects to test for validity */ private int getNumTests() { final int totalIdle = getNumIdle(); final int numTests = getNumTestsPerEvictionRun(); if (numTests >= 0) { return Math.min(numTests, totalIdle); } return (int) Math.ceil(totalIdle / Math.abs((double) numTests)); } /** * Gets an estimate of the number of threads currently blocked waiting for * an object from the pool. This is intended for monitoring only, not for * synchronization control. * * @return The estimate of the number of threads currently blocked waiting * for an object from the pool */ @Override public int getNumWaiters() { if (getBlockWhenExhausted()) { // Assume no overflow return poolMap.values().stream().mapToInt(e -> e.getIdleObjects().getTakeQueueLength()).sum(); } return 0; } /** * Gets an estimate of the number of threads currently blocked waiting for * an object from the pool for each key. This is intended for * monitoring only, not for synchronization control. * * @return The estimate of the number of threads currently blocked waiting * for an object from the pool for each key */ @Override public Map<String, Integer> getNumWaitersByKey() { final Map<String, Integer> result = new HashMap<>(); poolMap.forEach((k, deque) -> result.put(k.toString(), getBlockWhenExhausted() ? Integer.valueOf(deque.getIdleObjects().getTakeQueueLength()) : ZERO)); return result; } @Override String getStatsString() { // Simply listed in AB order. return super.getStatsString() + String.format(", fairness=%s, maxIdlePerKey%,d, maxTotalPerKey=%,d, minIdlePerKey=%,d, numTotal=%,d", fairness, maxIdlePerKey, maxTotalPerKey, minIdlePerKey, numTotal.get()); } /** * Tests to see if there are any threads currently waiting to borrow * objects but are blocked waiting for more objects to become available. * * @return {@code true} if there is at least one thread waiting otherwise * {@code false} */ private boolean hasBorrowWaiters() { return getBlockWhenExhausted() && poolMap.values().stream().anyMatch(deque -> deque.getIdleObjects().hasTakeWaiters()); } /** * {@inheritDoc} * <p> * Activation of this method decrements the active count associated with * the given keyed pool and attempts to destroy {@code obj.} * </p> * * @param key pool key * @param obj instance to invalidate * * @throws E if an exception occurs destroying the * object * @throws IllegalStateException if obj does not belong to the pool * under the given key */ @Override public void invalidateObject(final K key, final T obj) throws E { invalidateObject(key, obj, DestroyMode.NORMAL); } /** * {@inheritDoc} * <p> * Activation of this method decrements the active count associated with * the given keyed pool and attempts to destroy {@code obj.} * </p> * * @param key pool key * @param obj instance to invalidate * @param destroyMode DestroyMode context provided to factory * * @throws E if an exception occurs destroying the * object * @throws IllegalStateException if obj does not belong to the pool * under the given key * @since 2.9.0 */ @Override public void invalidateObject(final K key, final T obj, final DestroyMode destroyMode) throws E { final ObjectDeque<T> objectDeque = poolMap.get(key); final PooledObject<T> p = objectDeque != null ? objectDeque.getAllObjects().get(new IdentityWrapper<>(obj)) : null; if (p == null) { throw new IllegalStateException(appendStats("Object not currently part of this pool")); } synchronized (p) { if (p.getState() != PooledObjectState.INVALID) { destroy(key, p, true, destroyMode); reuseCapacity(); } } } /** * Provides information on all the objects in the pool, both idle (waiting * to be borrowed) and active (currently borrowed). * <p> * Note: This is named listAllObjects so it is presented as an operation via * JMX. That means it won't be invoked unless the explicitly requested * whereas all attributes will be automatically requested when viewing the * attributes for an object in a tool like JConsole. * </p> * * @return Information grouped by key on all the objects in the pool */ @Override public Map<String, List<DefaultPooledObjectInfo>> listAllObjects() { return poolMap.entrySet().stream().collect(Collectors.toMap(e -> e.getKey().toString(), e -> e.getValue().getAllObjects().values().stream().map(DefaultPooledObjectInfo::new).collect(Collectors.toList()))); } /** * Registers a key for pool control and ensures that * {@link #getMinIdlePerKey()} idle instances are created. * * @param key - The key to register for pool control. * * @throws E If the associated factory throws an exception */ public void preparePool(final K key) throws E { final int minIdlePerKeySave = getMinIdlePerKey(); if (minIdlePerKeySave < 1) { return; } ensureMinIdle(key); } /** * Register the use of a key by an object. * <p> * {@link #register(Object)} and {@link #deregister(Object)} must always be used as a pair. * </p> * * @param k The key to register * * @return The objects currently associated with the given key. If this * method returns without throwing an exception then it will never * return null. */ private ObjectDeque<T> register(final K k) { Lock lock = keyLock.readLock(); ObjectDeque<T> objectDeque = null; try { lock.lock(); objectDeque = poolMap.get(k); if (objectDeque == null) { // Upgrade to write lock lock.unlock(); lock = keyLock.writeLock(); lock.lock(); final AtomicBoolean allocated = new AtomicBoolean(); objectDeque = poolMap.computeIfAbsent(k, key -> { allocated.set(true); final ObjectDeque<T> deque = new ObjectDeque<>(fairness); deque.getNumInterested().incrementAndGet(); // NOTE: Keys must always be added to both poolMap and // poolKeyList at the same time while protected by poolKeyList.add(k); return deque; }); if (!allocated.get()) { objectDeque.getNumInterested().incrementAndGet(); } } else { objectDeque.getNumInterested().incrementAndGet(); } } finally { lock.unlock(); } return objectDeque; } /** * Recovers abandoned objects which have been checked out but * not used since longer than the removeAbandonedTimeout. * * @param abandonedConfig The configuration to use to identify abandoned objects */ @SuppressWarnings("resource") // The PrintWriter is managed elsewhere private void removeAbandoned(final AbandonedConfig abandonedConfig) { poolMap.forEach((key, value) -> { // Generate a list of abandoned objects to remove final ArrayList<PooledObject<T>> remove = createRemoveList(abandonedConfig, value.getAllObjects()); // Now remove the abandoned objects remove.forEach(pooledObject -> { if (abandonedConfig.getLogAbandoned()) { pooledObject.printStackTrace(abandonedConfig.getLogWriter()); } try { invalidateObject(key, pooledObject.getObject(), DestroyMode.ABANDONED); } catch (final Exception e) { swallowException(e); } }); }); } /** * Returns an object to a keyed sub-pool. * <p> * If {@link #getMaxIdlePerKey() maxIdle} is set to a positive value and the * number of idle instances under the given key has reached this value, the * returning instance is destroyed. * </p> * <p> * If {@link #getTestOnReturn() testOnReturn} == true, the returning * instance is validated before being returned to the idle instance sub-pool * under the given key. In this case, if validation fails, the instance is * destroyed. * </p> * <p> * Exceptions encountered destroying objects for any reason are swallowed * but notified via a {@link SwallowedExceptionListener}. * </p> * * @param key pool key * @param obj instance to return to the keyed pool * * @throws IllegalStateException if an object is returned to the pool that * was not borrowed from it or if an object is * returned to the pool multiple times */ @Override public void returnObject(final K key, final T obj) { final ObjectDeque<T> objectDeque = poolMap.get(key); if (objectDeque == null) { throw new IllegalStateException("No keyed pool found under the given key."); } final PooledObject<T> p = objectDeque.getAllObjects().get(new IdentityWrapper<>(obj)); if (PooledObject.isNull(p)) { throw new IllegalStateException("Returned object not currently part of this pool"); } markReturningState(p); final Duration activeTime = p.getActiveDuration(); try { if (getTestOnReturn() && !factory.validateObject(key, p)) { try { destroy(key, p, true, DestroyMode.NORMAL); } catch (final Exception e) { swallowException(e); } whenWaitersAddObject(key, objectDeque.idleObjects); return; } try { factory.passivateObject(key, p); } catch (final Exception e1) { swallowException(e1); try { destroy(key, p, true, DestroyMode.NORMAL); } catch (final Exception e) { swallowException(e); } whenWaitersAddObject(key, objectDeque.idleObjects); return; } if (!p.deallocate()) { throw new IllegalStateException("Object has already been returned to this pool"); } final int maxIdle = getMaxIdlePerKey(); final LinkedBlockingDeque<PooledObject<T>> idleObjects = objectDeque.getIdleObjects(); if (isClosed() || maxIdle > -1 && maxIdle <= idleObjects.size()) { try { destroy(key, p, true, DestroyMode.NORMAL); } catch (final Exception e) { swallowException(e); } } else { 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(key); } } } finally { if (hasBorrowWaiters()) { reuseCapacity(); } updateStatsReturn(activeTime); } } /** * Attempt to create one new instance to serve from the most heavily * loaded pool that can add a new instance. * * This method exists to ensure liveness in the pool when threads are * parked waiting and capacity to create instances under the requested keys * subsequently becomes available. * * This method is not guaranteed to create an instance and its selection * of the most loaded pool that can create an instance may not always be * correct, since it does not lock the pool and instances may be created, * borrowed, returned or destroyed by other threads while it is executing. */ private void reuseCapacity() { final int maxTotalPerKeySave = getMaxTotalPerKey(); int maxQueueLength = 0; LinkedBlockingDeque<PooledObject<T>> mostLoadedPool = null; K mostLoadedKey = null; // Find the most loaded pool that could take a new instance for (final Map.Entry<K, ObjectDeque<T>> entry : poolMap.entrySet()) { final K k = entry.getKey(); final LinkedBlockingDeque<PooledObject<T>> pool = entry.getValue().getIdleObjects(); final int queueLength = pool.getTakeQueueLength(); if (getNumActive(k) < maxTotalPerKeySave && queueLength > maxQueueLength) { maxQueueLength = queueLength; mostLoadedPool = pool; mostLoadedKey = k; } } // Attempt to add an instance to the most loaded pool. if (mostLoadedPool != null) { register(mostLoadedKey); try { // If there is no capacity to add, create will return null // and addIdleObject will no-op. addIdleObject(mostLoadedKey, create(mostLoadedKey)); } catch (final Exception e) { swallowException(e); } finally { deregister(mostLoadedKey); } } } /** * Call {@link #reuseCapacity()} repeatedly. * <p> * Always activates {@link #reuseCapacity()} at least once. * * @param newCapacity number of new instances to attempt to create. */ private void reuseCapacity(final int newCapacity) { final int bound = newCapacity < 1 ? 1 : newCapacity; for (int i = 0; i < bound; i++) { reuseCapacity(); } } /** * Sets the configuration. * * @param conf the new configuration to use. This is used by value. * * @see GenericKeyedObjectPoolConfig */ public void setConfig(final GenericKeyedObjectPoolConfig<T> conf) { super.setConfig(conf); setMaxIdlePerKey(conf.getMaxIdlePerKey()); setMaxTotalPerKey(conf.getMaxTotalPerKey()); setMaxTotal(conf.getMaxTotal()); setMinIdlePerKey(conf.getMinIdlePerKey()); } /** * Sets the cap on the number of "idle" instances per key in the pool. * If maxIdlePerKey is set too low on heavily loaded systems it is possible * you will see objects being destroyed and almost immediately new objects * being created. This is a result of the active threads momentarily * returning objects faster than they are requesting them, causing the * number of idle objects to rise above maxIdlePerKey. The best value for * maxIdlePerKey for heavily loaded system will vary but the default is a * good starting point. * * @param maxIdlePerKey the maximum number of "idle" instances that can be * held in a given keyed sub-pool. Use a negative value * for no limit * * @see #getMaxIdlePerKey */ public void setMaxIdlePerKey(final int maxIdlePerKey) { this.maxIdlePerKey = maxIdlePerKey; } /** * Sets the limit on the number of object instances allocated by the pool * (checked out or idle), per key. When the limit is reached, the sub-pool * is said to be exhausted. A negative value indicates no limit. * * @param maxTotalPerKey the limit on the number of active instances per key * * @see #getMaxTotalPerKey */ public void setMaxTotalPerKey(final int maxTotalPerKey) { this.maxTotalPerKey = maxTotalPerKey; } /** * Sets the target for the minimum number of idle objects to maintain in * each of the keyed sub-pools. This setting only has an effect if it is * positive and {@link #getDurationBetweenEvictionRuns()} is greater than * zero. If this is the case, an attempt is made to ensure that each * sub-pool has the required minimum number of instances during idle object * eviction runs. * <p> * If the configured value of minIdlePerKey is greater than the configured * value for maxIdlePerKey then the value of maxIdlePerKey will be used * instead. * </p> * * @param minIdlePerKey The minimum size of the each keyed pool * * @see #getMinIdlePerKey() * @see #getMaxIdlePerKey() * @see #setDurationBetweenEvictionRuns(Duration) */ public void setMinIdlePerKey(final int minIdlePerKey) { this.minIdlePerKey = minIdlePerKey; } @Override protected void toStringAppendFields(final StringBuilder builder) { super.toStringAppendFields(builder); builder.append(", maxIdlePerKey="); builder.append(maxIdlePerKey); builder.append(", minIdlePerKey="); builder.append(minIdlePerKey); builder.append(", maxTotalPerKey="); builder.append(maxTotalPerKey); builder.append(", factory="); builder.append(factory); builder.append(", fairness="); builder.append(fairness); builder.append(", poolMap="); builder.append(poolMap); builder.append(", poolKeyList="); builder.append(poolKeyList); builder.append(", keyLock="); builder.append(keyLock); builder.append(", numTotal="); builder.append(numTotal); builder.append(", evictionKeyIterator="); builder.append(evictionKeyIterator); builder.append(", evictionKey="); builder.append(evictionKey); builder.append(", abandonedConfig="); builder.append(abandonedConfig); } /** * @since 2.10.0 */ @Override public void use(final T pooledObject) { final AbandonedConfig abandonedCfg = this.abandonedConfig; if (abandonedCfg != null && abandonedCfg.getUseUsageTracking()) { poolMap.values().stream() .map(pool -> pool.getAllObjects().get(new IdentityWrapper<>(pooledObject))) .filter(Objects::nonNull) .findFirst() .ifPresent(PooledObject::use); } } /** * 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); } } } }
5,276
0
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3/impl/PooledSoftReference.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.impl; import java.lang.ref.SoftReference; /** * Extension of {@link DefaultPooledObject} to wrap pooled soft references. * * <p>This class is intended to be thread-safe.</p> * * @param <T> the type of the underlying object that the wrapped SoftReference * refers to. * * @since 2.0 */ public class PooledSoftReference<T> extends DefaultPooledObject<T> { /** SoftReference wrapped by this object */ private volatile SoftReference<T> reference; /** * Creates a new PooledSoftReference wrapping the provided reference. * * @param reference SoftReference to be managed by the pool */ public PooledSoftReference(final SoftReference<T> reference) { super(null); // Null the hard reference in the parent this.reference = reference; } /** * Gets the object that the wrapped SoftReference refers to. * <p> * Note that if the reference has been cleared, this method will return * null. * </p> * * @return Object referred to by the SoftReference */ @Override public T getObject() { return reference.get(); } /** * Gets the SoftReference wrapped by this object. * * @return underlying SoftReference */ public synchronized SoftReference<T> getReference() { return reference; } /** * Sets the wrapped reference. * * <p>This method exists to allow a new, non-registered reference to be * held by the pool to track objects that have been checked out of the pool. * The actual parameter <strong>should</strong> be a reference to the same * object that {@link #getObject()} returns before calling this method.</p> * * @param reference new reference */ public synchronized void setReference(final SoftReference<T> reference) { this.reference = reference; } /** * {@inheritDoc} */ @Override public String toString() { final StringBuilder result = new StringBuilder(); result.append("Referenced Object: "); result.append(getObject().toString()); result.append(", State: "); synchronized (this) { result.append(getState().toString()); } return result.toString(); // TODO add other attributes // TODO encapsulate state and other attribute display in parent } }
5,277
0
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3/impl/DefaultPooledObject.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.impl; import java.io.PrintWriter; import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.util.Deque; import java.util.Objects; import org.apache.commons.pool3.PooledObject; import org.apache.commons.pool3.PooledObjectState; import org.apache.commons.pool3.TrackedUse; /** * This wrapper is used to track the additional information, such as state, for * the pooled objects. * <p> * This class is intended to be thread-safe. * </p> * * @param <T> the type of object in the pool * * @since 2.0 */ public class DefaultPooledObject<T> implements PooledObject<T> { private final T object; private PooledObjectState state = PooledObjectState.IDLE; // @GuardedBy("this") to ensure transitions are valid private final Clock systemClock = Clock.systemUTC(); private final Instant createInstant = now(); private volatile Instant lastBorrowInstant = createInstant; private volatile Instant lastUseInstant = createInstant; private volatile Instant lastReturnInstant = createInstant; private volatile boolean logAbandoned; private volatile CallStack borrowedBy = NoOpCallStack.INSTANCE; private volatile CallStack usedBy = NoOpCallStack.INSTANCE; private volatile long borrowedCount; /** * Creates a new instance that wraps the provided object so that the pool can * track the state of the pooled object. * * @param object The object to wrap */ public DefaultPooledObject(final T object) { this.object = object; } /** * Allocates the object. * * @return {@code true} if the original state was {@link PooledObjectState#IDLE IDLE} */ @Override public synchronized boolean allocate() { if (state == PooledObjectState.IDLE) { state = PooledObjectState.ALLOCATED; lastBorrowInstant = now(); lastUseInstant = lastBorrowInstant; borrowedCount++; if (logAbandoned) { borrowedBy.fillInStackTrace(); } return true; } if (state == PooledObjectState.EVICTION) { // TODO Allocate anyway and ignore eviction test state = PooledObjectState.EVICTION_RETURN_TO_HEAD; } // TODO if validating and testOnBorrow == true then pre-allocate for // performance return false; } @Override public int compareTo(final PooledObject<T> other) { final int compareTo = getLastReturnInstant().compareTo(other.getLastReturnInstant()); if (compareTo == 0) { // Make sure the natural ordering is broadly consistent with equals // although this will break down if distinct objects have the same // identity hash code. // see java.lang.Comparable Javadocs return System.identityHashCode(this) - System.identityHashCode(other); } return compareTo; } /** * Deallocates the object and sets it {@link PooledObjectState#IDLE IDLE} * if it is currently {@link PooledObjectState#ALLOCATED ALLOCATED} * or {@link PooledObjectState#RETURNING RETURNING}. * * @return {@code true} if the state was {@link PooledObjectState#ALLOCATED ALLOCATED} * or {@link PooledObjectState#RETURNING RETURNING}. */ @Override public synchronized boolean deallocate() { if (state == PooledObjectState.ALLOCATED || state == PooledObjectState.RETURNING) { state = PooledObjectState.IDLE; lastReturnInstant = now(); borrowedBy.clear(); return true; } return false; } @Override public synchronized boolean endEvictionTest( final Deque<PooledObject<T>> idleQueue) { if (state == PooledObjectState.EVICTION) { state = PooledObjectState.IDLE; return true; } if (state == PooledObjectState.EVICTION_RETURN_TO_HEAD) { state = PooledObjectState.IDLE; idleQueue.offerFirst(this); } return false; } /** * Gets the number of times this object has been borrowed. * @return The number of times this object has been borrowed. * @since 2.1 */ @Override public long getBorrowedCount() { return borrowedCount; } @Override public Instant getCreateInstant() { return createInstant; } @Override public Duration getIdleDuration() { // elapsed may be negative if: // - another thread updates lastReturnInstant during the calculation window // - System.currentTimeMillis() is not monotonic (e.g. system time is set back) final Duration elapsed = Duration.between(lastReturnInstant, now()); return elapsed.isNegative() ? Duration.ZERO : elapsed; } @Override public Instant getLastBorrowInstant() { return lastBorrowInstant; } @Override public Instant getLastReturnInstant() { return lastReturnInstant; } /** * Gets an estimate of the last time this object was used. If the class * of the pooled object implements {@link TrackedUse}, what is returned is * the maximum of {@link TrackedUse#getLastUsedInstant()} and * {@link #getLastBorrowInstant()}; otherwise this method gives the same * value as {@link #getLastBorrowInstant()}. * * @return the last Instant this object was used. */ @Override public Instant getLastUsedInstant() { if (object instanceof TrackedUse) { return PoolImplUtils.max(((TrackedUse) object).getLastUsedInstant(), lastUseInstant); } return lastUseInstant; } @Override public T getObject() { return object; } /** * Gets the state of this object. * @return state */ @Override public synchronized PooledObjectState getState() { return state; } /** * Sets the state to {@link PooledObjectState#INVALID INVALID}. */ @Override public synchronized void invalidate() { state = PooledObjectState.INVALID; } /** * Marks the pooled object as {@link PooledObjectState#ABANDONED ABANDONED}. */ @Override public synchronized void markAbandoned() { state = PooledObjectState.ABANDONED; } /** * Marks the pooled object as {@link PooledObjectState#RETURNING RETURNING}. */ @Override public synchronized void markReturning() { state = PooledObjectState.RETURNING; } /** * Gets the current instant of the clock. * * @return the current instant of the clock. */ private Instant now() { return systemClock.instant(); } @Override public void printStackTrace(final PrintWriter writer) { boolean written = borrowedBy.printStackTrace(writer); written |= usedBy.printStackTrace(writer); if (written) { writer.flush(); } } @Override public void setLogAbandoned(final boolean logAbandoned) { this.logAbandoned = logAbandoned; } /** * Configures the stack trace generation strategy based on whether or not fully * detailed stack traces are required. When set to false, abandoned logs may * only include caller class information rather than method names, line numbers, * and other normal metadata available in a full stack trace. * * @param requireFullStackTrace the new configuration setting for abandoned object * logging * @since 2.5 */ @Override public void setRequireFullStackTrace(final boolean requireFullStackTrace) { borrowedBy = CallStackUtils.newCallStack("'Pooled object created' " + "yyyy-MM-dd HH:mm:ss Z 'by the following code has not been returned to the pool:'", true, requireFullStackTrace); usedBy = CallStackUtils.newCallStack("The last code to use this object was:", false, requireFullStackTrace); } @Override public synchronized boolean startEvictionTest() { if (state == PooledObjectState.IDLE) { state = PooledObjectState.EVICTION; return true; } return false; } @Override public String toString() { final StringBuilder result = new StringBuilder(); result.append("Object: "); result.append(Objects.toString(object)); result.append(", State: "); synchronized (this) { result.append(state.toString()); } return result.toString(); // TODO add other attributes } @Override public void use() { lastUseInstant = now(); usedBy.fillInStackTrace(); } }
5,278
0
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3/impl/PoolImplUtils.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.impl; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.time.Duration; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.Objects; import java.util.concurrent.TimeUnit; import org.apache.commons.pool3.PooledObjectFactory; /** * Implementation specific utilities. * * @since 2.0 */ final class PoolImplUtils { /** * Identifies the concrete type of object that an object factory creates. * * @param factoryClass The factory to examine * * @return the type of object the factory creates */ @SuppressWarnings("rawtypes") static Class<?> getFactoryType(final Class<? extends PooledObjectFactory> factoryClass) { final Class<PooledObjectFactory> type = PooledObjectFactory.class; final Object genericType = getGenericType(type, factoryClass); if (genericType instanceof Integer) { // POOL-324 org.apache.commons.pool3.impl.GenericObjectPool.getFactoryType() throws // java.lang.ClassCastException // // A bit hackish, but we must handle cases when getGenericType() does not return a concrete types. final ParameterizedType pi = getParameterizedType(type, factoryClass); if (pi != null) { final Type[] bounds = ((TypeVariable) pi.getActualTypeArguments()[((Integer) genericType).intValue()]) .getBounds(); if (bounds != null && bounds.length > 0) { final Type bound0 = bounds[0]; if (bound0 instanceof Class) { return (Class<?>) bound0; } } } // last resort: Always return a Class return Object.class; } return (Class<?>) genericType; } /** * Gets the concrete type used by an implementation of an interface that uses a generic type. * * @param type The interface that defines a generic type * @param clazz The class that implements the interface with a concrete type * @param <T> The interface type * * @return concrete type used by the implementation */ private static <T> Object getGenericType(final Class<T> type, final Class<? extends T> clazz) { if (type == null || clazz == null) { // Error will be logged further up the call stack return null; } // Look to see if this class implements the generic interface final ParameterizedType pi = getParameterizedType(type, clazz); if (pi != null) { return getTypeParameter(clazz, pi.getActualTypeArguments()[0]); } // Interface not found on this class. Look at the superclass. @SuppressWarnings("unchecked") final Class<? extends T> superClass = (Class<? extends T>) clazz.getSuperclass(); final Object result = getGenericType(type, superClass); if (result instanceof Class<?>) { // Superclass implements interface and defines explicit type for generic return result; } if (result instanceof Integer) { // Superclass implements interface and defines unknown type for generic // Map that unknown type to the generic types defined in this class final ParameterizedType superClassType = (ParameterizedType) clazz.getGenericSuperclass(); return getTypeParameter(clazz, superClassType.getActualTypeArguments()[((Integer) result).intValue()]); } // Error will be logged further up the call stack return null; } /** * Gets the matching parameterized type or null. * * @param type The interface that defines a generic type. * @param clazz The class that implements the interface with a concrete type. * @param <T> The interface type. * @return the matching parameterized type or null. */ private static <T> ParameterizedType getParameterizedType(final Class<T> type, final Class<? extends T> clazz) { for (final Type iface : clazz.getGenericInterfaces()) { // Only need to check interfaces that use generics if (iface instanceof ParameterizedType) { final ParameterizedType pi = (ParameterizedType) iface; // Look for the generic interface if (pi.getRawType() instanceof Class && type.isAssignableFrom((Class<?>) pi.getRawType())) { return pi; } } } return null; } /** * For a generic parameter, return either the Class used or if the type is unknown, the index for the type in * definition of the class * * @param clazz defining class * @param argType the type argument of interest * * @return An instance of {@link Class} representing the type used by the type parameter or an instance of * {@link Integer} representing the index for the type in the definition of the defining class */ private static Object getTypeParameter(final Class<?> clazz, final Type argType) { if (argType instanceof Class<?>) { return argType; } final TypeVariable<?>[] tvs = clazz.getTypeParameters(); for (int i = 0; i < tvs.length; i++) { if (tvs[i].equals(argType)) { return Integer.valueOf(i); } } return null; } static boolean isPositive(final Duration delay) { return delay != null && !delay.isNegative() && !delay.isZero(); } /** * Returns the greater of two {@code Instant} values. That is, the result is the argument closer to the value of * {@link Instant#MAX}. If the arguments have the same value, the result is that same value. * * @param a an argument. * @param b another argument. * @return the larger of {@code a} and {@code b}. */ static Instant max(final Instant a, final Instant b) { return a.compareTo(b) > 0 ? a : b; } /** * Returns the smaller of two {@code Instant} values. That is, the result is the argument closer to the value of * {@link Instant#MIN}. If the arguments have the same value, the result is that same value. * * @param a an argument. * @param b another argument. * @return the smaller of {@code a} and {@code b}. */ static Instant min(final Instant a, final Instant b) { return a.compareTo(b) < 0 ? a : b; } /** * Returns a non-null duration, value if non-null, otherwise defaultValue. * * @param value May be null. * @param defaultValue May not be null/ * @return value if non-null, otherwise defaultValue. */ static Duration nonNull(final Duration value, final Duration defaultValue) { return value != null ? value : Objects.requireNonNull(defaultValue, "defaultValue"); } /** * Converts a {@link TimeUnit} to a {@link ChronoUnit}. * * @param timeUnit A TimeUnit. * @return The corresponding ChronoUnit. */ static ChronoUnit toChronoUnit(final TimeUnit timeUnit) { // TODO when using Java >= 9: Use TimeUnit.toChronoUnit(). switch (Objects.requireNonNull(timeUnit)) { case NANOSECONDS: return ChronoUnit.NANOS; case MICROSECONDS: return ChronoUnit.MICROS; case MILLISECONDS: return ChronoUnit.MILLIS; case SECONDS: return ChronoUnit.SECONDS; case MINUTES: return ChronoUnit.MINUTES; case HOURS: return ChronoUnit.HOURS; case DAYS: return ChronoUnit.DAYS; default: throw new IllegalArgumentException(timeUnit.toString()); } } /** * Converts am amount and TimeUnit into a Duration. * * @param amount the amount of the duration, measured in terms of the unit, positive or negative * @param timeUnit the unit that the duration is measured in, must have an exact duration, not null * @return a Duration. */ static Duration toDuration(final long amount, final TimeUnit timeUnit) { return Duration.of(amount, PoolImplUtils.toChronoUnit(timeUnit)); } }
5,279
0
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3/impl/CallStackUtils.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.impl; import java.security.AccessControlException; /** * Utility methods for {@link CallStack}. * * @since 2.4.3 */ public final class CallStackUtils { /** * Tests whether the caller can create a security manager in the current environment. * * @return {@code true} if it is able to create a security manager in the current environment, {@code false} * otherwise. */ private static boolean canCreateSecurityManager() { final SecurityManager manager = System.getSecurityManager(); if (manager == null) { return true; } try { manager.checkPermission(new RuntimePermission("createSecurityManager")); return true; } catch (final AccessControlException ignored) { return false; } } /** * Constructs a new {@link CallStack} using the fasted allowed strategy. * * @param messageFormat message (or format) to print first in stack traces * @param useTimestamp if true, interpret message as a SimpleDateFormat and print the created timestamp; * otherwise, print message format literally * @param requireFullStackTrace if true, forces the use of a stack walking mechanism that includes full stack trace * information; otherwise, uses a faster implementation if possible * @return a new CallStack * @since 2.5 */ public static CallStack newCallStack(final String messageFormat, final boolean useTimestamp, final boolean requireFullStackTrace) { return canCreateSecurityManager() && !requireFullStackTrace ? new SecurityManagerCallStack(messageFormat, useTimestamp) : new ThrowableCallStack(messageFormat, useTimestamp); } /** * Hidden constructor. */ private CallStackUtils() { } }
5,280
0
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3/impl/EvictionTimer.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.impl; import java.lang.ref.WeakReference; import java.security.AccessController; import java.security.PrivilegedAction; import java.time.Duration; import java.util.HashMap; import java.util.Map.Entry; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; /** * Provides a shared idle object eviction timer for all pools. * <p> * This class is currently implemented using {@link ScheduledThreadPoolExecutor}. This implementation may change in any * future release. This class keeps track of how many pools are using it. If no pools are using the timer, it is * cancelled. This prevents a thread being left running which, in application server environments, can lead to memory * leads and/or prevent applications from shutting down or reloading cleanly. * </p> * <p> * This class has package scope to prevent its inclusion in the pool public API. The class declaration below should * *not* be changed to public. * </p> * <p> * This class is intended to be thread-safe. * </p> * * @since 2.0 */ final class EvictionTimer { /** * Thread factory that creates a daemon thread, with the context class loader from this class. */ private static final class EvictorThreadFactory implements ThreadFactory { @Override public Thread newThread(final Runnable runnable) { final Thread thread = new Thread(null, runnable, "commons-pool-evictor"); thread.setDaemon(true); // POOL-363 - Required for applications using Runtime.addShutdownHook(). AccessController.doPrivileged((PrivilegedAction<Void>) () -> { thread.setContextClassLoader(EvictorThreadFactory.class.getClassLoader()); return null; }); return thread; } } /** * Task that removes references to abandoned tasks and shuts * down the executor if there are no live tasks left. */ private static final class Reaper implements Runnable { @Override public void run() { synchronized (EvictionTimer.class) { for (final Entry<WeakReference<BaseGenericObjectPool<?, ?>.Evictor>, WeakRunner<BaseGenericObjectPool<?, ?>.Evictor>> entry : TASK_MAP .entrySet()) { if (entry.getKey().get() == null) { executor.remove(entry.getValue()); TASK_MAP.remove(entry.getKey()); } } if (TASK_MAP.isEmpty() && executor != null) { executor.shutdown(); executor.setCorePoolSize(0); executor = null; } } } } /** * Runnable that runs the referent of a weak reference. When the referent is no * no longer reachable, run is no-op. * @param <R> The kind of Runnable. */ private static final class WeakRunner<R extends Runnable> implements Runnable { private final WeakReference<R> ref; /** * Constructs a new instance to track the given reference. * * @param ref the reference to track. */ private WeakRunner(final WeakReference<R> ref) { this.ref = ref; } @Override public void run() { final Runnable task = ref.get(); if (task != null) { task.run(); } else { executor.remove(this); TASK_MAP.remove(ref); } } } /** Executor instance */ private static ScheduledThreadPoolExecutor executor; //@GuardedBy("EvictionTimer.class") /** Keys are weak references to tasks, values are runners managed by executor. */ private static final HashMap< WeakReference<BaseGenericObjectPool<?, ?>.Evictor>, WeakRunner<BaseGenericObjectPool<?, ?>.Evictor>> TASK_MAP = new HashMap<>(); // @GuardedBy("EvictionTimer.class") /** * Removes the specified eviction task from the timer. * * @param evictor Task to be cancelled. * @param timeout If the associated executor is no longer required, how * long should this thread wait for the executor to * terminate? * @param restarting The state of the evictor. */ static synchronized void cancel(final BaseGenericObjectPool<?, ?>.Evictor evictor, final Duration timeout, final boolean restarting) { if (evictor != null) { evictor.cancel(); remove(evictor); } if (!restarting && executor != null && TASK_MAP.isEmpty()) { executor.shutdown(); try { executor.awaitTermination(timeout.toMillis(), TimeUnit.MILLISECONDS); } catch (final InterruptedException e) { // Swallow // Significant API changes would be required to propagate this } executor.setCorePoolSize(0); executor = null; } } /** * For testing only. * * @return The executor. */ static ScheduledThreadPoolExecutor getExecutor() { return executor; } /** * @return the number of eviction tasks under management. */ static synchronized int getNumTasks() { return TASK_MAP.size(); } /** * Gets the task map. Keys are weak references to tasks, values are runners managed by executor. * * @return the task map. */ static HashMap<WeakReference<BaseGenericObjectPool<?, ?>.Evictor>, WeakRunner<BaseGenericObjectPool<?, ?>.Evictor>> getTaskMap() { return TASK_MAP; } /** * Removes evictor from the task set and executor. * Only called when holding the class lock. * * @param evictor Eviction task to remove */ private static void remove(final BaseGenericObjectPool<?, ?>.Evictor evictor) { for (final Entry<WeakReference<BaseGenericObjectPool<?, ?>.Evictor>, WeakRunner<BaseGenericObjectPool<?, ?>.Evictor>> entry : TASK_MAP.entrySet()) { if (entry.getKey().get() == evictor) { executor.remove(entry.getValue()); TASK_MAP.remove(entry.getKey()); break; } } } /** * Adds the specified eviction task to the timer. Tasks that are added with * a call to this method *must* call {@link * #cancel(BaseGenericObjectPool.Evictor, Duration, boolean)} * to cancel the task to prevent memory and/or thread leaks in application * server environments. * * @param task Task to be scheduled. * @param delay Delay in milliseconds before task is executed. * @param period Time in milliseconds between executions. */ static synchronized void schedule( final BaseGenericObjectPool<?, ?>.Evictor task, final Duration delay, final Duration period) { if (null == executor) { executor = new ScheduledThreadPoolExecutor(1, new EvictorThreadFactory()); executor.setRemoveOnCancelPolicy(true); executor.scheduleAtFixedRate(new Reaper(), delay.toMillis(), period.toMillis(), TimeUnit.MILLISECONDS); } final WeakReference<BaseGenericObjectPool<?, ?>.Evictor> ref = new WeakReference<>(task); final WeakRunner<BaseGenericObjectPool<?, ?>.Evictor> runner = new WeakRunner<>(ref); final ScheduledFuture<?> scheduledFuture = executor.scheduleWithFixedDelay(runner, delay.toMillis(), period.toMillis(), TimeUnit.MILLISECONDS); task.setScheduledFuture(scheduledFuture); TASK_MAP.put(ref, runner); } /** Prevents instantiation */ private EvictionTimer() { // Hide the default constructor } /** * @since 2.4.3 */ @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("EvictionTimer []"); return builder.toString(); } }
5,281
0
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3/impl/SecurityManagerCallStack.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.impl; import java.io.PrintWriter; import java.lang.ref.WeakReference; import java.security.AccessController; import java.security.PrivilegedAction; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; /** * A {@link CallStack} strategy using a {@link SecurityManager}. Obtaining the current call stack is much faster via a * SecurityManger, but access to the underlying method may be restricted by the current SecurityManager. In environments * where a SecurityManager cannot be created, {@link ThrowableCallStack} should be used instead. * * @see RuntimePermission * @see SecurityManager#getClassContext() * @since 2.4.3 */ public class SecurityManagerCallStack implements CallStack { /** * A custom security manager. */ private static final class PrivateSecurityManager extends SecurityManager { /** * Gets the class stack. * * @return class stack */ private List<WeakReference<Class<?>>> getCallStack() { final Stream<WeakReference<Class<?>>> map = Stream.of(getClassContext()).map(WeakReference::new); return map.collect(Collectors.toList()); } } /** * A snapshot of a class stack. */ private static final class Snapshot { private final long timestampMillis = System.currentTimeMillis(); private final List<WeakReference<Class<?>>> stack; /** * Constructs a new snapshot with a class stack. * * @param stack class stack */ private Snapshot(final List<WeakReference<Class<?>>> stack) { this.stack = stack; } } private final String messageFormat; //@GuardedBy("dateFormat") private final DateFormat dateFormat; private final PrivateSecurityManager securityManager; private volatile Snapshot snapshot; /** * Creates a new instance. * * @param messageFormat message format * @param useTimestamp whether to format the dates in the output message or not */ public SecurityManagerCallStack(final String messageFormat, final boolean useTimestamp) { this.messageFormat = messageFormat; this.dateFormat = useTimestamp ? new SimpleDateFormat(messageFormat) : null; this.securityManager = AccessController.doPrivileged((PrivilegedAction<PrivateSecurityManager>) PrivateSecurityManager::new); } @Override public void clear() { snapshot = null; } @Override public void fillInStackTrace() { snapshot = new Snapshot(securityManager.getCallStack()); } @Override public boolean printStackTrace(final PrintWriter writer) { final Snapshot snapshotRef = this.snapshot; if (snapshotRef == null) { return false; } final String message; if (dateFormat == null) { message = messageFormat; } else { synchronized (dateFormat) { message = dateFormat.format(Long.valueOf(snapshotRef.timestampMillis)); } } writer.println(message); snapshotRef.stack.forEach(reference -> writer.println(reference.get())); return true; } }
5,282
0
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3/impl/ThrowableCallStack.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.impl; import java.io.PrintWriter; import java.text.DateFormat; import java.text.SimpleDateFormat; /** * CallStack strategy that uses the stack trace from a {@link Throwable}. This strategy, while slower than the * SecurityManager implementation, provides call stack method names and other metadata in addition to the call stack * of classes. * * @see Throwable#fillInStackTrace() * @since 2.4.3 */ public class ThrowableCallStack implements CallStack { /** * A snapshot of a throwable. */ private static final class Snapshot extends Throwable { private static final long serialVersionUID = 1L; private final long timestampMillis = System.currentTimeMillis(); } private final String messageFormat; //@GuardedBy("dateFormat") private final DateFormat dateFormat; private volatile Snapshot snapshot; /** * Creates a new instance. * * @param messageFormat message format * @param useTimestamp whether to format the dates in the output message or not */ public ThrowableCallStack(final String messageFormat, final boolean useTimestamp) { this.messageFormat = messageFormat; this.dateFormat = useTimestamp ? new SimpleDateFormat(messageFormat) : null; } @Override public void clear() { snapshot = null; } @Override public void fillInStackTrace() { snapshot = new Snapshot(); } @Override public synchronized boolean printStackTrace(final PrintWriter writer) { final Snapshot snapshotRef = this.snapshot; if (snapshotRef == null) { return false; } final String message; if (dateFormat == null) { message = messageFormat; } else { synchronized (dateFormat) { message = dateFormat.format(Long.valueOf(snapshotRef.timestampMillis)); } } writer.println(message); snapshotRef.printStackTrace(writer); return true; } }
5,283
0
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3/impl/EvictionConfig.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.impl; import java.time.Duration; /** * This class is used by pool implementations to pass configuration information * to {@link EvictionPolicy} instances. The {@link EvictionPolicy} may also have * its own specific configuration attributes. * <p> * This class is immutable and thread-safe. * </p> * * @since 2.0 */ public class EvictionConfig { private static final Duration MAX_DURATION = Duration.ofMillis(Long.MAX_VALUE); private final Duration idleEvictDuration; private final Duration idleSoftEvictDuration; private final int minIdle; /** * Creates a new eviction configuration with the specified parameters. * Instances are immutable. * * @param idleEvictDuration Expected to be provided by * {@link BaseGenericObjectPool#getMinEvictableIdleDuration()} * @param idleSoftEvictDuration Expected to be provided by * {@link BaseGenericObjectPool#getSoftMinEvictableIdleDuration()} * @param minIdle Expected to be provided by * {@link GenericObjectPool#getMinIdle()} or * {@link GenericKeyedObjectPool#getMinIdlePerKey()} * @since 2.10.0 */ public EvictionConfig(final Duration idleEvictDuration, final Duration idleSoftEvictDuration, final int minIdle) { this.idleEvictDuration = PoolImplUtils.isPositive(idleEvictDuration) ? idleEvictDuration : MAX_DURATION; this.idleSoftEvictDuration = PoolImplUtils.isPositive(idleSoftEvictDuration) ? idleSoftEvictDuration : MAX_DURATION; this.minIdle = minIdle; } /** * Gets the {@code idleEvictTime} for this eviction configuration * instance. * <p> * How the evictor behaves based on this value will be determined by the * configured {@link EvictionPolicy}. * </p> * * @return The {@code idleEvictTime}. * @since 2.11.0 */ public Duration getIdleEvictDuration() { return idleEvictDuration; } /** * Gets the {@code idleSoftEvictTime} for this eviction configuration * instance. * <p> * How the evictor behaves based on this value will be determined by the * configured {@link EvictionPolicy}. * </p> * * @return The (@code idleSoftEvictTime} in milliseconds * @since 2.11.0 */ public Duration getIdleSoftEvictDuration() { return idleSoftEvictDuration; } /** * Gets the {@code minIdle} for this eviction configuration instance. * <p> * How the evictor behaves based on this value will be determined by the * configured {@link EvictionPolicy}. * </p> * * @return The {@code minIdle} */ public int getMinIdle() { return minIdle; } /** * @since 2.4 */ @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("EvictionConfig [idleEvictDuration="); builder.append(idleEvictDuration); builder.append(", idleSoftEvictDuration="); builder.append(idleSoftEvictDuration); builder.append(", minIdle="); builder.append(minIdle); builder.append("]"); return builder.toString(); } }
5,284
0
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3/impl/DefaultPooledObjectInfoMBean.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.impl; /** * The interface that defines the information about pooled objects that will be exposed via JMX. * <h2>Note</h2> * <p> * This interface exists only to define those attributes and methods that will be made available via JMX. It must not be implemented by clients as it is subject * to change between major, minor and patch version releases of commons pool. Clients that implement this interface may not, therefore, be able to upgrade to a * new minor or patch release without requiring code changes. * </p> * * @since 2.0 */ public interface DefaultPooledObjectInfoMBean { /** * Gets the number of times this object has been borrowed. * * @return The number of times this object has been borrowed. * @since 2.1 */ long getBorrowedCount(); /** * Gets the time (using the same basis as {@link java.time.Clock#instant()}) that pooled object was created. * * @return The creation time for the pooled object. */ long getCreateTime(); /** * Gets the time that pooled object was created. * * @return The creation time for the pooled object formatted as {@code yyyy-MM-dd HH:mm:ss Z}. */ String getCreateTimeFormatted(); /** * Gets the time (using the same basis as {@link java.time.Clock#instant()}) the polled object was last borrowed. * * @return The time the pooled object was last borrowed. */ long getLastBorrowTime(); /** * Gets the time that pooled object was last borrowed. * * @return The last borrowed time for the pooled object formatted as {@code yyyy-MM-dd HH:mm:ss Z}. */ String getLastBorrowTimeFormatted(); /** * Gets the stack trace recorded when the pooled object was last borrowed. * * @return The stack trace showing which code last borrowed the pooled object. */ String getLastBorrowTrace(); /** * Gets the time (using the same basis as {@link java.time.Clock#instant()})the wrapped object was last returned. * * @return The time the object was last returned. */ long getLastReturnTime(); /** * Gets the time that pooled object was last returned. * * @return The last returned time for the pooled object formatted as {@code yyyy-MM-dd HH:mm:ss Z}. */ String getLastReturnTimeFormatted(); /** * Gets a String form of the wrapper for debug purposes. The format is not fixed and may change at any time. * * @return A string representation of the pooled object. * * @see Object#toString() */ String getPooledObjectToString(); /** * Gets the name of the class of the pooled object. * * @return The pooled object's class name. * * @see Class#getName() */ String getPooledObjectType(); }
5,285
0
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3/impl/InterruptibleReentrantLock.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.impl; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; /** * This sub-class was created to expose the waiting threads so that they can be * interrupted when the pool using the queue that uses this lock is closed. The * class is intended for internal use only. * <p> * This class is intended to be thread-safe. * </p> * * @since 2.0 */ final class InterruptibleReentrantLock extends ReentrantLock { private static final long serialVersionUID = 1L; /** * Constructs a new InterruptibleReentrantLock with the given fairness policy. * * @param fairness true means threads should acquire contended locks as if * waiting in a FIFO queue */ public InterruptibleReentrantLock(final boolean fairness) { super(fairness); } /** * Interrupts the threads that are waiting on a specific condition * * @param condition the condition on which the threads are waiting. */ public void interruptWaiters(final Condition condition) { getWaitingThreads(condition).forEach(Thread::interrupt); } }
5,286
0
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3/impl/GenericKeyedObjectPoolMXBean.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.impl; import java.util.List; import java.util.Map; /** * Defines the methods that will be made available via JMX. * <h2>Note</h2> * <p> * This interface exists only to define those attributes and methods that will be made available via JMX. It must not be implemented by clients as it is subject * to change between major, minor and patch version releases of commons pool. Clients that implement this interface may not, therefore, be able to upgrade to a * new minor or patch release without requiring code changes. * </p> * * @param <K> The type of keys maintained by the pool. * * @since 2.0 */ public interface GenericKeyedObjectPoolMXBean<K> { // Expose getters for configuration settings /** * See {@link GenericKeyedObjectPool#getBlockWhenExhausted()}. * * @return See {@link GenericKeyedObjectPool#getBlockWhenExhausted()}. */ boolean getBlockWhenExhausted(); /** * See {@link GenericKeyedObjectPool#getBorrowedCount()}. * * @return See {@link GenericKeyedObjectPool#getBorrowedCount()}. */ long getBorrowedCount(); /** * See {@link GenericKeyedObjectPool#getCreatedCount()}. * * @return See {@link GenericKeyedObjectPool#getCreatedCount()}. */ long getCreatedCount(); /** * See {@link GenericKeyedObjectPool#getCreationStackTrace()}. * * @return See {@link GenericKeyedObjectPool#getCreationStackTrace()}. */ String getCreationStackTrace(); /** * See {@link GenericKeyedObjectPool#getDestroyedByBorrowValidationCount()}. * * @return See {@link GenericKeyedObjectPool#getDestroyedByBorrowValidationCount()}. */ long getDestroyedByBorrowValidationCount(); /** * See {@link GenericKeyedObjectPool#getDestroyedByEvictorCount()}. * * @return See {@link GenericKeyedObjectPool#getDestroyedByEvictorCount()}. */ long getDestroyedByEvictorCount(); /** * See {@link GenericKeyedObjectPool#getDestroyedCount()}. * * @return See {@link GenericKeyedObjectPool#getDestroyedCount()}. */ long getDestroyedCount(); /** * See {@link GenericKeyedObjectPool#getFairness()}. * * @return See {@link GenericKeyedObjectPool#getFairness()}. */ boolean getFairness(); /** * See {@link GenericKeyedObjectPool#getLifo()}. * * @return See {@link GenericKeyedObjectPool#getLifo()}. */ boolean getLifo(); /** * See {@link GenericKeyedObjectPool#getLogAbandoned()}. * * @return See {@link GenericKeyedObjectPool#getLogAbandoned()}. * @since 2.10.0 */ default boolean getLogAbandoned() { return false; } /** * See {@link GenericKeyedObjectPool#getMaxBorrowWaitTimeMillis()}. * * @return See {@link GenericKeyedObjectPool#getMaxBorrowWaitTimeMillis()}. */ long getMaxBorrowWaitTimeMillis(); /** * See {@link GenericKeyedObjectPool#getMaxIdlePerKey()}. * * @return See {@link GenericKeyedObjectPool#getMaxIdlePerKey()}. */ int getMaxIdlePerKey(); /** * See {@link GenericKeyedObjectPool#getMaxTotal()}. * * @return See {@link GenericKeyedObjectPool#getMaxTotal()}. */ int getMaxTotal(); /** * See {@link GenericKeyedObjectPool#getMaxTotalPerKey()}. * * @return See {@link GenericKeyedObjectPool#getMaxTotalPerKey()}. */ int getMaxTotalPerKey(); /** * See {@link GenericKeyedObjectPool#getMaxWaitDuration()}. * * @return See {@link GenericKeyedObjectPool#getMaxWaitDuration()}. */ long getMaxWaitMillis(); /** * See {@link GenericKeyedObjectPool#getMeanActiveTimeMillis()}. * * @return See {@link GenericKeyedObjectPool#getMeanActiveTimeMillis()}. */ long getMeanActiveTimeMillis(); /** * See {@link GenericKeyedObjectPool#getMaxBorrowWaitTimeMillis()}. * * @return See {@link GenericKeyedObjectPool#getMaxBorrowWaitTimeMillis()}. */ long getMeanBorrowWaitTimeMillis(); /** * See {@link GenericKeyedObjectPool#getMeanIdleTimeMillis()}. * * @return See {@link GenericKeyedObjectPool#getMeanIdleTimeMillis()}. */ long getMeanIdleTimeMillis(); /** * See {@link GenericKeyedObjectPool#getMinEvictableIdleDuration()}. * * @return See {@link GenericKeyedObjectPool#getMinEvictableIdleDuration()}. */ long getMinEvictableIdleTimeMillis(); // Expose getters for monitoring attributes /** * See {@link GenericKeyedObjectPool#getMinIdlePerKey()}. * * @return See {@link GenericKeyedObjectPool#getMinIdlePerKey()}. */ int getMinIdlePerKey(); /** * See {@link GenericKeyedObjectPool#getNumActive()}. * * @return See {@link GenericKeyedObjectPool#getNumActive()}. */ int getNumActive(); /** * See {@link GenericKeyedObjectPool#getNumActivePerKey()}. * * @return See {@link GenericKeyedObjectPool#getNumActivePerKey()}. */ Map<String, Integer> getNumActivePerKey(); /** * See {@link GenericKeyedObjectPool#getNumIdle()}. * * @return See {@link GenericKeyedObjectPool#getNumIdle()}. */ int getNumIdle(); /** * See {@link GenericKeyedObjectPool#getNumTestsPerEvictionRun()}. * * @return See {@link GenericKeyedObjectPool#getNumTestsPerEvictionRun()}. */ int getNumTestsPerEvictionRun(); /** * See {@link GenericKeyedObjectPool#getNumWaiters()}. * * @return See {@link GenericKeyedObjectPool#getNumWaiters()}. */ int getNumWaiters(); /** * See {@link GenericKeyedObjectPool#getNumWaitersByKey()}. * * @return See {@link GenericKeyedObjectPool#getNumWaitersByKey()}. */ Map<String, Integer> getNumWaitersByKey(); /** * See {@link GenericKeyedObjectPool#getRemoveAbandonedOnBorrow()}. * * @return See {@link GenericKeyedObjectPool#getRemoveAbandonedOnBorrow()}. * @since 2.10.0 */ default boolean getRemoveAbandonedOnBorrow() { return false; } /** * See {@link GenericKeyedObjectPool#getRemoveAbandonedOnMaintenance()}. * * @return See {@link GenericKeyedObjectPool#getRemoveAbandonedOnMaintenance()}. * @since 2.10.0 */ default boolean getRemoveAbandonedOnMaintenance() { return false; } /** * See {@link GenericKeyedObjectPool#getRemoveAbandonedTimeoutDuration()}. * * @return See {@link GenericKeyedObjectPool#getRemoveAbandonedTimeoutDuration()}. * @since 2.10.0 */ default int getRemoveAbandonedTimeout() { return 0; } /** * See {@link GenericKeyedObjectPool#getReturnedCount()}. * * @return See {@link GenericKeyedObjectPool#getReturnedCount()}. */ long getReturnedCount(); /** * See {@link GenericKeyedObjectPool#getTestOnBorrow()}. * * @return See {@link GenericKeyedObjectPool#getTestOnBorrow()}. */ boolean getTestOnBorrow(); /** * See {@link GenericKeyedObjectPool#getTestOnCreate()}. * * @return See {@link GenericKeyedObjectPool#getTestOnCreate()}. * @since 2.2 */ boolean getTestOnCreate(); /** * See {@link GenericKeyedObjectPool#getTestOnReturn()}. * * @return See {@link GenericKeyedObjectPool#getTestOnReturn()}. */ boolean getTestOnReturn(); /** * See {@link GenericKeyedObjectPool#getTestWhileIdle()}. * * @return See {@link GenericKeyedObjectPool#getTestWhileIdle()}. */ boolean getTestWhileIdle(); /** * See {@link GenericKeyedObjectPool#getDurationBetweenEvictionRuns} * * @return See {@link GenericKeyedObjectPool#getDurationBetweenEvictionRuns()}. */ long getTimeBetweenEvictionRunsMillis(); /** * See {@link GenericKeyedObjectPool#isAbandonedConfig()}. * * @return See {@link GenericKeyedObjectPool#isAbandonedConfig()}. * @since 2.10.0 */ default boolean isAbandonedConfig() { return false; } /** * See {@link GenericKeyedObjectPool#isClosed()}. * * @return See {@link GenericKeyedObjectPool#isClosed()}. */ boolean isClosed(); /** * See {@link GenericKeyedObjectPool#listAllObjects()}. * * @return See {@link GenericKeyedObjectPool#listAllObjects()}. */ Map<String, List<DefaultPooledObjectInfo>> listAllObjects(); }
5,287
0
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3/impl/SoftReferenceObjectPool.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.impl; import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.lang.ref.SoftReference; import java.util.ArrayList; import java.util.Collection; import java.util.NoSuchElementException; import java.util.Objects; import java.util.Optional; import org.apache.commons.pool3.BaseObjectPool; import org.apache.commons.pool3.ObjectPool; import org.apache.commons.pool3.PoolUtils; import org.apache.commons.pool3.PooledObjectFactory; /** * A {@link java.lang.ref.SoftReference SoftReference} based {@link ObjectPool}. * <p> * This class is intended to be thread-safe. * </p> * * @param <T> * Type of element pooled in this pool. * @param <E> * Type of exception thrown by this pool. * * @since 2.0 */ public class SoftReferenceObjectPool<T, E extends Exception> extends BaseObjectPool<T, E> { /** Factory to source pooled objects. */ private final PooledObjectFactory<T, E> factory; /** * Queue of broken references that might be able to be removed from * {@code _pool}. This is used to help {@link #getNumIdle()} be more * accurate with minimal performance overhead. */ private final ReferenceQueue<T> refQueue = new ReferenceQueue<>(); /** Count of instances that have been checkout out to pool clients */ private int numActive; // @GuardedBy("this") /** Total number of instances that have been destroyed */ private long destroyCount; // @GuardedBy("this") /** Total number of instances that have been created */ private long createCount; // @GuardedBy("this") /** Idle references - waiting to be borrowed */ private final LinkedBlockingDeque<PooledSoftReference<T>> idleReferences = new LinkedBlockingDeque<>(); /** All references - checked out or waiting to be borrowed. */ private final ArrayList<PooledSoftReference<T>> allReferences = new ArrayList<>(); /** * Constructs a {@code SoftReferenceObjectPool} with the specified factory. * * @param factory non-null object factory to use. */ public SoftReferenceObjectPool(final PooledObjectFactory<T, E> factory) { this.factory = Objects.requireNonNull(factory, "factory"); } /** * Creates an object, and places it into the pool. addObject() is useful for * "pre-loading" a pool with idle objects. * <p> * Before being added to the pool, the newly created instance is * {@link PooledObjectFactory#validateObject( * org.apache.commons.pool3.PooledObject) validated} and * {@link PooledObjectFactory#passivateObject( * org.apache.commons.pool3.PooledObject) passivated}. If * validation fails, the new instance is * {@link PooledObjectFactory#destroyObject( * org.apache.commons.pool3.PooledObject) destroyed}. Exceptions * generated by the factory {@code makeObject} or * {@code passivate} are propagated to the caller. Exceptions * destroying instances are silently swallowed. * </p> * * @throws IllegalStateException * if invoked on a {@link #close() closed} pool * @throws E * when the {@link #getFactory() factory} has a problem creating * or passivating an object. */ @Override public synchronized void addObject() throws E { assertOpen(); final T obj = factory.makeObject().getObject(); createCount++; // Create and register with the queue final PooledSoftReference<T> ref = new PooledSoftReference<>(new SoftReference<>(obj, refQueue)); allReferences.add(ref); boolean success = true; if (!factory.validateObject(ref)) { success = false; } else { factory.passivateObject(ref); } final boolean shouldDestroy = !success; if (success) { idleReferences.add(ref); notifyAll(); // numActive has changed } if (shouldDestroy) { try { destroy(ref); } catch (final Exception ignored) { // ignored } } } /** * Borrows an object from the pool. If there are no idle instances available * in the pool, the configured factory's * {@link PooledObjectFactory#makeObject()} method is invoked to create a * new instance. * <p> * All instances are {@link PooledObjectFactory#activateObject( * org.apache.commons.pool3.PooledObject) activated} * and {@link PooledObjectFactory#validateObject( * org.apache.commons.pool3.PooledObject) * validated} before being returned by this method. If validation fails or * an exception occurs activating or validating an idle instance, the * failing instance is {@link PooledObjectFactory#destroyObject( * org.apache.commons.pool3.PooledObject) * destroyed} and another instance is retrieved from the pool, validated and * activated. This process continues until either the pool is empty or an * instance passes validation. If the pool is empty on activation or it does * not contain any valid instances, the factory's {@code makeObject} * method is used to create a new instance. If the created instance either * raises an exception on activation or fails validation, * {@code NoSuchElementException} is thrown. Exceptions thrown by * {@code MakeObject} are propagated to the caller; but other than * {@code ThreadDeath} or {@code VirtualMachineError}, exceptions * generated by activation, validation or destroy methods are swallowed * silently. * </p> * * @throws NoSuchElementException * if a valid object cannot be provided * @throws IllegalStateException * if invoked on a {@link #close() closed} pool * @throws E * if an exception occurs creating a new instance * @return a valid, activated object instance */ @SuppressWarnings("null") // ref cannot be null @Override public synchronized T borrowObject() throws E { assertOpen(); T obj = null; boolean newlyCreated = false; PooledSoftReference<T> ref = null; while (null == obj) { if (idleReferences.isEmpty()) { newlyCreated = true; obj = factory.makeObject().getObject(); createCount++; // Do not register with the queue ref = new PooledSoftReference<>(new SoftReference<>(obj)); allReferences.add(ref); } else { ref = idleReferences.pollFirst(); obj = ref.getObject(); // Clear the reference so it will not be queued, but replace with a // a new, non-registered reference so we can still track this object // in allReferences ref.getReference().clear(); ref.setReference(new SoftReference<>(obj)); } if (null != obj) { try { factory.activateObject(ref); if (!factory.validateObject(ref)) { throw new Exception("ValidateObject failed"); } } catch (final Throwable t) { PoolUtils.checkRethrow(t); try { destroy(ref); } catch (final Throwable t2) { PoolUtils.checkRethrow(t2); // Swallowed } finally { obj = null; } if (newlyCreated) { throw new NoSuchElementException("Could not create a validated object, cause: " + t); } } } } numActive++; ref.allocate(); return obj; } /** * Clears any objects sitting idle in the pool. */ @Override public synchronized void clear() { idleReferences.forEach(pooledSoftRef -> { try { if (null != pooledSoftRef.getObject()) { factory.destroyObject(pooledSoftRef); } } catch (final Exception ignored) { // ignored, keep destroying the rest } }); idleReferences.clear(); pruneClearedReferences(); } /** * Closes this pool, and frees any resources associated with it. Invokes * {@link #clear()} to destroy and remove instances in the pool. * <p> * Calling {@link #addObject} or {@link #borrowObject} after invoking this * method on a pool will cause them to throw an * {@link IllegalStateException}. * </p> */ @Override public void close() { super.close(); clear(); } /** * Destroys a {@code PooledSoftReference} and removes it from the idle and all * references pools. * * @param toDestroy PooledSoftReference to destroy * * @throws E If an error occurs while trying to destroy the object */ private void destroy(final PooledSoftReference<T> toDestroy) throws E { toDestroy.invalidate(); idleReferences.remove(toDestroy); allReferences.remove(toDestroy); try { factory.destroyObject(toDestroy); } finally { destroyCount++; toDestroy.getReference().clear(); } } /** * Finds the PooledSoftReference in allReferences that points to obj. * * @param obj returning object * @return PooledSoftReference wrapping a soft reference to obj */ private PooledSoftReference<T> findReference(final T obj) { final Optional<PooledSoftReference<T>> first = allReferences.stream() .filter(reference -> Objects.equals(reference.getObject(), obj)).findFirst(); return first.orElse(null); } /** * Gets the {@link PooledObjectFactory} used by this pool to create and * manage object instances. * * @return the factory */ public synchronized PooledObjectFactory<T, E> getFactory() { return factory; } /** * Gets the number of instances currently borrowed from this pool. * * @return the number of instances currently borrowed from this pool */ @Override public synchronized int getNumActive() { return numActive; } /** * Gets an approximation not less than the of the number of idle * instances in the pool. * * @return estimated number of idle instances in the pool */ @Override public synchronized int getNumIdle() { pruneClearedReferences(); return idleReferences.size(); } /** * {@inheritDoc} */ @Override public synchronized void invalidateObject(final T obj) throws E { final PooledSoftReference<T> ref = findReference(obj); if (ref == null) { throw new IllegalStateException("Object to invalidate is not currently part of this pool"); } destroy(ref); numActive--; notifyAll(); // numActive has changed } /** * If any idle objects were garbage collected, remove their * {@link Reference} wrappers from the idle object pool. */ private void pruneClearedReferences() { // Remove wrappers for enqueued references from idle and allReferences lists removeClearedReferences(idleReferences); removeClearedReferences(allReferences); while (refQueue.poll() != null) { // NOPMD } } /** * Clears cleared references from the collection. * * @param collection collection of idle/allReferences */ private void removeClearedReferences(final Collection<PooledSoftReference<T>> collection) { collection.removeIf(ref -> ref.getReference() == null || ref.getReference().isEnqueued()); } /** * Returns an instance to the pool after successful validation and * passivation. The returning instance is destroyed if any of the following * are true: * <ul> * <li>the pool is closed</li> * <li>{@link PooledObjectFactory#validateObject( * org.apache.commons.pool3.PooledObject) validation} fails * </li> * <li>{@link PooledObjectFactory#passivateObject( * org.apache.commons.pool3.PooledObject) passivation} * throws an exception</li> * </ul> * Exceptions passivating or destroying instances are silently swallowed. * Exceptions validating instances are propagated to the client. * * @param obj * instance to return to the pool * @throws IllegalArgumentException * if obj is not currently part of this pool */ @Override public synchronized void returnObject(final T obj) throws E { boolean success = !isClosed(); final PooledSoftReference<T> ref = findReference(obj); if (ref == null) { throw new IllegalStateException("Returned object not currently part of this pool"); } if (!factory.validateObject(ref)) { success = false; } else { try { factory.passivateObject(ref); } catch (final Exception e) { success = false; } } final boolean shouldDestroy = !success; numActive--; if (success) { // Deallocate and add to the idle instance pool ref.deallocate(); idleReferences.add(ref); } notifyAll(); // numActive has changed if (shouldDestroy) { try { destroy(ref); } catch (final Exception ignored) { // ignored } } } @Override protected void toStringAppendFields(final StringBuilder builder) { super.toStringAppendFields(builder); builder.append(", factory="); builder.append(factory); builder.append(", refQueue="); builder.append(refQueue); builder.append(", numActive="); builder.append(numActive); builder.append(", destroyCount="); builder.append(destroyCount); builder.append(", createCount="); builder.append(createCount); builder.append(", idleReferences="); builder.append(idleReferences); builder.append(", allReferences="); builder.append(allReferences); } }
5,288
0
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3/impl/GenericObjectPool.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.impl; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; import java.util.NoSuchElementException; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Collectors; import org.apache.commons.pool3.DestroyMode; import org.apache.commons.pool3.ObjectPool; import org.apache.commons.pool3.PoolUtils; import org.apache.commons.pool3.PooledObject; import org.apache.commons.pool3.PooledObjectFactory; import org.apache.commons.pool3.PooledObjectState; import org.apache.commons.pool3.SwallowedExceptionListener; import org.apache.commons.pool3.TrackedUse; import org.apache.commons.pool3.UsageTracking; /** * A configurable {@link ObjectPool} implementation. * <p> * When coupled with the appropriate {@link PooledObjectFactory}, * {@code GenericObjectPool} provides robust pooling functionality for * arbitrary objects. * </p> * <p> * Optionally, one may configure the pool to examine and possibly evict objects * as they sit idle in the pool and to ensure that a minimum number of idle * objects are available. This is performed by an "idle object eviction" thread, * which runs asynchronously. Caution should be used when configuring this * optional feature. Eviction runs contend with client threads for access to * objects in the pool, so if they run too frequently performance issues may * result. * </p> * <p> * The pool can also be configured to detect and remove "abandoned" objects, * i.e. objects that have been checked out of the pool but neither used nor * returned before the configured * {@link AbandonedConfig#getRemoveAbandonedTimeoutDuration() removeAbandonedTimeout}. * Abandoned object removal can be configured to happen when * {@code borrowObject} is invoked and the pool is close to starvation, or * it can be executed by the idle object evictor, or both. If pooled objects * implement the {@link TrackedUse} interface, their last use will be queried * using the {@code getLastUsed} method on that interface; otherwise * abandonment is determined by how long an object has been checked out from * the pool. * </p> * <p> * Implementation note: To prevent possible deadlocks, care has been taken to * ensure that no call to a factory method will occur within a synchronization * block. See POOL-125 and DBCP-44 for more information. * </p> * <p> * This class is intended to be thread-safe. * </p> * * @see GenericKeyedObjectPool * * @param <T> Type of element pooled in this pool. * @param <E> Type of exception thrown in this pool. * * @since 2.0 */ public class GenericObjectPool<T, E extends Exception> extends BaseGenericObjectPool<T, E> implements ObjectPool<T, E>, GenericObjectPoolMXBean, UsageTracking<T> { // JMX specific attributes private static final String ONAME_BASE = "org.apache.commons.pool3:type=GenericObjectPool,name="; private static void wait(final Object obj, final Duration duration) throws InterruptedException { obj.wait(duration.toMillis(), duration.getNano() % 1_000_000); } private volatile String factoryType; private volatile int maxIdle = GenericObjectPoolConfig.DEFAULT_MAX_IDLE; private volatile int minIdle = GenericObjectPoolConfig.DEFAULT_MIN_IDLE; private final PooledObjectFactory<T, E> factory; /* * All of the objects currently associated with this pool in any state. It * excludes objects that have been destroyed. The size of * {@link #allObjects} will always be less than or equal to {@link * #_maxActive}. Map keys are pooled objects, values are the PooledObject * wrappers used internally by the pool. */ private final ConcurrentHashMap<IdentityWrapper<T>, PooledObject<T>> allObjects = new ConcurrentHashMap<>(); /* * The combined count of the currently created objects and those in the * process of being created. Under load, it may exceed {@link #_maxActive} * if multiple threads try and create a new object at the same time but * {@link #create()} will ensure that there are never more than * {@link #_maxActive} objects created at any one time. */ private final AtomicLong createCount = new AtomicLong(); private long makeObjectCount; private final Object makeObjectCountLock = new Object(); private final LinkedBlockingDeque<PooledObject<T>> idleObjects; /** * Creates a new {@code GenericObjectPool} using defaults from * {@link GenericObjectPoolConfig}. * * @param factory The object factory to be used to create object instances * used by this pool */ public GenericObjectPool(final PooledObjectFactory<T, E> factory) { this(factory, new GenericObjectPoolConfig<>()); } /** * Creates a new {@code GenericObjectPool} using a specific * configuration. * * @param factory The object factory to be used to create object instances * used by this pool * @param config The configuration to use for this pool instance. The * configuration is used by value. Subsequent changes to * the configuration object will not be reflected in the * pool. */ public GenericObjectPool(final PooledObjectFactory<T, E> factory, final GenericObjectPoolConfig<T> config) { super(config, ONAME_BASE, config.getJmxNamePrefix()); if (factory == null) { jmxUnregister(); // tidy up throw new IllegalArgumentException("Factory may not be null"); } this.factory = factory; idleObjects = new LinkedBlockingDeque<>(config.getFairness()); setConfig(config); } /** * Creates a new {@code GenericObjectPool} that tracks and destroys * objects that are checked out, but never returned to the pool. * * @param factory The object factory to be used to create object instances * used by this pool * @param config The base pool configuration to use for this pool instance. * The configuration is used by value. Subsequent changes to * the configuration object will not be reflected in the * pool. * @param abandonedConfig Configuration for abandoned object identification * and removal. The configuration is used by value. */ public GenericObjectPool(final PooledObjectFactory<T, E> factory, final GenericObjectPoolConfig<T> config, final AbandonedConfig abandonedConfig) { this(factory, config); setAbandonedConfig(abandonedConfig); } /** * 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 E If the factory fails to passivate the object */ private void addIdleObject(final PooledObject<T> p) throws E { if (!PooledObject.isNull(p)) { factory.passivateObject(p); if (getLifo()) { idleObjects.addFirst(p); } else { idleObjects.addLast(p); } } } /** * 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> * <p> * If the factory returns null when creating an object, a {@code NullPointerException} * is thrown. If there is no factory set (factory == null), an {@code IllegalStateException} * is thrown. * </p> * */ @Override public void addObject() throws E { assertOpen(); if (factory == null) { throw new IllegalStateException("Cannot add objects without a factory."); } addIdleObject(create()); } /** * Equivalent to <code>{@link #borrowObject(long) * borrowObject}({@link #getMaxWaitDuration()})</code>. * * {@inheritDoc} */ @Override public T borrowObject() throws E { return borrowObject(getMaxWaitDuration()); } /** * Borrows an object from the pool using the specific waiting time which only * applies if {@link #getBlockWhenExhausted()} is true. * <p> * If there is one or more idle instance available in the pool, then an * idle instance will be selected based on the value of {@link #getLifo()}, * activated and returned. If activation fails, or {@link #getTestOnBorrow() * testOnBorrow} is set to {@code true} and validation fails, the * instance is destroyed and the next available instance is examined. This * continues until either a valid instance is returned or there are no more * idle instances available. * </p> * <p> * If there are no idle instances available in the pool, behavior depends on * the {@link #getMaxTotal() maxTotal}, (if applicable) * {@link #getBlockWhenExhausted()} and the value passed in to the * {@code borrowMaxWaitMillis} parameter. If the number of instances * checked out from the pool is less than {@code maxTotal,} a new * instance is created, activated and (if applicable) validated and returned * to the caller. If validation fails, a {@code NoSuchElementException} * is thrown. If the factory returns null when creating an instance, * a {@code NullPointerException} is thrown. * </p> * <p> * If the pool is exhausted (no available idle instances and no capacity to * create new ones), this method will either block (if * {@link #getBlockWhenExhausted()} is true) or throw a * {@code NoSuchElementException} (if * {@link #getBlockWhenExhausted()} is false). The length of time that this * method will block when {@link #getBlockWhenExhausted()} is true is * determined by the value passed in to the {@code borrowMaxWaitMillis} * parameter. * </p> * <p> * When the pool is exhausted, multiple calling threads may be * simultaneously blocked waiting for instances to become available. A * "fairness" algorithm has been implemented to ensure that threads receive * available instances in request arrival order. * </p> * * @param borrowMaxWaitDuration The time to wait for an object * to become available * * @return object instance from the pool * @throws NoSuchElementException if an instance cannot be returned * @throws E if an object instance cannot be returned due to an error * @since 2.10.0 */ public T borrowObject(final Duration borrowMaxWaitDuration) throws E { assertOpen(); final AbandonedConfig ac = this.abandonedConfig; if (ac != null && ac.getRemoveAbandonedOnBorrow() && getNumIdle() < 2 && getNumActive() > getMaxTotal() - 3) { removeAbandoned(ac); } PooledObject<T> p = null; // Get local copy of current config so it is consistent for entire // method execution final boolean blockWhenExhausted = getBlockWhenExhausted(); boolean create; final Instant waitTime = Instant.now(); while (p == null) { create = false; p = idleObjects.pollFirst(); if (p == null) { p = create(); if (!PooledObject.isNull(p)) { create = true; } } if (blockWhenExhausted) { if (PooledObject.isNull(p)) { try { p = borrowMaxWaitDuration.isNegative() ? idleObjects.takeFirst() : idleObjects.pollFirst(borrowMaxWaitDuration); } catch (final InterruptedException e) { // Don't surface exception type of internal locking mechanism. throw cast(e); } } if (PooledObject.isNull(p)) { throw new NoSuchElementException(appendStats( "Timeout waiting for idle object, borrowMaxWaitDuration=" + borrowMaxWaitDuration)); } } else if (PooledObject.isNull(p)) { throw new NoSuchElementException(appendStats("Pool exhausted")); } if (!p.allocate()) { p = null; } if (!PooledObject.isNull(p)) { try { factory.activateObject(p); } catch (final Exception e) { try { destroy(p, DestroyMode.NORMAL); } catch (final Exception ignored) { // ignored - activation failure is more important } p = null; if (create) { final NoSuchElementException nsee = new NoSuchElementException( appendStats("Unable to activate object")); nsee.initCause(e); throw nsee; } } if (!PooledObject.isNull(p) && getTestOnBorrow()) { boolean validate = false; Throwable validationThrowable = null; try { validate = factory.validateObject(p); } catch (final Throwable t) { PoolUtils.checkRethrow(t); validationThrowable = t; } if (!validate) { try { destroy(p, DestroyMode.NORMAL); destroyedByBorrowValidationCount.incrementAndGet(); } catch (final Exception ignored) { // ignored - validation failure is more important } p = null; if (create) { final NoSuchElementException nsee = new NoSuchElementException( appendStats("Unable to validate object")); nsee.initCause(validationThrowable); throw nsee; } } } } } updateStatsBorrow(p, Duration.between(waitTime, Instant.now())); return p.getObject(); } /** * Borrows an object from the pool using the specific waiting time which only * applies if {@link #getBlockWhenExhausted()} is true. * <p> * If there is one or more idle instance available in the pool, then an * idle instance will be selected based on the value of {@link #getLifo()}, * activated and returned. If activation fails, or {@link #getTestOnBorrow() * testOnBorrow} is set to {@code true} and validation fails, the * instance is destroyed and the next available instance is examined. This * continues until either a valid instance is returned or there are no more * idle instances available. * </p> * <p> * If there are no idle instances available in the pool, behavior depends on * the {@link #getMaxTotal() maxTotal}, (if applicable) * {@link #getBlockWhenExhausted()} and the value passed in to the * {@code borrowMaxWaitMillis} parameter. If the number of instances * checked out from the pool is less than {@code maxTotal,} a new * instance is created, activated and (if applicable) validated and returned * to the caller. If validation fails, a {@code NoSuchElementException} * is thrown. If the factory returns null when creating an instance, * a {@code NullPointerException} is thrown. * </p> * <p> * If the pool is exhausted (no available idle instances and no capacity to * create new ones), this method will either block (if * {@link #getBlockWhenExhausted()} is true) or throw a * {@code NoSuchElementException} (if * {@link #getBlockWhenExhausted()} is false). The length of time that this * method will block when {@link #getBlockWhenExhausted()} is true is * determined by the value passed in to the {@code borrowMaxWaitMillis} * parameter. * </p> * <p> * When the pool is exhausted, multiple calling threads may be * simultaneously blocked waiting for instances to become available. A * "fairness" algorithm has been implemented to ensure that threads receive * available instances in request arrival order. * </p> * * @param borrowMaxWaitMillis The time to wait in milliseconds for an object * to become available * * @return object instance from the pool * * @throws NoSuchElementException if an instance cannot be returned * * @throws E if an object instance cannot be returned due to an * error */ public T borrowObject(final long borrowMaxWaitMillis) throws E { return borrowObject(Duration.ofMillis(borrowMaxWaitMillis)); } /** * Clears any objects sitting idle in the pool by removing them from the * idle instance pool and then invoking the configured * {@link PooledObjectFactory#destroyObject(PooledObject)} method on each * idle instance. * <p> * Implementation notes: * </p> * <ul> * <li>This method does not destroy or effect in any way instances that are * checked out of the pool when it is invoked.</li> * <li>Invoking this method does not prevent objects being returned to the * idle instance pool, even during its execution. Additional instances may * be returned while removed items are being destroyed.</li> * <li>Exceptions encountered destroying idle instances are swallowed * but notified via a {@link SwallowedExceptionListener}.</li> * </ul> */ @Override public void clear() { PooledObject<T> p = idleObjects.poll(); while (p != null) { try { destroy(p, DestroyMode.NORMAL); } catch (final Exception e) { swallowException(e); } p = idleObjects.poll(); } } /** * Closes the pool. Once the pool is closed, {@link #borrowObject()} will * fail with IllegalStateException, but {@link #returnObject(Object)} and * {@link #invalidateObject(Object)} will continue to work, with returned * objects destroyed on return. * <p> * Destroys idle instances in the pool by invoking {@link #clear()}. * </p> */ @Override public void close() { if (isClosed()) { return; } synchronized (closeLock) { if (isClosed()) { return; } // Stop the evictor before the pool is closed since evict() calls // assertOpen() stopEvictor(); closed = true; // This clear removes any idle objects clear(); jmxUnregister(); // Release any threads that were waiting for an object idleObjects.interuptTakeWaiters(); } } /** * Attempts to create a new wrapped pooled object. * <p> * If there are {@link #getMaxTotal()} objects already in circulation or in process of being created, this method * returns null. * </p> * <p> * If the factory makeObject returns null, this method throws a NullPointerException. * </p> * * @return The new wrapped pooled object or null. * @throws E if the object factory's {@code makeObject} fails */ private PooledObject<T> create() throws E { int localMaxTotal = getMaxTotal(); // This simplifies the code later in this method if (localMaxTotal < 0) { localMaxTotal = Integer.MAX_VALUE; } final Instant localStartInstant = Instant.now(); final Duration maxWaitDurationRaw = getMaxWaitDuration(); final Duration localMaxWaitDuration = maxWaitDurationRaw.isNegative() ? Duration.ZERO : maxWaitDurationRaw; // Flag that indicates if create should: // - TRUE: call the factory to create an object // - FALSE: return null // - null: loop and re-test the condition that determines whether to // call the factory Boolean create = null; while (create == null) { synchronized (makeObjectCountLock) { final long newCreateCount = createCount.incrementAndGet(); if (newCreateCount > localMaxTotal) { // The pool is currently at capacity or in the process of // making enough new objects to take it to capacity. createCount.decrementAndGet(); if (makeObjectCount == 0) { // There are no makeObject() calls in progress so the // pool is at capacity. Do not attempt to create a new // object. Return and wait for an object to be returned create = Boolean.FALSE; } else { // There are makeObject() calls in progress that might // bring the pool to capacity. Those calls might also // fail so wait until they complete and then re-test if // the pool is at capacity or not. try { wait(makeObjectCountLock, localMaxWaitDuration); } catch (final InterruptedException e) { // Don't surface exception type of internal locking mechanism. throw cast(e); } } } else { // The pool is not at capacity. Create a new object. makeObjectCount++; create = Boolean.TRUE; } } // Do not block more if maxWaitTimeMillis is set. if (create == null && localMaxWaitDuration.compareTo(Duration.ZERO) > 0 && Duration.between(localStartInstant, Instant.now()).compareTo(localMaxWaitDuration) >= 0) { create = Boolean.FALSE; } } if (!create.booleanValue()) { return null; } final PooledObject<T> p; try { p = factory.makeObject(); if (PooledObject.isNull(p)) { createCount.decrementAndGet(); throw new NullPointerException(String.format("%s.makeObject() = null", factory.getClass().getSimpleName())); } if (getTestOnCreate() && !factory.validateObject(p)) { createCount.decrementAndGet(); return null; } } catch (final Throwable e) { createCount.decrementAndGet(); throw e; } finally { synchronized (makeObjectCountLock) { makeObjectCount--; makeObjectCountLock.notifyAll(); } } final AbandonedConfig ac = this.abandonedConfig; if (ac != null && ac.getLogAbandoned()) { p.setLogAbandoned(true); p.setRequireFullStackTrace(ac.getRequireFullStackTrace()); } createdCount.incrementAndGet(); allObjects.put(IdentityWrapper.on(p), p); return p; } /** * Destroys a wrapped pooled object. * * @param toDestroy The wrapped pooled object to destroy * @param destroyMode DestroyMode context provided to the factory * * @throws E If the factory fails to destroy the pooled object * cleanly */ private void destroy(final PooledObject<T> toDestroy, final DestroyMode destroyMode) throws E { toDestroy.invalidate(); idleObjects.remove(toDestroy); allObjects.remove(IdentityWrapper.on(toDestroy)); try { factory.destroyObject(toDestroy, destroyMode); } finally { destroyedCount.incrementAndGet(); createCount.decrementAndGet(); } } /** * 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> * <p> * If the factory returns null when creating an instance, a {@code NullPointerException} * is thrown. * </p> * * @param idleCount the number of idle instances desired * @param always true means create instances even if the pool has no threads waiting * @throws E if the factory's makeObject throws */ private void ensureIdle(final int idleCount, final boolean always) throws E { if (idleCount < 1 || isClosed() || !always && !idleObjects.hasTakeWaiters()) { return; } while (idleObjects.size() < idleCount) { final PooledObject<T> p = create(); if (PooledObject.isNull(p)) { // 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(); } } @Override void ensureMinIdle() throws E { ensureIdle(getMinIdle(), true); } /** * {@inheritDoc} * <p> * Successive activations of this method examine objects in sequence, * cycling through objects in oldest-to-youngest order. * </p> */ @Override public void evict() throws E { assertOpen(); if (!idleObjects.isEmpty()) { PooledObject<T> underTest = null; final EvictionPolicy<T> evictionPolicy = getEvictionPolicy(); synchronized (evictionLock) { final EvictionConfig evictionConfig = new EvictionConfig( getMinEvictableIdleDuration(), getSoftMinEvictableIdleDuration(), getMinIdle()); final boolean testWhileIdle = getTestWhileIdle(); for (int i = 0, m = getNumTests(); i < m; i++) { if (evictionIterator == null || !evictionIterator.hasNext()) { evictionIterator = new EvictionIterator(idleObjects); } if (!evictionIterator.hasNext()) { // Pool exhausted, nothing to do here return; } try { underTest = evictionIterator.next(); } catch (final NoSuchElementException nsee) { // Object was borrowed in another thread // Don't count this as an eviction test so reduce i; i--; evictionIterator = null; continue; } if (!underTest.startEvictionTest()) { // Object was borrowed in another thread // Don't count this as an eviction test so reduce i; i--; continue; } // User provided eviction policy could throw all sorts of // crazy exceptions. Protect against such an exception // killing the eviction thread. boolean evict; try { evict = evictionPolicy.evict(evictionConfig, underTest, idleObjects.size()); } catch (final Throwable t) { // Slightly convoluted as SwallowedExceptionListener // uses Exception rather than Throwable PoolUtils.checkRethrow(t); swallowException(new Exception(t)); // Don't evict on error conditions evict = false; } if (evict) { destroy(underTest, DestroyMode.NORMAL); destroyedByEvictorCount.incrementAndGet(); } else { if (testWhileIdle) { boolean active = false; try { factory.activateObject(underTest); active = true; } catch (final Exception e) { destroy(underTest, DestroyMode.NORMAL); destroyedByEvictorCount.incrementAndGet(); } if (active) { boolean validate = false; Throwable validationThrowable = null; try { validate = factory.validateObject(underTest); } catch (final Throwable t) { PoolUtils.checkRethrow(t); validationThrowable = t; } if (!validate) { destroy(underTest, DestroyMode.NORMAL); destroyedByEvictorCount.incrementAndGet(); if (validationThrowable != null) { if (validationThrowable instanceof RuntimeException) { throw (RuntimeException) validationThrowable; } throw (Error) validationThrowable; } } else { try { factory.passivateObject(underTest); } catch (final Exception e) { destroy(underTest, DestroyMode.NORMAL); destroyedByEvictorCount.incrementAndGet(); } } } } underTest.endEvictionTest(idleObjects); // TODO - May need to add code here once additional // states are used } } } } final AbandonedConfig ac = this.abandonedConfig; if (ac != null && ac.getRemoveAbandonedOnMaintenance()) { removeAbandoned(ac); } } /** * Gets a reference to the factory used to create, destroy and validate * the objects used by this pool. * * @return the factory */ public PooledObjectFactory<T, E> getFactory() { return factory; } /** * Gets the type - including the specific type rather than the generic - * of the factory. * * @return A string representation of the factory type */ @Override public String getFactoryType() { // Not thread safe. Accept that there may be multiple evaluations. if (factoryType == null) { final StringBuilder result = new StringBuilder(); result.append(factory.getClass().getName()); result.append('<'); final Class<?> pooledObjectType = PoolImplUtils.getFactoryType(factory.getClass()); result.append(pooledObjectType.getName()); result.append('>'); factoryType = result.toString(); } return factoryType; } /** * Gets the cap on the number of "idle" instances in the pool. If maxIdle * is set too low on heavily loaded systems it is possible you will see * objects being destroyed and almost immediately new objects being created. * This is a result of the active threads momentarily returning objects * faster than they are requesting them, causing the number of idle * objects to rise above maxIdle. The best value for maxIdle for heavily * loaded system will vary but the default is a good starting point. * * @return the maximum number of "idle" instances that can be held in the * pool or a negative value if there is no limit * * @see #setMaxIdle */ @Override public int getMaxIdle() { return maxIdle; } /** * Gets the target for the minimum number of idle objects to maintain in * the pool. This setting only has an effect if it is positive and * {@link #getDurationBetweenEvictionRuns()} is greater than zero. If this * is the case, an attempt is made to ensure that the pool has the required * minimum number of instances during idle object eviction runs. * <p> * If the configured value of minIdle is greater than the configured value * for maxIdle then the value of maxIdle will be used instead. * </p> * * @return The minimum number of objects. * * @see #setMinIdle(int) * @see #setMaxIdle(int) * @see #setDurationBetweenEvictionRuns(Duration) */ @Override public int getMinIdle() { final int maxIdleSave = getMaxIdle(); return Math.min(this.minIdle, maxIdleSave); } @Override public int getNumActive() { return allObjects.size() - idleObjects.size(); } @Override public int getNumIdle() { return idleObjects.size(); } /** * Calculates the number of objects to test in a run of the idle object * evictor. * * @return The number of objects to test for validity */ private int getNumTests() { final int numTestsPerEvictionRun = getNumTestsPerEvictionRun(); if (numTestsPerEvictionRun >= 0) { return Math.min(numTestsPerEvictionRun, idleObjects.size()); } return (int) Math.ceil(idleObjects.size() / Math.abs((double) numTestsPerEvictionRun)); } /** * Gets an estimate of the number of threads currently blocked waiting for * an object from the pool. This is intended for monitoring only, not for * synchronization control. * * @return The estimate of the number of threads currently blocked waiting * for an object from the pool */ @Override public int getNumWaiters() { if (getBlockWhenExhausted()) { return idleObjects.getTakeQueueLength(); } return 0; } PooledObject<T> getPooledObject(final T obj) { return allObjects.get(new IdentityWrapper<>(obj)); } @Override String getStatsString() { // Simply listed in AB order. return super.getStatsString() + String.format(", createdCount=%,d, makeObjectCount=%,d, maxIdle=%,d, minIdle=%,d", createdCount.get(), makeObjectCount, maxIdle, minIdle); } /** * {@inheritDoc} * <p> * Activation of this method decrements the active count and attempts to destroy the instance, using the default * (NORMAL) {@link DestroyMode}. * </p> * * @throws E if an exception occurs destroying the * @throws IllegalStateException if obj does not belong to this pool */ @Override public void invalidateObject(final T obj) throws E { invalidateObject(obj, DestroyMode.NORMAL); } /** * {@inheritDoc} * <p> * Activation of this method decrements the active count and attempts to destroy the instance, using the provided * {@link DestroyMode}. * </p> * * @throws E if an exception occurs destroying the object * @throws IllegalStateException if obj does not belong to this pool * @since 2.9.0 */ @Override public void invalidateObject(final T obj, final DestroyMode destroyMode) throws E { final PooledObject<T> p = getPooledObject(obj); if (p == null) { if (isAbandonedConfig()) { return; } throw new IllegalStateException("Invalidated object not currently part of this pool"); } synchronized (p) { if (p.getState() != PooledObjectState.INVALID) { destroy(p, destroyMode); } } ensureIdle(1, false); } /** * Provides information on all the objects in the pool, both idle (waiting * to be borrowed) and active (currently borrowed). * <p> * Note: This is named listAllObjects so it is presented as an operation via * JMX. That means it won't be invoked unless the explicitly requested * whereas all attributes will be automatically requested when viewing the * attributes for an object in a tool like JConsole. * </p> * * @return Information grouped on all the objects in the pool */ @Override public Set<DefaultPooledObjectInfo> listAllObjects() { return allObjects.values().stream().map(DefaultPooledObjectInfo::new).collect(Collectors.toSet()); } /** * Tries to ensure that {@link #getMinIdle()} idle instances are available * in the pool. * * @throws E If the associated factory throws an exception * @since 2.4 */ public void preparePool() throws E { if (getMinIdle() < 1) { return; } ensureMinIdle(); } /** * Recovers abandoned objects which have been checked out but * not used since longer than the removeAbandonedTimeout. * * @param abandonedConfig The configuration to use to identify abandoned objects */ @SuppressWarnings("resource") // PrintWriter is managed elsewhere private void removeAbandoned(final AbandonedConfig abandonedConfig) { // Generate a list of abandoned objects to remove final ArrayList<PooledObject<T>> remove = createRemoveList(abandonedConfig, allObjects); // Now remove the abandoned objects remove.forEach(pooledObject -> { if (abandonedConfig.getLogAbandoned()) { pooledObject.printStackTrace(abandonedConfig.getLogWriter()); } try { invalidateObject(pooledObject.getObject(), DestroyMode.ABANDONED); } catch (final Exception e) { swallowException(e); } }); } /** * {@inheritDoc} * <p> * If {@link #getMaxIdle() maxIdle} is set to a positive value and the * number of idle instances has reached this value, the returning instance * is destroyed. * </p> * <p> * If {@link #getTestOnReturn() testOnReturn} == true, the returning * instance is validated before being returned to the idle instance pool. In * this case, if validation fails, the instance is destroyed. * </p> * <p> * Exceptions encountered destroying objects for any reason are swallowed * but notified via a {@link SwallowedExceptionListener}. * </p> */ @Override public void returnObject(final T obj) { final PooledObject<T> p = getPooledObject(obj); if (p == null) { if (!isAbandonedConfig()) { throw new IllegalStateException( "Returned object not currently part of this pool"); } return; // Object was abandoned and removed } markReturningState(p); final Duration activeTime = p.getActiveDuration(); if (getTestOnReturn() && !factory.validateObject(p)) { try { destroy(p, DestroyMode.NORMAL); } catch (final Exception e) { swallowException(e); } try { ensureIdle(1, false); } catch (final Exception e) { swallowException(e); } updateStatsReturn(activeTime); return; } try { factory.passivateObject(p); } catch (final Exception e1) { swallowException(e1); try { destroy(p, DestroyMode.NORMAL); } catch (final Exception e) { swallowException(e); } try { ensureIdle(1, false); } catch (final Exception e) { swallowException(e); } updateStatsReturn(activeTime); return; } if (!p.deallocate()) { throw new IllegalStateException( "Object has already been returned to this pool or is invalid"); } final int maxIdleSave = getMaxIdle(); if (isClosed() || maxIdleSave > -1 && maxIdleSave <= idleObjects.size()) { try { destroy(p, DestroyMode.NORMAL); } catch (final Exception e) { swallowException(e); } try { ensureIdle(1, false); } catch (final Exception e) { swallowException(e); } } else { 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(); } } updateStatsReturn(activeTime); } /** * Sets the base pool configuration. * * @param conf the new configuration to use. This is used by value. * * @see GenericObjectPoolConfig */ public void setConfig(final GenericObjectPoolConfig<T> conf) { super.setConfig(conf); setMaxIdle(conf.getMaxIdle()); setMinIdle(conf.getMinIdle()); setMaxTotal(conf.getMaxTotal()); } /** * Sets the cap on the number of "idle" instances in the pool. If maxIdle * is set too low on heavily loaded systems it is possible you will see * objects being destroyed and almost immediately new objects being created. * This is a result of the active threads momentarily returning objects * faster than they are requesting them, causing the number of idle * objects to rise above maxIdle. The best value for maxIdle for heavily * loaded system will vary but the default is a good starting point. * * @param maxIdle * The cap on the number of "idle" instances in the pool. Use a * negative value to indicate an unlimited number of idle * instances * * @see #getMaxIdle */ public void setMaxIdle(final int maxIdle) { this.maxIdle = maxIdle; } /** * Sets the target for the minimum number of idle objects to maintain in * the pool. This setting only has an effect if it is positive and * {@link #getDurationBetweenEvictionRuns()} is greater than zero. If this * is the case, an attempt is made to ensure that the pool has the required * minimum number of instances during idle object eviction runs. * <p> * If the configured value of minIdle is greater than the configured value * for maxIdle then the value of maxIdle will be used instead. * </p> * * @param minIdle * The minimum number of objects. * * @see #getMinIdle() * @see #getMaxIdle() * @see #getDurationBetweenEvictionRuns() */ public void setMinIdle(final int minIdle) { this.minIdle = minIdle; } @Override protected void toStringAppendFields(final StringBuilder builder) { super.toStringAppendFields(builder); builder.append(", factoryType="); builder.append(factoryType); builder.append(", maxIdle="); builder.append(maxIdle); builder.append(", minIdle="); builder.append(minIdle); builder.append(", factory="); builder.append(factory); builder.append(", allObjects="); builder.append(allObjects); builder.append(", createCount="); builder.append(createCount); builder.append(", idleObjects="); builder.append(idleObjects); builder.append(", abandonedConfig="); builder.append(abandonedConfig); } @Override public void use(final T pooledObject) { final AbandonedConfig abandonedCfg = this.abandonedConfig; if (abandonedCfg != null && abandonedCfg.getUseUsageTracking()) { final PooledObject<T> po = getPooledObject(pooledObject); if (po != null) { po.use(); } } } }
5,289
0
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3/impl/BaseObjectPoolConfig.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.impl; import java.time.Duration; import org.apache.commons.pool3.BaseObject; /** * Provides the implementation for the common attributes shared by the * sub-classes. New instances of this class will be created using the defaults * defined by the public constants. * <p> * This class is not thread-safe. * </p> * * @param <T> Type of element pooled. * @since 2.0 */ public abstract class BaseObjectPoolConfig<T> extends BaseObject implements Cloneable { /** * The default value for the {@code lifo} configuration attribute. * @see GenericObjectPool#getLifo() * @see GenericKeyedObjectPool#getLifo() */ public static final boolean DEFAULT_LIFO = true; /** * The default value for the {@code fairness} configuration attribute. * @see GenericObjectPool#getFairness() * @see GenericKeyedObjectPool#getFairness() */ public static final boolean DEFAULT_FAIRNESS = false; /** * The default value for the {@code maxWait} configuration attribute. * @see GenericObjectPool#getMaxWaitDuration() * @see GenericKeyedObjectPool#getMaxWaitDuration() * @since 2.10.0 */ public static final Duration DEFAULT_MAX_WAIT = Duration.ofMillis(-1L); /** * The default value for the {@code minEvictableIdleDuration} * configuration attribute. * @see GenericObjectPool#getMinEvictableIdleDuration() * @see GenericKeyedObjectPool#getMinEvictableIdleDuration() * @since 2.11.0 */ public static final Duration DEFAULT_MIN_EVICTABLE_IDLE_DURATION = Duration.ofMillis(1000L * 60L * 30L); /** * The default value for the {@code softMinEvictableIdleTime} * configuration attribute. * @see GenericObjectPool#getSoftMinEvictableIdleDuration() * @see GenericKeyedObjectPool#getSoftMinEvictableIdleDuration() * @since 2.11.0 */ public static final Duration DEFAULT_SOFT_MIN_EVICTABLE_IDLE_DURATION = Duration.ofMillis(-1); /** * The default value for {@code evictorShutdownTimeout} configuration * attribute. * @see GenericObjectPool#getEvictorShutdownTimeoutDuration() * @see GenericKeyedObjectPool#getEvictorShutdownTimeoutDuration() * @since 2.10.0 */ public static final Duration DEFAULT_EVICTOR_SHUTDOWN_TIMEOUT = Duration.ofMillis(10L * 1000L); /** * The default value for the {@code numTestsPerEvictionRun} configuration * attribute. * @see GenericObjectPool#getNumTestsPerEvictionRun() * @see GenericKeyedObjectPool#getNumTestsPerEvictionRun() */ public static final int DEFAULT_NUM_TESTS_PER_EVICTION_RUN = 3; /** * The default value for the {@code testOnCreate} configuration attribute. * @see GenericObjectPool#getTestOnCreate() * @see GenericKeyedObjectPool#getTestOnCreate() * * @since 2.2 */ public static final boolean DEFAULT_TEST_ON_CREATE = false; /** * The default value for the {@code testOnBorrow} configuration attribute. * @see GenericObjectPool#getTestOnBorrow() * @see GenericKeyedObjectPool#getTestOnBorrow() */ public static final boolean DEFAULT_TEST_ON_BORROW = false; /** * The default value for the {@code testOnReturn} configuration attribute. * @see GenericObjectPool#getTestOnReturn() * @see GenericKeyedObjectPool#getTestOnReturn() */ public static final boolean DEFAULT_TEST_ON_RETURN = false; /** * The default value for the {@code testWhileIdle} configuration attribute. * @see GenericObjectPool#getTestWhileIdle() * @see GenericKeyedObjectPool#getTestWhileIdle() */ public static final boolean DEFAULT_TEST_WHILE_IDLE = false; /** * The default value for the {@code timeBetweenEvictionRuns} * configuration attribute. * @see GenericObjectPool#getDurationBetweenEvictionRuns() * @see GenericKeyedObjectPool#getDurationBetweenEvictionRuns() */ public static final Duration DEFAULT_DURATION_BETWEEN_EVICTION_RUNS = Duration.ofMillis(-1L); /** * The default value for the {@code blockWhenExhausted} configuration * attribute. * @see GenericObjectPool#getBlockWhenExhausted() * @see GenericKeyedObjectPool#getBlockWhenExhausted() */ public static final boolean DEFAULT_BLOCK_WHEN_EXHAUSTED = true; /** * The default value for enabling JMX for pools created with a configuration * instance. */ public static final boolean DEFAULT_JMX_ENABLE = true; /** * The default value for the prefix used to name JMX enabled pools created * with a configuration instance. * @see GenericObjectPool#getJmxName() * @see GenericKeyedObjectPool#getJmxName() */ public static final String DEFAULT_JMX_NAME_PREFIX = "pool"; /** * The default value for the base name to use to name JMX enabled pools * created with a configuration instance. The default is {@code null} * which means the pool will provide the base name to use. * @see GenericObjectPool#getJmxName() * @see GenericKeyedObjectPool#getJmxName() */ public static final String DEFAULT_JMX_NAME_BASE = null; /** * The default value for the {@code evictionPolicyClassName} configuration * attribute. * @see GenericObjectPool#getEvictionPolicyClassName() * @see GenericKeyedObjectPool#getEvictionPolicyClassName() */ public static final String DEFAULT_EVICTION_POLICY_CLASS_NAME = DefaultEvictionPolicy.class.getName(); private boolean lifo = DEFAULT_LIFO; private boolean fairness = DEFAULT_FAIRNESS; private Duration maxWaitDuration = DEFAULT_MAX_WAIT; private Duration minEvictableIdleDuration = DEFAULT_MIN_EVICTABLE_IDLE_DURATION; private Duration evictorShutdownTimeoutDuration = DEFAULT_EVICTOR_SHUTDOWN_TIMEOUT; private Duration softMinEvictableIdleDuration = DEFAULT_SOFT_MIN_EVICTABLE_IDLE_DURATION; private int numTestsPerEvictionRun = DEFAULT_NUM_TESTS_PER_EVICTION_RUN; private EvictionPolicy<T> evictionPolicy; // Only 2.6.0 applications set this private String evictionPolicyClassName = DEFAULT_EVICTION_POLICY_CLASS_NAME; private boolean testOnCreate = DEFAULT_TEST_ON_CREATE; private boolean testOnBorrow = DEFAULT_TEST_ON_BORROW; private boolean testOnReturn = DEFAULT_TEST_ON_RETURN; private boolean testWhileIdle = DEFAULT_TEST_WHILE_IDLE; private Duration durationBetweenEvictionRuns = DEFAULT_DURATION_BETWEEN_EVICTION_RUNS; private boolean blockWhenExhausted = DEFAULT_BLOCK_WHEN_EXHAUSTED; private boolean jmxEnabled = DEFAULT_JMX_ENABLE; // TODO Consider changing this to a single property for 3.x private String jmxNamePrefix = DEFAULT_JMX_NAME_PREFIX; private String jmxNameBase = DEFAULT_JMX_NAME_BASE; /** * Gets the value for the {@code blockWhenExhausted} configuration attribute * for pools created with this configuration instance. * * @return The current setting of {@code blockWhenExhausted} for this * configuration instance * * @see GenericObjectPool#getBlockWhenExhausted() * @see GenericKeyedObjectPool#getBlockWhenExhausted() */ public boolean getBlockWhenExhausted() { return blockWhenExhausted; } /** * Gets the value for the {@code timeBetweenEvictionRuns} configuration * attribute for pools created with this configuration instance. * * @return The current setting of {@code timeBetweenEvictionRuns} for * this configuration instance * * @see GenericObjectPool#getDurationBetweenEvictionRuns() * @see GenericKeyedObjectPool#getDurationBetweenEvictionRuns() * @since 2.11.0 */ public Duration getDurationBetweenEvictionRuns() { return durationBetweenEvictionRuns; } /** * Gets the value for the {@code evictionPolicyClass} configuration * attribute for pools created with this configuration instance. * * @return The current setting of {@code evictionPolicyClass} for this * configuration instance * * @see GenericObjectPool#getEvictionPolicy() * @see GenericKeyedObjectPool#getEvictionPolicy() * @since 2.6.0 */ public EvictionPolicy<T> getEvictionPolicy() { return evictionPolicy; } /** * Gets the value for the {@code evictionPolicyClassName} configuration * attribute for pools created with this configuration instance. * * @return The current setting of {@code evictionPolicyClassName} for this * configuration instance * * @see GenericObjectPool#getEvictionPolicyClassName() * @see GenericKeyedObjectPool#getEvictionPolicyClassName() */ public String getEvictionPolicyClassName() { return evictionPolicyClassName; } /** * Gets the value for the {@code evictorShutdownTimeout} configuration * attribute for pools created with this configuration instance. * * @return The current setting of {@code evictorShutdownTimeout} for * this configuration instance * * @see GenericObjectPool#getEvictorShutdownTimeoutDuration() * @see GenericKeyedObjectPool#getEvictorShutdownTimeoutDuration() * @since 2.11.0 */ public Duration getEvictorShutdownTimeoutDuration() { return evictorShutdownTimeoutDuration; } /** * Gets the value for the {@code fairness} configuration attribute for pools * created with this configuration instance. * * @return The current setting of {@code fairness} for this configuration * instance * * @see GenericObjectPool#getFairness() * @see GenericKeyedObjectPool#getFairness() */ public boolean getFairness() { return fairness; } /** * Gets the value of the flag that determines if JMX will be enabled for * pools created with this configuration instance. * * @return The current setting of {@code jmxEnabled} for this configuration * instance */ public boolean getJmxEnabled() { return jmxEnabled; } /** * Gets the value of the JMX name base that will be used as part of the * name assigned to JMX enabled pools created with this configuration * instance. A value of {@code null} means that the pool will define * the JMX name base. * * @return The current setting of {@code jmxNameBase} for this * configuration instance */ public String getJmxNameBase() { return jmxNameBase; } /** * Gets the value of the JMX name prefix that will be used as part of the * name assigned to JMX enabled pools created with this configuration * instance. * * @return The current setting of {@code jmxNamePrefix} for this * configuration instance */ public String getJmxNamePrefix() { return jmxNamePrefix; } /** * Gets the value for the {@code lifo} configuration attribute for pools * created with this configuration instance. * * @return The current setting of {@code lifo} for this configuration * instance * * @see GenericObjectPool#getLifo() * @see GenericKeyedObjectPool#getLifo() */ public boolean getLifo() { return lifo; } /** * Gets the value for the {@code maxWait} configuration attribute for pools * created with this configuration instance. * * @return The current setting of {@code maxWait} for this * configuration instance * * @see GenericObjectPool#getMaxWaitDuration() * @see GenericKeyedObjectPool#getMaxWaitDuration() * @since 2.11.0 */ public Duration getMaxWaitDuration() { return maxWaitDuration; } /** * Gets the value for the {@code minEvictableIdleTime} configuration * attribute for pools created with this configuration instance. * * @return The current setting of {@code minEvictableIdleTime} for * this configuration instance * * @see GenericObjectPool#getMinEvictableIdleDuration() * @see GenericKeyedObjectPool#getMinEvictableIdleDuration() * @since 2.11.0 */ public Duration getMinEvictableIdleDuration() { return minEvictableIdleDuration; } /** * Gets the value for the {@code numTestsPerEvictionRun} configuration * attribute for pools created with this configuration instance. * * @return The current setting of {@code numTestsPerEvictionRun} for this * configuration instance * * @see GenericObjectPool#getNumTestsPerEvictionRun() * @see GenericKeyedObjectPool#getNumTestsPerEvictionRun() */ public int getNumTestsPerEvictionRun() { return numTestsPerEvictionRun; } /** * Gets the value for the {@code softMinEvictableIdleTime} * configuration attribute for pools created with this configuration * instance. * * @return The current setting of {@code softMinEvictableIdleTime} * for this configuration instance * * @see GenericObjectPool#getSoftMinEvictableIdleDuration() * @see GenericKeyedObjectPool#getSoftMinEvictableIdleDuration() * @since 2.11.0 */ public Duration getSoftMinEvictableIdleDuration() { return softMinEvictableIdleDuration; } /** * Gets the value for the {@code testOnBorrow} configuration attribute for * pools created with this configuration instance. * * @return The current setting of {@code testOnBorrow} for this * configuration instance * * @see GenericObjectPool#getTestOnBorrow() * @see GenericKeyedObjectPool#getTestOnBorrow() */ public boolean getTestOnBorrow() { return testOnBorrow; } /** * Gets the value for the {@code testOnCreate} configuration attribute for * pools created with this configuration instance. * * @return The current setting of {@code testOnCreate} for this * configuration instance * * @see GenericObjectPool#getTestOnCreate() * @see GenericKeyedObjectPool#getTestOnCreate() * * @since 2.2 */ public boolean getTestOnCreate() { return testOnCreate; } /** * Gets the value for the {@code testOnReturn} configuration attribute for * pools created with this configuration instance. * * @return The current setting of {@code testOnReturn} for this * configuration instance * * @see GenericObjectPool#getTestOnReturn() * @see GenericKeyedObjectPool#getTestOnReturn() */ public boolean getTestOnReturn() { return testOnReturn; } /** * Gets the value for the {@code testWhileIdle} configuration attribute for * pools created with this configuration instance. * * @return The current setting of {@code testWhileIdle} for this * configuration instance * * @see GenericObjectPool#getTestWhileIdle() * @see GenericKeyedObjectPool#getTestWhileIdle() */ public boolean getTestWhileIdle() { return testWhileIdle; } /** * Sets the value for the {@code blockWhenExhausted} configuration attribute * for pools created with this configuration instance. * * @param blockWhenExhausted The new setting of {@code blockWhenExhausted} * for this configuration instance * * @see GenericObjectPool#getBlockWhenExhausted() * @see GenericKeyedObjectPool#getBlockWhenExhausted() */ public void setBlockWhenExhausted(final boolean blockWhenExhausted) { this.blockWhenExhausted = blockWhenExhausted; } /** * Sets the value for the {@code timeBetweenEvictionRuns} configuration * attribute for pools created with this configuration instance. * * @param timeBetweenEvictionRuns The new setting of * {@code timeBetweenEvictionRuns} for this configuration * instance * * @see GenericObjectPool#getDurationBetweenEvictionRuns() * @see GenericKeyedObjectPool#getDurationBetweenEvictionRuns() * @since 2.10.0 */ public void setDurationBetweenEvictionRuns(final Duration timeBetweenEvictionRuns) { this.durationBetweenEvictionRuns = PoolImplUtils.nonNull(timeBetweenEvictionRuns, DEFAULT_DURATION_BETWEEN_EVICTION_RUNS); } /** * Sets the value for the {@code evictionPolicyClass} configuration * attribute for pools created with this configuration instance. * * @param evictionPolicy The new setting of * {@code evictionPolicyClass} for this configuration instance * * @see GenericObjectPool#getEvictionPolicy() * @see GenericKeyedObjectPool#getEvictionPolicy() * @since 2.6.0 */ public void setEvictionPolicy(final EvictionPolicy<T> evictionPolicy) { this.evictionPolicy = evictionPolicy; } /** * Sets the value for the {@code evictionPolicyClassName} configuration * attribute for pools created with this configuration instance. * * @param evictionPolicyClassName The new setting of * {@code evictionPolicyClassName} for this configuration instance * * @see GenericObjectPool#getEvictionPolicyClassName() * @see GenericKeyedObjectPool#getEvictionPolicyClassName() */ public void setEvictionPolicyClassName(final String evictionPolicyClassName) { this.evictionPolicyClassName = evictionPolicyClassName; } /** * Sets the value for the {@code evictorShutdownTimeout} configuration * attribute for pools created with this configuration instance. * * @param evictorShutdownTimeoutDuration The new setting of * {@code evictorShutdownTimeout} for this configuration * instance * * @see GenericObjectPool#getEvictorShutdownTimeoutDuration() * @see GenericKeyedObjectPool#getEvictorShutdownTimeoutDuration() * @since 2.11.0 */ public void setEvictorShutdownTimeout(final Duration evictorShutdownTimeoutDuration) { this.evictorShutdownTimeoutDuration = PoolImplUtils.nonNull(evictorShutdownTimeoutDuration, DEFAULT_EVICTOR_SHUTDOWN_TIMEOUT); } /** * Sets the value for the {@code fairness} configuration attribute for pools * created with this configuration instance. * * @param fairness The new setting of {@code fairness} * for this configuration instance * * @see GenericObjectPool#getFairness() * @see GenericKeyedObjectPool#getFairness() */ public void setFairness(final boolean fairness) { this.fairness = fairness; } /** * Sets the value of the flag that determines if JMX will be enabled for * pools created with this configuration instance. * * @param jmxEnabled The new setting of {@code jmxEnabled} * for this configuration instance */ public void setJmxEnabled(final boolean jmxEnabled) { this.jmxEnabled = jmxEnabled; } /** * Sets the value of the JMX name base that will be used as part of the * name assigned to JMX enabled pools created with this configuration * instance. A value of {@code null} means that the pool will define * the JMX name base. * * @param jmxNameBase The new setting of {@code jmxNameBase} * for this configuration instance */ public void setJmxNameBase(final String jmxNameBase) { this.jmxNameBase = jmxNameBase; } /** * Sets the value of the JMX name prefix that will be used as part of the * name assigned to JMX enabled pools created with this configuration * instance. * * @param jmxNamePrefix The new setting of {@code jmxNamePrefix} * for this configuration instance */ public void setJmxNamePrefix(final String jmxNamePrefix) { this.jmxNamePrefix = jmxNamePrefix; } /** * Sets the value for the {@code lifo} configuration attribute for pools * created with this configuration instance. * * @param lifo The new setting of {@code lifo} * for this configuration instance * * @see GenericObjectPool#getLifo() * @see GenericKeyedObjectPool#getLifo() */ public void setLifo(final boolean lifo) { this.lifo = lifo; } /** * Sets the value for the {@code maxWait} configuration attribute for pools * created with this configuration instance. * * @param maxWaitDuration The new setting of {@code maxWaitDuration} * for this configuration instance * * @see GenericObjectPool#getMaxWaitDuration() * @see GenericKeyedObjectPool#getMaxWaitDuration() * @since 2.11.0 */ public void setMaxWait(final Duration maxWaitDuration) { this.maxWaitDuration = PoolImplUtils.nonNull(maxWaitDuration, DEFAULT_MAX_WAIT); } /** * Sets the value for the {@code minEvictableIdleTime} configuration * attribute for pools created with this configuration instance. * * @param minEvictableIdleTime The new setting of * {@code minEvictableIdleTime} for this configuration instance * * @see GenericObjectPool#getMinEvictableIdleDuration() * @see GenericKeyedObjectPool#getMinEvictableIdleDuration() * @since 2.10.0 */ public void setMinEvictableIdleDuration(final Duration minEvictableIdleTime) { this.minEvictableIdleDuration = PoolImplUtils.nonNull(minEvictableIdleTime, DEFAULT_MIN_EVICTABLE_IDLE_DURATION); } /** * Sets the value for the {@code numTestsPerEvictionRun} configuration * attribute for pools created with this configuration instance. * * @param numTestsPerEvictionRun The new setting of * {@code numTestsPerEvictionRun} for this configuration instance * * @see GenericObjectPool#getNumTestsPerEvictionRun() * @see GenericKeyedObjectPool#getNumTestsPerEvictionRun() */ public void setNumTestsPerEvictionRun(final int numTestsPerEvictionRun) { this.numTestsPerEvictionRun = numTestsPerEvictionRun; } /** * Sets the value for the {@code softMinEvictableIdleTime} * configuration attribute for pools created with this configuration * instance. * * @param softMinEvictableIdleTime The new setting of * {@code softMinEvictableIdleTime} for this configuration * instance * * @see GenericObjectPool#getSoftMinEvictableIdleDuration() * @see GenericKeyedObjectPool#getSoftMinEvictableIdleDuration() * @since 2.10.0 */ public void setSoftMinEvictableIdleDuration(final Duration softMinEvictableIdleTime) { this.softMinEvictableIdleDuration = PoolImplUtils.nonNull(softMinEvictableIdleTime, DEFAULT_SOFT_MIN_EVICTABLE_IDLE_DURATION); } /** * Sets the value for the {@code testOnBorrow} configuration attribute for * pools created with this configuration instance. * * @param testOnBorrow The new setting of {@code testOnBorrow} * for this configuration instance * * @see GenericObjectPool#getTestOnBorrow() * @see GenericKeyedObjectPool#getTestOnBorrow() */ public void setTestOnBorrow(final boolean testOnBorrow) { this.testOnBorrow = testOnBorrow; } /** * Sets the value for the {@code testOnCreate} configuration attribute for * pools created with this configuration instance. * * @param testOnCreate The new setting of {@code testOnCreate} * for this configuration instance * * @see GenericObjectPool#getTestOnCreate() * @see GenericKeyedObjectPool#getTestOnCreate() * * @since 2.2 */ public void setTestOnCreate(final boolean testOnCreate) { this.testOnCreate = testOnCreate; } /** * Sets the value for the {@code testOnReturn} configuration attribute for * pools created with this configuration instance. * * @param testOnReturn The new setting of {@code testOnReturn} * for this configuration instance * * @see GenericObjectPool#getTestOnReturn() * @see GenericKeyedObjectPool#getTestOnReturn() */ public void setTestOnReturn(final boolean testOnReturn) { this.testOnReturn = testOnReturn; } /** * Sets the value for the {@code testWhileIdle} configuration attribute for * pools created with this configuration instance. * * @param testWhileIdle The new setting of {@code testWhileIdle} * for this configuration instance * * @see GenericObjectPool#getTestWhileIdle() * @see GenericKeyedObjectPool#getTestWhileIdle() */ public void setTestWhileIdle(final boolean testWhileIdle) { this.testWhileIdle = testWhileIdle; } @Override protected void toStringAppendFields(final StringBuilder builder) { builder.append("lifo="); builder.append(lifo); builder.append(", fairness="); builder.append(fairness); builder.append(", maxWaitDuration="); builder.append(maxWaitDuration); builder.append(", minEvictableIdleTime="); builder.append(minEvictableIdleDuration); builder.append(", softMinEvictableIdleTime="); builder.append(softMinEvictableIdleDuration); builder.append(", numTestsPerEvictionRun="); builder.append(numTestsPerEvictionRun); builder.append(", evictionPolicyClassName="); builder.append(evictionPolicyClassName); builder.append(", testOnCreate="); builder.append(testOnCreate); builder.append(", testOnBorrow="); builder.append(testOnBorrow); builder.append(", testOnReturn="); builder.append(testOnReturn); builder.append(", testWhileIdle="); builder.append(testWhileIdle); builder.append(", timeBetweenEvictionRuns="); builder.append(durationBetweenEvictionRuns); builder.append(", blockWhenExhausted="); builder.append(blockWhenExhausted); builder.append(", jmxEnabled="); builder.append(jmxEnabled); builder.append(", jmxNamePrefix="); builder.append(jmxNamePrefix); builder.append(", jmxNameBase="); builder.append(jmxNameBase); } }
5,290
0
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3/impl/GenericKeyedObjectPoolConfig.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.impl; /** * A simple structure encapsulating the configuration for a * {@link GenericKeyedObjectPool}. * * <p> * This class is not thread-safe; it is only intended to be used to provide * attributes used when creating a pool. * </p> * * @param <T> Type of element pooled. * @since 2.0 */ public class GenericKeyedObjectPoolConfig<T> extends BaseObjectPoolConfig<T> { /** * The default value for the {@code maxTotalPerKey} configuration attribute. * @see GenericKeyedObjectPool#getMaxTotalPerKey() */ public static final int DEFAULT_MAX_TOTAL_PER_KEY = 8; /** * The default value for the {@code maxTotal} configuration attribute. * @see GenericKeyedObjectPool#getMaxTotal() */ public static final int DEFAULT_MAX_TOTAL = -1; /** * The default value for the {@code minIdlePerKey} configuration attribute. * @see GenericKeyedObjectPool#getMinIdlePerKey() */ public static final int DEFAULT_MIN_IDLE_PER_KEY = 0; /** * The default value for the {@code maxIdlePerKey} configuration attribute. * @see GenericKeyedObjectPool#getMaxIdlePerKey() */ public static final int DEFAULT_MAX_IDLE_PER_KEY = 8; private int minIdlePerKey = DEFAULT_MIN_IDLE_PER_KEY; private int maxIdlePerKey = DEFAULT_MAX_IDLE_PER_KEY; private int maxTotalPerKey = DEFAULT_MAX_TOTAL_PER_KEY; private int maxTotal = DEFAULT_MAX_TOTAL; /** * Constructs a new configuration with default settings. */ public GenericKeyedObjectPoolConfig() { } @SuppressWarnings("unchecked") @Override public GenericKeyedObjectPoolConfig<T> clone() { try { return (GenericKeyedObjectPoolConfig<T>) super.clone(); } catch (final CloneNotSupportedException e) { throw new AssertionError(); // Can't happen } } /** * Gets the value for the {@code maxIdlePerKey} configuration attribute * for pools created with this configuration instance. * * @return The current setting of {@code maxIdlePerKey} for this * configuration instance * * @see GenericKeyedObjectPool#getMaxIdlePerKey() */ public int getMaxIdlePerKey() { return maxIdlePerKey; } /** * Gets the value for the {@code maxTotal} configuration attribute * for pools created with this configuration instance. * * @return The current setting of {@code maxTotal} for this * configuration instance * * @see GenericKeyedObjectPool#getMaxTotal() */ public int getMaxTotal() { return maxTotal; } /** * Gets the value for the {@code maxTotalPerKey} configuration attribute * for pools created with this configuration instance. * * @return The current setting of {@code maxTotalPerKey} for this * configuration instance * * @see GenericKeyedObjectPool#getMaxTotalPerKey() */ public int getMaxTotalPerKey() { return maxTotalPerKey; } /** * Gets the value for the {@code minIdlePerKey} configuration attribute * for pools created with this configuration instance. * * @return The current setting of {@code minIdlePerKey} for this * configuration instance * * @see GenericKeyedObjectPool#getMinIdlePerKey() */ public int getMinIdlePerKey() { return minIdlePerKey; } /** * Sets the value for the {@code maxIdlePerKey} configuration attribute for * pools created with this configuration instance. * * @param maxIdlePerKey The new setting of {@code maxIdlePerKey} * for this configuration instance * * @see GenericKeyedObjectPool#setMaxIdlePerKey(int) */ public void setMaxIdlePerKey(final int maxIdlePerKey) { this.maxIdlePerKey = maxIdlePerKey; } /** * Sets the value for the {@code maxTotal} configuration attribute for * pools created with this configuration instance. * * @param maxTotal The new setting of {@code maxTotal} * for this configuration instance * * @see GenericKeyedObjectPool#setMaxTotal(int) */ public void setMaxTotal(final int maxTotal) { this.maxTotal = maxTotal; } /** * Sets the value for the {@code maxTotalPerKey} configuration attribute for * pools created with this configuration instance. * * @param maxTotalPerKey The new setting of {@code maxTotalPerKey} * for this configuration instance * * @see GenericKeyedObjectPool#setMaxTotalPerKey(int) */ public void setMaxTotalPerKey(final int maxTotalPerKey) { this.maxTotalPerKey = maxTotalPerKey; } /** * Sets the value for the {@code minIdlePerKey} configuration attribute for * pools created with this configuration instance. * * @param minIdlePerKey The new setting of {@code minIdlePerKey} * for this configuration instance * * @see GenericKeyedObjectPool#setMinIdlePerKey(int) */ public void setMinIdlePerKey(final int minIdlePerKey) { this.minIdlePerKey = minIdlePerKey; } @Override protected void toStringAppendFields(final StringBuilder builder) { super.toStringAppendFields(builder); builder.append(", minIdlePerKey="); builder.append(minIdlePerKey); builder.append(", maxIdlePerKey="); builder.append(maxIdlePerKey); builder.append(", maxTotalPerKey="); builder.append(maxTotalPerKey); builder.append(", maxTotal="); builder.append(maxTotal); } }
5,291
0
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3/impl/LinkedBlockingDeque.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.impl; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; import java.time.Duration; import java.util.AbstractQueue; import java.util.Collection; import java.util.Deque; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Objects; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; /** * An optionally-bounded {@linkplain java.util.concurrent.BlockingDeque blocking * deque} based on linked nodes. * * <p> The optional capacity bound constructor argument serves as a * way to prevent excessive expansion. The capacity, if unspecified, * is equal to {@link Integer#MAX_VALUE}. Linked nodes are * dynamically created upon each insertion unless this would bring the * deque above capacity. * </p> * * <p>Most operations run in constant time (ignoring time spent * blocking). Exceptions include {@link #remove(Object) remove}, * {@link #removeFirstOccurrence removeFirstOccurrence}, {@link * #removeLastOccurrence removeLastOccurrence}, {@link #contains * contains}, {@link #iterator iterator.remove()}, and the bulk * operations, all of which run in linear time. * </p> * * <p>This class and its iterator implement all of the * <em>optional</em> methods of the {@link Collection} and {@link * Iterator} interfaces. * </p> * * <p>This class is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * </p> * * @param <E> the type of elements held in this collection * * Note: This was copied from Apache Harmony and modified to suit the needs of * Commons Pool. * * @since 2.0 */ final class LinkedBlockingDeque<E> extends AbstractQueue<E> implements Deque<E>, Serializable { /* * Implemented as a simple doubly-linked list protected by a * single lock and using conditions to manage blocking. * * To implement weakly consistent iterators, it appears we need to * keep all Nodes GC-reachable from a predecessor dequeued Node. * That would cause two problems: * - allow a rogue Iterator to cause unbounded memory retention * - cause cross-generational linking of old Nodes to new Nodes if * a Node was tenured while live, which generational GCs have a * hard time dealing with, causing repeated major collections. * However, only non-deleted Nodes need to be reachable from * dequeued Nodes, and reachability does not necessarily have to * be of the kind understood by the GC. We use the trick of * linking a Node that has just been dequeued to itself. Such a * self-link implicitly means to jump to "first" (for next links) * or "last" (for prev links). */ /* * We have "diamond" multiple interface/abstract class inheritance * here, and that introduces ambiguities. Often we want the * BlockingDeque javadoc combined with the AbstractQueue * implementation, so a lot of method specs are duplicated here. */ /** * Base class for Iterators for LinkedBlockingDeque */ private abstract class AbstractItr implements Iterator<E> { /** * The next node to return in next() */ Node<E> next; /** * nextItem holds on to item fields because once we claim that * an element exists in hasNext(), we must return item read * under lock (in advance()) even if it was in the process of * being removed when hasNext() was called. */ E nextItem; /** * Node returned by most recent call to next. Needed by remove. * Reset to null if this element is deleted by a call to remove. */ private Node<E> lastRet; /** * Constructs a new iterator. Sets the initial position. */ AbstractItr() { // set to initial position lock.lock(); try { next = firstNode(); nextItem = next == null ? null : next.item; } finally { lock.unlock(); } } /** * Advances next. */ void advance() { lock.lock(); try { // assert next != null; next = succ(next); nextItem = next == null ? null : next.item; } finally { lock.unlock(); } } /** * Obtain the first node to be returned by the iterator. * * @return first node */ abstract Node<E> firstNode(); @Override public boolean hasNext() { return next != null; } @Override public E next() { if (next == null) { throw new NoSuchElementException(); } lastRet = next; final E x = nextItem; advance(); return x; } /** * For a given node, obtain the next node to be returned by the * iterator. * * @param n given node * * @return next node */ abstract Node<E> nextNode(Node<E> n); @Override public void remove() { final Node<E> n = lastRet; if (n == null) { throw new IllegalStateException(); } lastRet = null; lock.lock(); try { if (n.item != null) { unlink(n); } } finally { lock.unlock(); } } /** * Returns the successor node of the given non-null, but * possibly previously deleted, node. * * @param n node whose successor is sought * @return successor node */ private Node<E> succ(Node<E> n) { // Chains of deleted nodes ending in null or self-links // are possible if multiple interior nodes are removed. for (;;) { final Node<E> s = nextNode(n); if (s == null) { return null; } if (s.item != null) { return s; } if (s == n) { return firstNode(); } n = s; } } } /** Descending iterator */ private final class DescendingItr extends AbstractItr { @Override Node<E> firstNode() { return last; } @Override Node<E> nextNode(final Node<E> n) { return n.prev; } } /** Forward iterator */ private final class Itr extends AbstractItr { @Override Node<E> firstNode() { return first; } @Override Node<E> nextNode(final Node<E> n) { return n.next; } } /** * Doubly-linked list node class. * * @param <E> node item type */ private static final class Node<E> { /** * The item, or null if this node has been removed. */ E item; /** * One of: * - the real predecessor Node * - this Node, meaning the predecessor is tail * - null, meaning there is no predecessor */ Node<E> prev; /** * One of: * - the real successor Node * - this Node, meaning the successor is head * - null, meaning there is no successor */ Node<E> next; /** * Constructs a new list node. * * @param x The list item * @param p Previous item * @param n Next item */ Node(final E x, final Node<E> p, final Node<E> n) { item = x; prev = p; next = n; } } private static final long serialVersionUID = -387911632671998426L; /** * Pointer to first node. * Invariant: (first == null && last == null) || * (first.prev == null && first.item != null) */ private transient Node<E> first; // @GuardedBy("lock") /** * Pointer to last node. * Invariant: (first == null && last == null) || * (last.next == null && last.item != null) */ private transient Node<E> last; // @GuardedBy("lock") /** Number of items in the deque */ private transient int count; // @GuardedBy("lock") /** Maximum number of items in the deque */ private final int capacity; /** Main lock guarding all access */ private final InterruptibleReentrantLock lock; /** Condition for waiting takes */ private final Condition notEmpty; /** Condition for waiting puts */ private final Condition notFull; /** * Creates a {@code LinkedBlockingDeque} with a capacity of * {@link Integer#MAX_VALUE}. */ public LinkedBlockingDeque() { this(Integer.MAX_VALUE); } /** * Creates a {@code LinkedBlockingDeque} with a capacity of * {@link Integer#MAX_VALUE} and the given fairness policy. * @param fairness true means threads waiting on the deque should be served * as if waiting in a FIFO request queue */ public LinkedBlockingDeque(final boolean fairness) { this(Integer.MAX_VALUE, fairness); } // Basic linking and unlinking operations, called only while holding lock /** * Creates a {@code LinkedBlockingDeque} with a capacity of * {@link Integer#MAX_VALUE}, initially containing the elements of * the given collection, added in traversal order of the * collection's iterator. * * @param c the collection of elements to initially contain * @throws NullPointerException if the specified collection or any * of its elements are null */ public LinkedBlockingDeque(final Collection<? extends E> c) { this(Integer.MAX_VALUE); lock.lock(); // Never contended, but necessary for visibility try { for (final E e : c) { Objects.requireNonNull(e); if (!linkLast(e)) { throw new IllegalStateException("Deque full"); } } } finally { lock.unlock(); } } /** * Creates a {@code LinkedBlockingDeque} with the given (fixed) capacity. * * @param capacity the capacity of this deque * @throws IllegalArgumentException if {@code capacity} is less than 1 */ public LinkedBlockingDeque(final int capacity) { this(capacity, false); } /** * Creates a {@code LinkedBlockingDeque} with the given (fixed) capacity * and fairness policy. * * @param capacity the capacity of this deque * @param fairness true means threads waiting on the deque should be served * as if waiting in a FIFO request queue * @throws IllegalArgumentException if {@code capacity} is less than 1 */ public LinkedBlockingDeque(final int capacity, final boolean fairness) { if (capacity <= 0) { throw new IllegalArgumentException(); } this.capacity = capacity; lock = new InterruptibleReentrantLock(fairness); notEmpty = lock.newCondition(); notFull = lock.newCondition(); } /** * {@inheritDoc} */ @Override public boolean add(final E e) { addLast(e); return true; } /** * {@inheritDoc} */ @Override public void addFirst(final E e) { if (!offerFirst(e)) { throw new IllegalStateException("Deque full"); } } // BlockingDeque methods /** * {@inheritDoc} */ @Override public void addLast(final E e) { if (!offerLast(e)) { throw new IllegalStateException("Deque full"); } } /** * Atomically removes all of the elements from this deque. * The deque will be empty after this call returns. */ @Override public void clear() { lock.lock(); try { for (Node<E> f = first; f != null;) { f.item = null; final Node<E> n = f.next; f.prev = null; f.next = null; f = n; } first = last = null; count = 0; notFull.signalAll(); } finally { lock.unlock(); } } /** * Returns {@code true} if this deque contains the specified element. * More formally, returns {@code true} if and only if this deque contains * at least one element {@code e} such that {@code o.equals(e)}. * * @param o object to be checked for containment in this deque * @return {@code true} if this deque contains the specified element */ @Override public boolean contains(final Object o) { if (o == null) { return false; } lock.lock(); try { for (Node<E> p = first; p != null; p = p.next) { if (o.equals(p.item)) { return true; } } return false; } finally { lock.unlock(); } } /** * {@inheritDoc} */ @Override public Iterator<E> descendingIterator() { return new DescendingItr(); } /** * Drains the queue to the specified collection. * * @param c The collection to add the elements to * * @return number of elements added to the collection * * @throws UnsupportedOperationException if the add operation is not * supported by the specified collection * @throws ClassCastException if the class of the elements held by this * collection prevents them from being added to the specified * collection * @throws NullPointerException if c is null * @throws IllegalArgumentException if c is this instance */ public int drainTo(final Collection<? super E> c) { return drainTo(c, Integer.MAX_VALUE); } /** * Drains no more than the specified number of elements from the queue to the * specified collection. * * @param c collection to add the elements to * @param maxElements maximum number of elements to remove from the queue * * @return number of elements added to the collection * @throws UnsupportedOperationException if the add operation is not * supported by the specified collection * @throws ClassCastException if the class of the elements held by this * collection prevents them from being added to the specified * collection * @throws NullPointerException if c is null * @throws IllegalArgumentException if c is this instance */ public int drainTo(final Collection<? super E> c, final int maxElements) { Objects.requireNonNull(c, "c"); if (c == this) { throw new IllegalArgumentException(); } lock.lock(); try { final int n = Math.min(maxElements, count); for (int i = 0; i < n; i++) { c.add(first.item); // In this order, in case add() throws. unlinkFirst(); } return n; } finally { lock.unlock(); } } /** * Retrieves, but does not remove, the head of the queue represented by * this deque. This method differs from {@link #peek peek} only in that * it throws an exception if this deque is empty. * * <p>This method is equivalent to {@link #getFirst() getFirst}. * * @return the head of the queue represented by this deque * @throws NoSuchElementException if this deque is empty */ @Override public E element() { return getFirst(); } /** * {@inheritDoc} */ @Override public E getFirst() { final E x = peekFirst(); if (x == null) { throw new NoSuchElementException(); } return x; } /** * {@inheritDoc} */ @Override public E getLast() { final E x = peekLast(); if (x == null) { throw new NoSuchElementException(); } return x; } /** * Gets the length of the queue of threads waiting to take instances from this deque. See disclaimer on accuracy * in {@link java.util.concurrent.locks.ReentrantLock#getWaitQueueLength(Condition)}. * * @return number of threads waiting on this deque's notEmpty condition. */ public int getTakeQueueLength() { lock.lock(); try { return lock.getWaitQueueLength(notEmpty); } finally { lock.unlock(); } } /** * Returns true if there are threads waiting to take instances from this deque. See disclaimer on accuracy in * {@link java.util.concurrent.locks.ReentrantLock#hasWaiters(Condition)}. * * @return true if there is at least one thread waiting on this deque's notEmpty condition. */ public boolean hasTakeWaiters() { lock.lock(); try { return lock.hasWaiters(notEmpty); } finally { lock.unlock(); } } /** * Interrupts the threads currently waiting to take an object from the pool. See disclaimer on accuracy in * {@link java.util.concurrent.locks.ReentrantLock#getWaitingThreads(Condition)}. */ public void interuptTakeWaiters() { lock.lock(); try { lock.interruptWaiters(notEmpty); } finally { lock.unlock(); } } /** * Returns an iterator over the elements in this deque in proper sequence. * The elements will be returned in order from first (head) to last (tail). * The returned {@code Iterator} is a "weakly consistent" iterator that * will never throw {@link java.util.ConcurrentModificationException * ConcurrentModificationException}, * and guarantees to traverse elements as they existed upon * construction of the iterator, and may (but is not guaranteed to) * reflect any modifications subsequent to construction. * * @return an iterator over the elements in this deque in proper sequence */ @Override public Iterator<E> iterator() { return new Itr(); } /** * Links provided element as first element, or returns false if full. * * @param e The element to link as the first element. * * @return {@code true} if successful, otherwise {@code false} */ private boolean linkFirst(final E e) { // assert lock.isHeldByCurrentThread(); if (count >= capacity) { return false; } final Node<E> f = first; final Node<E> x = new Node<>(e, null, f); first = x; if (last == null) { last = x; } else { f.prev = x; } ++count; notEmpty.signal(); return true; } /** * Links provided element as last element, or returns false if full. * * @param e The element to link as the last element. * * @return {@code true} if successful, otherwise {@code false} */ private boolean linkLast(final E e) { // assert lock.isHeldByCurrentThread(); if (count >= capacity) { return false; } final Node<E> l = last; final Node<E> x = new Node<>(e, l, null); last = x; if (first == null) { first = x; } else { l.next = x; } ++count; notEmpty.signal(); return true; } /** * {@inheritDoc} */ @Override public boolean offer(final E e) { return offerLast(e); } /** * Links the provided element as the last in the queue, waiting up to the * specified time to do so if the queue is full. * <p> * This method is equivalent to {@link #offerLast(Object, long, TimeUnit)} * * @param e element to link * @param timeout length of time to wait * * @return {@code true} if successful, otherwise {@code false} * * @throws NullPointerException if e is null * @throws InterruptedException if the thread is interrupted whilst waiting * for space */ boolean offer(final E e, final Duration timeout) throws InterruptedException { return offerLast(e, timeout); } /** * Links the provided element as the last in the queue, waiting up to the * specified time to do so if the queue is full. * <p> * This method is equivalent to {@link #offerLast(Object, long, TimeUnit)} * * @param e element to link * @param timeout length of time to wait * @param unit units that timeout is expressed in * * @return {@code true} if successful, otherwise {@code false} * * @throws NullPointerException if e is null * @throws InterruptedException if the thread is interrupted whilst waiting * for space */ public boolean offer(final E e, final long timeout, final TimeUnit unit) throws InterruptedException { return offerLast(e, timeout, unit); } /** * {@inheritDoc} */ @Override public boolean offerFirst(final E e) { Objects.requireNonNull(e, "e"); lock.lock(); try { return linkFirst(e); } finally { lock.unlock(); } } /** * Links the provided element as the first in the queue, waiting up to the * specified time to do so if the queue is full. * * @param e element to link * @param timeout length of time to wait * * @return {@code true} if successful, otherwise {@code false} * * @throws NullPointerException if e is null * @throws InterruptedException if the thread is interrupted whilst waiting * for space */ public boolean offerFirst(final E e, final Duration timeout) throws InterruptedException { Objects.requireNonNull(e, "e"); long nanos = timeout.toNanos(); lock.lockInterruptibly(); try { while (!linkFirst(e)) { if (nanos <= 0) { return false; } nanos = notFull.awaitNanos(nanos); } return true; } finally { lock.unlock(); } } /** * Links the provided element as the first in the queue, waiting up to the * specified time to do so if the queue is full. * * @param e element to link * @param timeout length of time to wait * @param unit units that timeout is expressed in * * @return {@code true} if successful, otherwise {@code false} * * @throws NullPointerException if e is null * @throws InterruptedException if the thread is interrupted whilst waiting * for space */ public boolean offerFirst(final E e, final long timeout, final TimeUnit unit) throws InterruptedException { return offerFirst(e, PoolImplUtils.toDuration(timeout, unit)); } /** * {@inheritDoc} */ @Override public boolean offerLast(final E e) { Objects.requireNonNull(e, "e"); lock.lock(); try { return linkLast(e); } finally { lock.unlock(); } } /** * Links the provided element as the last in the queue, waiting up to the * specified time to do so if the queue is full. * * @param e element to link * @param timeout length of time to wait * * @return {@code true} if successful, otherwise {@code false} * * @throws NullPointerException if e is null * @throws InterruptedException if the thread is interrupted whist waiting * for space */ boolean offerLast(final E e, final Duration timeout) throws InterruptedException { Objects.requireNonNull(e, "e"); long nanos = timeout.toNanos(); lock.lockInterruptibly(); try { while (!linkLast(e)) { if (nanos <= 0) { return false; } nanos = notFull.awaitNanos(nanos); } return true; } finally { lock.unlock(); } } /** * Links the provided element as the last in the queue, waiting up to the * specified time to do so if the queue is full. * * @param e element to link * @param timeout length of time to wait * @param unit units that timeout is expressed in * * @return {@code true} if successful, otherwise {@code false} * * @throws NullPointerException if e is null * @throws InterruptedException if the thread is interrupted whist waiting * for space */ public boolean offerLast(final E e, final long timeout, final TimeUnit unit) throws InterruptedException { return offerLast(e, PoolImplUtils.toDuration(timeout, unit)); } @Override public E peek() { return peekFirst(); } // BlockingQueue methods @Override public E peekFirst() { lock.lock(); try { return first == null ? null : first.item; } finally { lock.unlock(); } } @Override public E peekLast() { lock.lock(); try { return last == null ? null : last.item; } finally { lock.unlock(); } } @Override public E poll() { return pollFirst(); } /** * Unlinks the first element in the queue, waiting up to the specified time * to do so if the queue is empty. * * <p>This method is equivalent to {@link #pollFirst(long, TimeUnit)}. * * @param timeout length of time to wait * * @return the unlinked element * @throws InterruptedException if the current thread is interrupted */ E poll(final Duration timeout) throws InterruptedException { return pollFirst(timeout); } /** * Unlinks the first element in the queue, waiting up to the specified time * to do so if the queue is empty. * * <p>This method is equivalent to {@link #pollFirst(long, TimeUnit)}. * * @param timeout length of time to wait * @param unit units that timeout is expressed in * * @return the unlinked element * @throws InterruptedException if the current thread is interrupted */ public E poll(final long timeout, final TimeUnit unit) throws InterruptedException { return pollFirst(timeout, unit); } @Override public E pollFirst() { lock.lock(); try { return unlinkFirst(); } finally { lock.unlock(); } } /** * Unlinks the first element in the queue, waiting up to the specified time * to do so if the queue is empty. * * @param timeout length of time to wait * * @return the unlinked element * @throws InterruptedException if the current thread is interrupted */ E pollFirst(final Duration timeout) throws InterruptedException { long nanos = timeout.toNanos(); lock.lockInterruptibly(); try { E x; while ((x = unlinkFirst()) == null) { if (nanos <= 0) { return null; } nanos = notEmpty.awaitNanos(nanos); } return x; } finally { lock.unlock(); } } /** * Unlinks the first element in the queue, waiting up to the specified time * to do so if the queue is empty. * * @param timeout length of time to wait * @param unit units that timeout is expressed in * * @return the unlinked element * @throws InterruptedException if the current thread is interrupted */ public E pollFirst(final long timeout, final TimeUnit unit) throws InterruptedException { return pollFirst(PoolImplUtils.toDuration(timeout, unit)); } @Override public E pollLast() { lock.lock(); try { return unlinkLast(); } finally { lock.unlock(); } } /** * Unlinks the last element in the queue, waiting up to the specified time * to do so if the queue is empty. * * @param timeout length of time to wait * * @return the unlinked element * @throws InterruptedException if the current thread is interrupted */ public E pollLast(final Duration timeout) throws InterruptedException { long nanos = timeout.toNanos(); lock.lockInterruptibly(); try { E x; while ( (x = unlinkLast()) == null) { if (nanos <= 0) { return null; } nanos = notEmpty.awaitNanos(nanos); } return x; } finally { lock.unlock(); } } /** * Unlinks the last element in the queue, waiting up to the specified time * to do so if the queue is empty. * * @param timeout length of time to wait * @param unit units that timeout is expressed in * * @return the unlinked element * @throws InterruptedException if the current thread is interrupted */ public E pollLast(final long timeout, final TimeUnit unit) throws InterruptedException { return pollLast(PoolImplUtils.toDuration(timeout, unit)); } /** * {@inheritDoc} */ @Override public E pop() { return removeFirst(); } /** * {@inheritDoc} */ @Override public void push(final E e) { addFirst(e); } /** * Links the provided element as the last in the queue, waiting until there * is space to do so if the queue is full. * * <p> * This method is equivalent to {@link #putLast(Object)}. * </p> * * @param e element to link * * @throws NullPointerException if e is null * @throws InterruptedException if the thread is interrupted whilst waiting * for space */ public void put(final E e) throws InterruptedException { putLast(e); } /** * Links the provided element as the first in the queue, waiting until there * is space to do so if the queue is full. * * @param e element to link * * @throws NullPointerException if e is null * @throws InterruptedException if the thread is interrupted whilst waiting * for space */ public void putFirst(final E e) throws InterruptedException { Objects.requireNonNull(e, "e"); lock.lock(); try { while (!linkFirst(e)) { notFull.await(); } } finally { lock.unlock(); } } /** * Links the provided element as the last in the queue, waiting until there * is space to do so if the queue is full. * * @param e element to link * * @throws NullPointerException if e is null * @throws InterruptedException if the thread is interrupted whilst waiting * for space */ public void putLast(final E e) throws InterruptedException { Objects.requireNonNull(e, "e"); lock.lock(); try { while (!linkLast(e)) { notFull.await(); } } finally { lock.unlock(); } } // Stack methods /** * Reconstitutes this deque from a stream (that is, * deserialize it). * @param s the stream */ private void readObject(final ObjectInputStream s) throws IOException, ClassNotFoundException { s.defaultReadObject(); count = 0; first = null; last = null; // Read in all elements and place in queue for (;;) { @SuppressWarnings("unchecked") final E item = (E)s.readObject(); if (item == null) { break; } add(item); } } /** * Returns the number of additional elements that this deque can ideally * (in the absence of memory or resource constraints) accept without * blocking. This is always equal to the initial capacity of this deque * less the current {@code size} of this deque. * * <p> * Note that you <em>cannot</em> always tell if an attempt to insert * an element will succeed by inspecting {@code remainingCapacity} * because it may be the case that another thread is about to * insert or remove an element. * </p> * * @return The number of additional elements the queue is able to accept */ public int remainingCapacity() { lock.lock(); try { return capacity - count; } finally { lock.unlock(); } } // Collection methods /** * Retrieves and removes the head of the queue represented by this deque. * This method differs from {@link #poll poll} only in that it throws an * exception if this deque is empty. * * <p> * This method is equivalent to {@link #removeFirst() removeFirst}. * </p> * * @return the head of the queue represented by this deque * @throws NoSuchElementException if this deque is empty */ @Override public E remove() { return removeFirst(); } /** * Removes the first occurrence of the specified element from this deque. * If the deque does not contain the element, it is unchanged. * More formally, removes the first element {@code e} such that * {@code o.equals(e)} (if such an element exists). * Returns {@code true} if this deque contained the specified element * (or equivalently, if this deque changed as a result of the call). * * <p> * This method is equivalent to * {@link #removeFirstOccurrence(Object) removeFirstOccurrence}. * </p> * * @param o element to be removed from this deque, if present * @return {@code true} if this deque changed as a result of the call */ @Override public boolean remove(final Object o) { return removeFirstOccurrence(o); } /** * {@inheritDoc} */ @Override public E removeFirst() { final E x = pollFirst(); if (x == null) { throw new NoSuchElementException(); } return x; } /* * TODO: Add support for more efficient bulk operations. * * We don't want to acquire the lock for every iteration, but we * also want other threads a chance to interact with the * collection, especially when count is close to capacity. */ // /** // * Adds all of the elements in the specified collection to this // * queue. Attempts to addAll of a queue to itself result in // * {@code IllegalArgumentException}. Further, the behavior of // * this operation is undefined if the specified collection is // * modified while the operation is in progress. // * // * @param c collection containing elements to be added to this queue // * @return {@code true} if this queue changed as a result of the call // * @throws ClassCastException // * @throws NullPointerException // * @throws IllegalArgumentException // * @throws IllegalStateException // * @see #add(Object) // */ // public boolean addAll(Collection<? extends E> c) { // if (c == null) // throw new NullPointerException(); // if (c == this) // throw new IllegalArgumentException(); // final ReentrantLock lock = this.lock; // lock.lock(); // try { // boolean modified = false; // for (E e : c) // if (linkLast(e)) // modified = true; // return modified; // } finally { // lock.unlock(); // } // } @Override public boolean removeFirstOccurrence(final Object o) { if (o == null) { return false; } lock.lock(); try { for (Node<E> p = first; p != null; p = p.next) { if (o.equals(p.item)) { unlink(p); return true; } } return false; } finally { lock.unlock(); } } /** * {@inheritDoc} */ @Override public E removeLast() { final E x = pollLast(); if (x == null) { throw new NoSuchElementException(); } return x; } @Override public boolean removeLastOccurrence(final Object o) { if (o == null) { return false; } lock.lock(); try { for (Node<E> p = last; p != null; p = p.prev) { if (o.equals(p.item)) { unlink(p); return true; } } return false; } finally { lock.unlock(); } } /** * Returns the number of elements in this deque. * * @return the number of elements in this deque */ @Override public int size() { lock.lock(); try { return count; } finally { lock.unlock(); } } /** * Unlinks the first element in the queue, waiting until there is an element * to unlink if the queue is empty. * * <p> * This method is equivalent to {@link #takeFirst()}. * </p> * * @return the unlinked element * @throws InterruptedException if the current thread is interrupted */ public E take() throws InterruptedException { return takeFirst(); } /** * Unlinks the first element in the queue, waiting until there is an element * to unlink if the queue is empty. * * @return the unlinked element * @throws InterruptedException if the current thread is interrupted */ public E takeFirst() throws InterruptedException { lock.lock(); try { E x; while ( (x = unlinkFirst()) == null) { notEmpty.await(); } return x; } finally { lock.unlock(); } } /** * Unlinks the last element in the queue, waiting until there is an element * to unlink if the queue is empty. * * @return the unlinked element * @throws InterruptedException if the current thread is interrupted */ public E takeLast() throws InterruptedException { lock.lock(); try { E x; while ( (x = unlinkLast()) == null) { notEmpty.await(); } return x; } finally { lock.unlock(); } } /** * Returns an array containing all of the elements in this deque, in * proper sequence (from first to last element). * * <p> * The returned array will be "safe" in that no references to it are * maintained by this deque. (In other words, this method must allocate * a new array). The caller is thus free to modify the returned array. * </p> * <p> * This method acts as bridge between array-based and collection-based * APIs. * </p> * * @return an array containing all of the elements in this deque */ @Override public Object[] toArray() { lock.lock(); try { final Object[] a = new Object[count]; int k = 0; for (Node<E> p = first; p != null; p = p.next) { a[k++] = p.item; } return a; } finally { lock.unlock(); } } /** * {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public <T> T[] toArray(T[] a) { lock.lock(); try { if (a.length < count) { a = (T[])java.lang.reflect.Array.newInstance (a.getClass().getComponentType(), count); } int k = 0; for (Node<E> p = first; p != null; p = p.next) { a[k++] = (T)p.item; } if (a.length > k) { a[k] = null; } return a; } finally { lock.unlock(); } } @Override public String toString() { lock.lock(); try { return super.toString(); } finally { lock.unlock(); } } /** * Unlinks the provided node. * * @param x The node to unlink */ private void unlink(final Node<E> x) { // assert lock.isHeldByCurrentThread(); final Node<E> p = x.prev; final Node<E> n = x.next; if (p == null) { unlinkFirst(); } else if (n == null) { unlinkLast(); } else { p.next = n; n.prev = p; x.item = null; // Don't mess with x's links. They may still be in use by // an iterator. --count; notFull.signal(); } } // Monitoring methods /** * Removes and returns the first element, or null if empty. * * @return The first element or {@code null} if empty */ private E unlinkFirst() { // assert lock.isHeldByCurrentThread(); final Node<E> f = first; if (f == null) { return null; } final Node<E> n = f.next; final E item = f.item; f.item = null; f.next = f; // help GC first = n; if (n == null) { last = null; } else { n.prev = null; } --count; notFull.signal(); return item; } /** * Removes and returns the last element, or null if empty. * * @return The first element or {@code null} if empty */ private E unlinkLast() { // assert lock.isHeldByCurrentThread(); final Node<E> l = last; if (l == null) { return null; } final Node<E> p = l.prev; final E item = l.item; l.item = null; l.prev = l; // help GC last = p; if (p == null) { first = null; } else { p.next = null; } --count; notFull.signal(); return item; } /** * Saves the state of this deque to a stream (that is, serialize it). * * @serialData The capacity (int), followed by elements (each an * {@code Object}) in the proper order, followed by a null * @param s the stream * @throws IOException if I/O errors occur while writing to the underlying {@code OutputStream} */ private void writeObject(final java.io.ObjectOutputStream s) throws IOException { lock.lock(); try { // Write out capacity and any hidden stuff s.defaultWriteObject(); // Write out all elements in the proper order. for (Node<E> p = first; p != null; p = p.next) { s.writeObject(p.item); } // Use trailing null as sentinel s.writeObject(null); } finally { lock.unlock(); } } }
5,292
0
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3/impl/EvictionPolicy.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.impl; import org.apache.commons.pool3.PooledObject; /** * To provide a custom eviction policy (i.e. something other than {@link * DefaultEvictionPolicy} for a pool, users must provide an implementation of * this interface that provides the required eviction policy. * * @param <T> the type of objects in the pool * @since 2.0 */ public interface EvictionPolicy<T> { /** * Tests if an idle object in the pool should be evicted or not. * * @param config The pool configuration settings related to eviction * @param underTest The pooled object being tested for eviction * @param idleCount The current number of idle objects in the pool including * the object under test * @return {@code true} if the object should be evicted, otherwise * {@code false} */ boolean evict(EvictionConfig config, PooledObject<T> underTest, int idleCount); }
5,293
0
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3/impl/package-info.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Object pooling API implementations. * <p> * {@link org.apache.commons.pool3.impl.GenericObjectPool GenericObjectPool} ({@link org.apache.commons.pool3.impl.GenericKeyedObjectPool * GenericKeyedObjectPool}) provides a more robust (but also more complicated) implementation of {@link org.apache.commons.pool3.ObjectPool ObjectPool} * ({@link org.apache.commons.pool3.KeyedObjectPool KeyedObjectPool}). * </p> * <p> * {@link org.apache.commons.pool3.impl.SoftReferenceObjectPool SoftReferenceObjectPool} provides a {@link java.lang.ref.SoftReference SoftReference} based * {@link org.apache.commons.pool3.ObjectPool ObjectPool}. * </p> * <p> * See also the {@link org.apache.commons.pool3} package. * </p> */ package org.apache.commons.pool3.impl;
5,294
0
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3/impl/NoOpCallStack.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.impl; import java.io.PrintWriter; /** * CallStack strategy using no-op implementations of all functionality. Can be used by default when abandoned object * logging is disabled. * * @since 2.5 */ public class NoOpCallStack implements CallStack { /** * Singleton instance. */ public static final CallStack INSTANCE = new NoOpCallStack(); /** * Constructs the singleton instance. */ private NoOpCallStack() { } @Override public void clear() { // no-op } @Override public void fillInStackTrace() { // no-op } @Override public boolean printStackTrace(final PrintWriter writer) { return false; } }
5,295
0
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3/proxy/JdkProxySource.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.proxy; import java.lang.reflect.Proxy; import java.util.Arrays; import org.apache.commons.pool3.UsageTracking; /** * Provides proxy objects using Java reflection. * * @param <T> type of the pooled object to be proxied * * @since 2.0 */ public class JdkProxySource<T> implements ProxySource<T> { private final ClassLoader classLoader; private final Class<?>[] interfaces; /** * Constructs a new proxy source for the given interfaces. * * @param classLoader The class loader with which to create the proxy * @param interfaces The interfaces to proxy */ public JdkProxySource(final ClassLoader classLoader, final Class<?>[] interfaces) { this.classLoader = classLoader; // Defensive copy this.interfaces = Arrays.copyOf(interfaces, interfaces.length); } @SuppressWarnings("unchecked") // Cast to T on return. @Override public T createProxy(final T pooledObject, final UsageTracking<T> usageTracking) { return (T) Proxy.newProxyInstance(classLoader, interfaces, new JdkProxyHandler<>(pooledObject, usageTracking)); } @SuppressWarnings("unchecked") @Override public T resolveProxy(final T proxy) { return ((JdkProxyHandler<T>) Proxy.getInvocationHandler(proxy)).disableProxy(); } /** * @since 2.4.3 */ @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("JdkProxySource [classLoader="); builder.append(classLoader); builder.append(", interfaces="); builder.append(Arrays.toString(interfaces)); builder.append("]"); return builder.toString(); } }
5,296
0
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3/proxy/ProxiedObjectPool.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.proxy; import java.util.NoSuchElementException; import org.apache.commons.pool3.ObjectPool; import org.apache.commons.pool3.UsageTracking; /** * Create a new object pool where the pooled objects are wrapped in proxies * allowing better control of pooled objects and in particular the prevention * of the continued use of an object by a client after that client returns the * object to the pool. * * @param <T> type of the pooled object * @param <E> type of the exception * * @since 2.0 */ public class ProxiedObjectPool<T, E extends Exception> implements ObjectPool<T, E> { private final ObjectPool<T, E> pool; private final ProxySource<T> proxySource; /** * Constructs a new proxied object pool. * * @param pool The object pool to wrap * @param proxySource The source of the proxy objects */ public ProxiedObjectPool(final ObjectPool<T, E> pool, final ProxySource<T> proxySource) { this.pool = pool; this.proxySource = proxySource; } @Override public void addObject() throws E, IllegalStateException, UnsupportedOperationException { pool.addObject(); } @SuppressWarnings("unchecked") @Override public T borrowObject() throws E, NoSuchElementException, IllegalStateException { UsageTracking<T> usageTracking = null; if (pool instanceof UsageTracking) { usageTracking = (UsageTracking<T>) pool; } return proxySource.createProxy(pool.borrowObject(), usageTracking); } @Override public void clear() throws E, UnsupportedOperationException { pool.clear(); } @Override public void close() { pool.close(); } @Override public int getNumActive() { return pool.getNumActive(); } @Override public int getNumIdle() { return pool.getNumIdle(); } @Override public void invalidateObject(final T proxy) throws E { pool.invalidateObject(proxySource.resolveProxy(proxy)); } @Override public void returnObject(final T proxy) throws E { pool.returnObject(proxySource.resolveProxy(proxy)); } /** * @since 2.4.3 */ @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("ProxiedObjectPool [pool="); builder.append(pool); builder.append(", proxySource="); builder.append(proxySource); builder.append("]"); return builder.toString(); } }
5,297
0
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3/proxy/CglibProxyHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.proxy; import java.lang.reflect.Method; import org.apache.commons.pool3.UsageTracking; import net.sf.cglib.proxy.MethodInterceptor; import net.sf.cglib.proxy.MethodProxy; /** * CGLib implementation of the proxy handler. * * @param <T> type of the wrapped pooled object * * @since 2.0 */ final class CglibProxyHandler<T> extends BaseProxyHandler<T> implements MethodInterceptor { /** * Constructs a CGLib proxy instance. * * @param pooledObject The object to wrap * @param usageTracking The instance, if any (usually the object pool) to * be provided with usage tracking information for this * wrapped object */ CglibProxyHandler(final T pooledObject, final UsageTracking<T> usageTracking) { super(pooledObject, usageTracking); } @Override public Object intercept(final Object object, final Method method, final Object[] args, final MethodProxy methodProxy) throws Throwable { return doInvoke(method, args); } }
5,298
0
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3
Create_ds/commons-pool/src/main/java/org/apache/commons/pool3/proxy/BaseProxyHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.pool3.proxy; import java.lang.reflect.Method; import org.apache.commons.pool3.UsageTracking; /** * Base implementation for object wrappers when using a * {@link ProxiedObjectPool}. * * @param <T> type of the wrapped pooled object * * @since 2.0 */ class BaseProxyHandler<T> { private volatile T pooledObject; private final UsageTracking<T> usageTracking; /** * Constructs a new wrapper for the given pooled object. * * @param pooledObject The object to wrap * @param usageTracking The instance, if any (usually the object pool) to * be provided with usage tracking information for this * wrapped object */ BaseProxyHandler(final T pooledObject, final UsageTracking<T> usageTracking) { this.pooledObject = pooledObject; this.usageTracking = usageTracking; } /** * Disable the proxy wrapper. Called when the object has been returned to * the pool. Further use of the wrapper should result in an * {@link IllegalStateException}. * * @return the object that this proxy was wrapping */ T disableProxy() { final T result = pooledObject; pooledObject = null; return result; } /** * Invoke the given method on the wrapped object. * * @param method The method to invoke * @param args The arguments to the method * @return The result of the method call * @throws Throwable If the method invocation fails */ Object doInvoke(final Method method, final Object[] args) throws Throwable { validateProxiedObject(); final T object = getPooledObject(); if (usageTracking != null) { usageTracking.use(object); } return method.invoke(object, args); } /** * Gets the wrapped, pooled object. * * @return the underlying pooled object */ T getPooledObject() { return pooledObject; } /** * @since 2.4.3 */ @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append(getClass().getName()); builder.append(" [pooledObject="); builder.append(pooledObject); builder.append(", usageTracking="); builder.append(usageTracking); builder.append("]"); return builder.toString(); } /** * Check that the proxy is still valid (i.e. that {@link #disableProxy()} * has not been called). * * @throws IllegalStateException if {@link #disableProxy()} has been called */ void validateProxiedObject() { if (pooledObject == null) { throw new IllegalStateException("This object may no longer be " + "used as it has been returned to the Object Pool."); } } }
5,299