@@ -976,6 +976,69 @@ void testAddObject() throws Exception {
976976 assertEquals (0 , genericObjectPool .getNumActive (), "should be zero active" );
977977 }
978978
979+ /*https://issues.apache.org/jira/browse/POOL-425*/
980+ @ Test
981+ @ Timeout (value = 60000 , unit = TimeUnit .MILLISECONDS )
982+ void testAddObjectRespectsMaxIdleLimit () throws Exception {
983+ genericObjectPool .setMaxIdle (1 );
984+ genericObjectPool .addObject ();
985+ genericObjectPool .addObject ();
986+ assertEquals (1 , genericObjectPool .getNumIdle (), "should be one idle" );
987+
988+ genericObjectPool .setMaxIdle (-1 );
989+ genericObjectPool .addObject ();
990+ genericObjectPool .addObject ();
991+ genericObjectPool .addObject ();
992+ assertEquals (4 , genericObjectPool .getNumIdle (), "should be four idle" );
993+ }
994+
995+ @ Test
996+ @ Timeout (value = 60000 , unit = TimeUnit .MILLISECONDS )
997+ void testAddObjectConcurrentCallsRespectsMaxIdle () throws Exception {
998+ final int maxIdleLimit = 5 ;
999+ final int numThreads = 10 ;
1000+ genericObjectPool .setMaxIdle (maxIdleLimit );
1001+
1002+ final CountDownLatch startLatch = new CountDownLatch (1 );
1003+ final CountDownLatch doneLatch = new CountDownLatch (numThreads );
1004+
1005+ List <Runnable > tasks = getRunnables (numThreads , startLatch , doneLatch );
1006+
1007+ ExecutorService executorService = Executors .newFixedThreadPool (numThreads );
1008+ tasks .forEach (executorService ::submit );
1009+ try {
1010+ startLatch .countDown (); // Start all threads simultaneously
1011+ doneLatch .await (); // Wait for all threads to complete
1012+ } finally {
1013+ executorService .shutdown ();
1014+ assertTrue (executorService .awaitTermination (Long .MAX_VALUE , TimeUnit .NANOSECONDS ));
1015+ }
1016+
1017+ assertTrue (genericObjectPool .getNumIdle () <= maxIdleLimit ,
1018+ "Concurrent addObject() calls should not exceed maxIdle limit of " + maxIdleLimit +
1019+ ", but found " + genericObjectPool .getNumIdle () + " idle objects" );
1020+ }
1021+
1022+ private List <Runnable > getRunnables (final int numThreads ,
1023+ final CountDownLatch startLatch ,
1024+ final CountDownLatch doneLatch ) {
1025+ List <Runnable > tasks = new ArrayList <>();
1026+
1027+ for (int i = 0 ; i < numThreads ; i ++) {
1028+ tasks .add (() -> {
1029+ try {
1030+ startLatch .await (); // Wait for all threads to be ready
1031+ genericObjectPool .addObject ();
1032+ } catch (Exception e ) {
1033+ Thread .currentThread ().interrupt (); // Restore interrupt status
1034+ } finally {
1035+ doneLatch .countDown ();
1036+ }
1037+ });
1038+ }
1039+ return tasks ;
1040+ }
1041+
9791042 @ Test
9801043 void testAddObjectCanAddToMaxIdle () throws Exception {
9811044 genericObjectPool .setMaxTotal (5 );
0 commit comments