-
Notifications
You must be signed in to change notification settings - Fork 290
/
GenericKeyedObjectPool.java
1711 lines (1551 loc) · 65.1 KB
/
GenericKeyedObjectPool.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* 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.pool2.impl;
import java.time.Duration;
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.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.pool2.DestroyMode;
import org.apache.commons.pool2.KeyedObjectPool;
import org.apache.commons.pool2.KeyedPooledObjectFactory;
import org.apache.commons.pool2.PoolUtils;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.PooledObjectState;
import org.apache.commons.pool2.SwallowedExceptionListener;
import org.apache.commons.pool2.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.
*
* @since 2.0
*/
public class GenericKeyedObjectPool<K, T> extends BaseGenericObjectPool<T>
implements KeyedObjectPool<K, T>, GenericKeyedObjectPoolMXBean<K>, UsageTracking<T> {
private static final Integer ZERO = Integer.valueOf(0);
/**
* Maintains information on the per key queue for a given key.
*
* @param <S> type of objects in the pool
*/
private 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 = 0;
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 ObjecDeque 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 count of the number of objects created for the current
* key.
*
* @return The number of objects created for this key
*/
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();
}
}
// JMX specific attributes
private static final String ONAME_BASE =
"org.apache.commons.pool2:type=GenericKeyedObjectPool,name=";
//--- configuration attributes ---------------------------------------------
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> 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 List<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 = null; // @GuardedBy("evictionLock")
private K evictionKey = null; // @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> 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> 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> 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.
*
* @param key The key to associate with the idle object
* @param p The wrapped object to add.
*
* @throws Exception If the associated factory fails to passivate the object
*/
private void addIdleObject(final K key, final PooledObject<T> p) throws Exception {
if (p != null) {
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.
*
* @param key the key a new instance should be added to
*
* @throws Exception when {@link KeyedPooledObjectFactory#makeObject}
* fails.
*/
@Override
public void addObject(final K key) throws Exception {
assertOpen();
register(key);
try {
final PooledObject<T> p = create(key);
addIdleObject(key, p);
} finally {
deregister(key);
}
}
/**
* Equivalent to <code>{@link #borrowObject(Object, long) borrowObject}(key,
* {@link #getMaxWaitDuration()})</code>.
*
* {@inheritDoc}
*/
@Override
public T borrowObject(final K key) throws Exception {
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.
* </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 Exception if a keyed object instance cannot be returned due to an
* error
*/
public T borrowObject(final K key, final long borrowMaxWaitMillis) throws Exception {
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 long waitTimeMillis = System.currentTimeMillis();
final ObjectDeque<T> objectDeque = register(key);
try {
while (p == null) {
create = false;
p = objectDeque.getIdleObjects().pollFirst();
if (p == null) {
p = create(key);
if (p != null) {
create = true;
}
}
if (blockWhenExhausted) {
if (p == null) {
if (borrowMaxWaitMillis < 0) {
p = objectDeque.getIdleObjects().takeFirst();
} else {
p = objectDeque.getIdleObjects().pollFirst(borrowMaxWaitMillis, TimeUnit.MILLISECONDS);
}
}
if (p == null) {
throw new NoSuchElementException(appendStats(
"Timeout waiting for idle object, borrowMaxWaitMillis=" + borrowMaxWaitMillis));
}
} else if (p == null) {
throw new NoSuchElementException(appendStats("Pool exhausted"));
}
if (!p.allocate()) {
p = null;
}
if (p != null) {
try {
factory.activateObject(key, p);
} catch (final Exception e) {
try {
destroy(key, p, true, DestroyMode.NORMAL);
} catch (final Exception e1) {
// Ignore - 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 (p != null && 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 e) {
// Ignore - 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.ofMillis(System.currentTimeMillis() - waitTimeMillis));
return p.getObject();
}
@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());
}
/**
* 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:
* </p>
* <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(this::clear);
}
/**
* Clears the specified sub-pool, removing all pooled instances
* corresponding to the given {@code key}. Exceptions encountered
* destroying idle instances are swallowed but notified via a
* {@link SwallowedExceptionListener}.
*
* @param key the key to clear
*/
@Override
public void clear(final K key) {
final ObjectDeque<T> objectDeque = register(key);
try {
final LinkedBlockingDeque<PooledObject<T>> idleObjects =
objectDeque.getIdleObjects();
PooledObject<T> p = idleObjects.poll();
while (p != null) {
try {
destroy(key, p, true, DestroyMode.NORMAL);
} catch (final Exception e) {
swallowException(e);
}
p = idleObjects.poll();
}
} finally {
deregister(key);
}
}
/**
* 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 Map<PooledObject<T>, K> map = new TreeMap<>();
poolMap.entrySet().forEach(entry -> {
final ObjectDeque<T> deque = entry.getValue();
// Protect against possible NPE if key has been removed in another
// thread. Not worth locking the keys while this loop completes.
if (deque != null) {
// Each item into the map using the PooledObject object as the
// key. It then gets sorted based on the idle time
deque.getIdleObjects().forEach(p -> map.put(p, entry.getKey()));
}
});
// 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.
*
* @param key Key associated with new pooled object
*
* @return The new, wrapped pooled object
*
* @throws Exception If the objection creation fails
*/
private PooledObject<T> create(final K key) throws Exception {
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.
objectDeque.makeObjectCountLock.wait();
}
} 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 (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(new IdentityWrapper<>(p.getObject()), 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);
final long numInterested = objectDeque.getNumInterested().decrementAndGet();
if (numInterested == 0 && objectDeque.getCreateCount().get() == 0) {
// Potential to remove key
// Upgrade to write lock
lock.unlock();
lock = keyLock.writeLock();
lock.lock();
if (objectDeque.getCreateCount().get() == 0 && objectDeque.getNumInterested().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 Exception If the object destruction failed
*/
private boolean destroy(final K key, final PooledObject<T> toDestroy, final boolean always, final DestroyMode destroyMode)
throws Exception {
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(new IdentityWrapper<>(toDestroy.getObject()));
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 Exception {
final int minIdlePerKeySave = getMinIdlePerKey();
if (minIdlePerKeySave < 1) {
return;
}
for (final K k : poolMap.keySet()) {
ensureMinIdle(k);
}
}
/**
* Ensure that the configured number of minimum idle objects is available in
* the pool for the given key.
*
* @param key The key to check for idle objects
*
* @throws Exception If a new object is required and cannot be created
*/
private void ensureMinIdle(final K key) throws Exception {
// 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 Exception {
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;