-
Notifications
You must be signed in to change notification settings - Fork 449
/
SchoonerSockIOPool.java
1778 lines (1542 loc) · 47.4 KB
/
SchoonerSockIOPool.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
/*******************************************************************************
* Copyright (c) 2009 Schooner Information Technology, Inc.
* All rights reserved.
*
* http://www.schoonerinfotech.com/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
package com.schooner.MemCached;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.channels.ByteChannel;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.locks.ReentrantLock;
import java.util.zip.CRC32;
import org.apache.commons.pool.impl.GenericObjectPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* This class is a connection pool for maintaning a pool of persistent
* connections<br/>
* to memcached servers.
*
* The pool must be initialized prior to use. This should typically be early on<br/>
* in the lifecycle of the JVM instance.<br/>
* <br/>
* <h3>An example of initializing using defaults:</h3>
*
* <pre>
* static {
* String[] serverlist = { "cache0.server.com:12345", "cache1.server.com:12345" };
*
* SockIOPool pool = SockIOPool.getInstance();
* pool.setServers(serverlist);
* pool.initialize();
* }
* </pre>
*
* <h3>An example of initializing using defaults and providing weights for
* servers:</h3>
*
* <pre>
* static {
* String[] serverlist = { "cache0.server.com:12345", "cache1.server.com:12345" };
* Integer[] weights = { new Integer(5), new Integer(2) };
*
* SockIOPool pool = SockIOPool.getInstance();
* pool.setServers(serverlist);
* pool.setWeights(weights);
* pool.initialize();
* }
* </pre>
*
* <h3>An example of initializing overriding defaults:</h3>
*
* <pre>
* static {
* String[] serverlist = { "cache0.server.com:12345", "cache1.server.com:12345" };
* Integer[] weights = { new Integer(5), new Integer(2) };
* pool.setInitConn(5);
* pool.setMinConn(5);
* pool.setMaxConn(10);
* pool.setMaintSleep(0);
* pool.setNagle(false);
* pool.initialize();
* }
* </pre>
*
* @author Xingen Wang
* @since 2.5.0
* @see SchoonerSockIOPool
*/
public class SchoonerSockIOPool {
// logger
private static Logger log = LoggerFactory.getLogger(SchoonerSockIOPool.class);
// store instances of pools
private static ConcurrentMap<String, SchoonerSockIOPool> pools = new ConcurrentHashMap<String, SchoonerSockIOPool>();
// avoid recurring construction
private static ThreadLocal<MessageDigest> MD5 = new ThreadLocal<MessageDigest>() {
@Override
protected final MessageDigest initialValue() {
try {
return MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
if (log.isErrorEnabled())
log.error("++++ no md5 algorithm found");
throw new IllegalStateException("++++ no md5 algorythm found");
}
}
};
public static final int NATIVE_HASH = 0; // native String.hashCode();
public static final int OLD_COMPAT_HASH = 1; // original compatibility
// hashing algorithm (works with other clients)
public static final int NEW_COMPAT_HASH = 2; // new CRC32 based
// compatibility hashing algorithm (works with other clients)
public static final int CONSISTENT_HASH = 3; // MD5 Based -- Stops
// thrashing when a server added or removed
public static final long MAX_RETRY_DELAY = 10 * 60 * 1000;
// max of 10 minute delay for fall off
boolean initialized = false;
private int minConn = 8;
private int maxConn = 32;
private long maxBusyTime = 1000 * 30; // max idle time for avail sockets
private long maintSleep = 1000 * 30; // maintenance thread sleep time
private int socketTO = 1000 * 30; // default timeout of socket reads
private int socketConnectTO = 1000 * 3; // default timeout of socket
// connections
@SuppressWarnings("unused")
private static int recBufferSize = 128;// bufsize
private long maxWait = 1000; // max wait time for avail sockets
private int maxIdle = maxConn;
private int minIdle = GenericObjectPool.DEFAULT_MIN_IDLE;
private boolean testOnBorrow = GenericObjectPool.DEFAULT_TEST_ON_BORROW;
private boolean testOnReturn = GenericObjectPool.DEFAULT_TEST_ON_RETURN;
private long timeBetweenEvictionRunsMillis = GenericObjectPool.DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS;
private int numTestsPerEvictionRun = GenericObjectPool.DEFAULT_NUM_TESTS_PER_EVICTION_RUN;
private long minEvictableIdleTimeMillis = GenericObjectPool.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS;
private boolean testWhileIdle = true;
private long softMinEvictableIdleTimeMillis = GenericObjectPool.DEFAULT_SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS;
private boolean lifo = GenericObjectPool.DEFAULT_LIFO;
private boolean aliveCheck = false; // default to not check each connection
// for being alive
private boolean failover = true; // default to failover in event of cache
private boolean failback = true; // only used if failover is also set ...
// controls putting a dead server back
// into rotation
// server dead
// controls putting a dead server back
// into rotation
private boolean nagle = false; // enable/disable Nagle's algorithm
private int hashingAlg = NATIVE_HASH; // default to using the native hash
// as it is the fastest
// locks
private final ReentrantLock initDeadLock = new ReentrantLock();
// list of all servers
private String[] servers;
private Integer[] weights;
private Integer totalWeight = 0;
private List<String> buckets;
private TreeMap<Long, String> consistentBuckets;
// map to hold all available sockets
Map<String, GenericObjectPool> socketPool;
ConcurrentMap<String, Date> hostDead;
ConcurrentMap<String, Long> hostDeadDur;
private AuthInfo authInfo;
private boolean isTcp;
private int bufferSize = 1024 * 1025;
protected SchoonerSockIOPool(boolean isTcp) {
this.isTcp = isTcp;
}
/**
* Factory to create/retrieve new pools given a unique poolName.
*
* @param poolName
* unique name of the pool
* @return instance of SockIOPool
*/
public static SchoonerSockIOPool getInstance(String poolName) {
SchoonerSockIOPool pool;
synchronized (pools) {
if (!pools.containsKey(poolName)) {
pool = new SchoonerSockIOPool(true);
pools.putIfAbsent(poolName, pool);
}
}
return pools.get(poolName);
}
public static SchoonerSockIOPool getInstance(String poolName, AuthInfo authInfo) {
SchoonerSockIOPool pool;
synchronized (pools) {
if (!pools.containsKey(poolName)) {
pool = new SchoonerSockIOPool(true);
pool.authInfo = authInfo;
pools.putIfAbsent(poolName, pool);
}
}
return pools.get(poolName);
}
public static SchoonerSockIOPool getInstance(String poolName, boolean isTcp) {
SchoonerSockIOPool pool;
synchronized (pools) {
if (!pools.containsKey(poolName)) {
pool = new SchoonerSockIOPool(isTcp);
pools.putIfAbsent(poolName, pool);
} else {
pool = pools.get(poolName);
if (pool.isTcp() == isTcp)
return pool;
else
return null;
}
}
return pool;
}
/**
* Single argument version of factory used for back compat. Simply creates a
* pool named "default".
*
* @return instance of SockIOPool
*/
public static SchoonerSockIOPool getInstance() {
return getInstance("default", true);
}
public static SchoonerSockIOPool getInstance(AuthInfo authInfo) {
return getInstance("default", authInfo);
}
public static SchoonerSockIOPool getInstance(boolean isTcp) {
return getInstance("default", isTcp);
}
/**
* Initializes the pool.
*/
public void initialize() {
initDeadLock.lock();
try {
// if servers is not set, or it empty, then
// throw a runtime exception
if (servers == null || servers.length <= 0) {
if (log.isErrorEnabled())
log.error("++++ trying to initialize with no servers");
throw new IllegalStateException("++++ trying to initialize with no servers");
}
// pools
socketPool = new HashMap<String, GenericObjectPool>(servers.length);
hostDead = new ConcurrentHashMap<String, Date>();
hostDeadDur = new ConcurrentHashMap<String, Long>();
// only create up to maxCreate connections at once
// initalize our internal hashing structures
if (this.hashingAlg == CONSISTENT_HASH)
populateConsistentBuckets();
else
populateBuckets();
// mark pool as initialized
this.initialized = true;
} finally {
initDeadLock.unlock();
}
}
public boolean isTcp() {
return isTcp;
}
private void populateBuckets() {
// store buckets in tree map
buckets = new ArrayList<String>();
for (int i = 0; i < servers.length; i++) {
if (this.weights != null && this.weights.length > i) {
for (int k = 0; k < this.weights[i].intValue(); k++) {
buckets.add(servers[i]);
}
} else {
buckets.add(servers[i]);
}
// Create a socket pool for each host
// Create an object pool to contain our active connections
GenericObjectPool gop;
SchoonerSockIOFactory factory;
if (authInfo != null) {
factory = new AuthSchoonerSockIOFactory(servers[i], isTcp, bufferSize, socketTO, socketConnectTO,
nagle, authInfo);
} else {
factory = new SchoonerSockIOFactory(servers[i], isTcp, bufferSize, socketTO, socketConnectTO, nagle);
}
gop = new GenericObjectPool(factory, maxConn, GenericObjectPool.WHEN_EXHAUSTED_BLOCK, maxWait, maxIdle,
minIdle, testOnBorrow, testOnReturn, timeBetweenEvictionRunsMillis, numTestsPerEvictionRun,
minEvictableIdleTimeMillis, testWhileIdle, this.softMinEvictableIdleTimeMillis, this.lifo);
factory.setSockets(gop);
socketPool.put(servers[i], gop);
}
}
private void populateConsistentBuckets() {
// store buckets in tree map
consistentBuckets = new TreeMap<Long, String>();
MessageDigest md5 = MD5.get();
if (this.totalWeight <= 0 && this.weights != null) {
for (int i = 0; i < this.weights.length; i++)
this.totalWeight += (this.weights[i] == null) ? 1 : this.weights[i];
} else if (this.weights == null) {
this.totalWeight = this.servers.length;
}
for (int i = 0; i < servers.length; i++) {
int thisWeight = 1;
if (this.weights != null && this.weights[i] != null)
thisWeight = this.weights[i];
double factor = Math.floor(((double) (40 * this.servers.length * thisWeight)) / (double) this.totalWeight);
for (long j = 0; j < factor; j++) {
byte[] d = md5.digest((servers[i] + "-" + j).getBytes());
for (int h = 0; h < 4; h++) {
Long k = ((long) (d[3 + h * 4] & 0xFF) << 24) | ((long) (d[2 + h * 4] & 0xFF) << 16)
| ((long) (d[1 + h * 4] & 0xFF) << 8) | ((long) (d[0 + h * 4] & 0xFF));
consistentBuckets.put(k, servers[i]);
}
}
// Create a socket pool for each host
// Create an object pool to contain our active connections
GenericObjectPool gop;
SchoonerSockIOFactory factory;
if (authInfo != null) {
factory = new AuthSchoonerSockIOFactory(servers[i], isTcp, bufferSize, socketTO, socketConnectTO,
nagle, authInfo);
} else {
factory = new SchoonerSockIOFactory(servers[i], isTcp, bufferSize, socketTO, socketConnectTO, nagle);
}
gop = new GenericObjectPool(factory, maxConn, GenericObjectPool.WHEN_EXHAUSTED_BLOCK, maxWait, maxIdle,
minIdle, testOnBorrow, testOnReturn, timeBetweenEvictionRunsMillis, numTestsPerEvictionRun,
minEvictableIdleTimeMillis, testWhileIdle, this.softMinEvictableIdleTimeMillis, this.lifo);
factory.setSockets(gop);
socketPool.put(servers[i], gop);
}
}
/**
* Closes and removes all sockets from specified pool for host. THIS METHOD
* IS NOT THREADSAFE, SO BE CAREFUL WHEN USING!
*
* Internal utility method.
*
* @param pool
* pool to clear
* @param host
* host to clear
*/
protected void clearHostFromPool(String host) {
GenericObjectPool pool = socketPool.get(host);
pool.clear();
}
/**
* Gets the host that a particular key / hashcode resides on.
*
* @param key
* @return
*/
public final String getHost(String key) {
return getHost(key, null);
}
/**
* Gets the host that a particular key / hashcode resides on.
*
* @param key
* @param hashcode
* @return
*/
public final String getHost(String key, Integer hashcode) {
SchoonerSockIO socket = getSock(key, hashcode);
String host = socket.getHost();
socket.close();
return host;
}
/**
* Returns appropriate SockIO object given string cache key.
*
* @param key
* hashcode for cache key
* @return SockIO obj connected to server
*/
public final SchoonerSockIO getSock(String key) {
return getSock(key, null);
}
/**
* Returns appropriate SockIO object given string cache key and optional
* hashcode.
*
* Trys to get SockIO from pool. Fails over to additional pools in event of
* server failure.
*
* @param key
* hashcode for cache key
* @param hashCode
* if not null, then the int hashcode to use
* @return SockIO obj connected to server
*/
public final SchoonerSockIO getSock(String key, Integer hashCode) {
if (!this.initialized) {
if (log.isErrorEnabled())
log.error("attempting to get SockIO from uninitialized pool!");
return null;
}
// if no servers return null
int size = 0;
if ((this.hashingAlg == CONSISTENT_HASH && consistentBuckets.size() == 0)
|| (buckets != null && (size = buckets.size()) == 0))
return null;
else if (size == 1) {
SchoonerSockIO sock = (this.hashingAlg == CONSISTENT_HASH) ? getConnection(consistentBuckets
.get(consistentBuckets.firstKey())) : getConnection(buckets.get(0));
return sock;
}
// from here on, we are working w/ multiple servers
// keep trying different servers until we find one
// making sure we only try each server one time
Set<String> tryServers = new HashSet<String>(Arrays.asList(servers));
// get initial bucket
long bucket = getBucket(key, hashCode);
String server = (this.hashingAlg == CONSISTENT_HASH) ? consistentBuckets.get(bucket) : buckets
.get((int) bucket);
while (!tryServers.isEmpty()) {
// try to get socket from bucket
SchoonerSockIO sock = getConnection(server);
if (sock != null)
return sock;
// if we do not want to failover, then bail here
if (!failover)
return null;
// log that we tried
tryServers.remove(server);
if (tryServers.isEmpty())
break;
// if we failed to get a socket from this server
// then we try again by adding an incrementer to the
// current key and then rehashing
int rehashTries = 0;
while (!tryServers.contains(server)) {
String newKey = new StringBuffer().append(rehashTries).append(key).toString();
// String.format( "%s%s", rehashTries, key );
bucket = getBucket(newKey, null);
server = (this.hashingAlg == CONSISTENT_HASH) ? consistentBuckets.get(bucket) : buckets
.get((int) bucket);
rehashTries++;
}
}
return null;
}
/**
* Returns a SockIO object from the pool for the passed in host.
*
* Meant to be called from a more intelligent method<br/>
* which handles choosing appropriate server<br/>
* and failover.
*
* @param host
* host from which to retrieve object
* @return SockIO object or null if fail to retrieve one
*/
public final SchoonerSockIO getConnection(String host) {
if (!this.initialized) {
if (log.isErrorEnabled())
log.error("attempting to get SockIO from uninitialized pool!");
return null;
}
if (host == null)
return null;
if (!failback && hostDead.containsKey(host) && hostDeadDur.containsKey(host)) {
Date store = hostDead.get(host);
long expire = hostDeadDur.get(host).longValue();
if ((store.getTime() + expire) > System.currentTimeMillis())
return null;
}
// if we have items in the pool then we can return it
GenericObjectPool sockets = socketPool.get(host);
SchoonerSockIO socket;
try {
socket = (SchoonerSockIO) sockets.borrowObject();
} catch (Exception e) {
socket = null;
}
if (socket == null) {
Date now = new Date();
hostDead.put(host, now);
long expire = (hostDeadDur.containsKey(host)) ? (((Long) hostDeadDur.get(host)).longValue() * 2) : 1000;
if (expire > MAX_RETRY_DELAY)
expire = MAX_RETRY_DELAY;
hostDeadDur.put(host, new Long(expire));
// also clear all entries for this host from availPool
sockets.clear();
}
return socket;
}
/**
* Closes all sockets in the passed in pool.
*
* Internal utility method.
*
* @param pool
* pool to close
*/
protected final void closeSocketPool() {
for (Iterator<GenericObjectPool> i = socketPool.values().iterator(); i.hasNext();) {
GenericObjectPool sockets = i.next();
try {
sockets.close();
} catch (Exception e) {
if (log.isErrorEnabled())
log.error("++++ failed to close socket pool.");
}
}
}
/**
* Shuts down the pool.
*
* Cleanly closes all sockets.<br/>
* Stops the maint thread.<br/>
* Nulls out all internal maps<br/>
*/
public void shutDown() {
closeSocketPool();
socketPool.clear();
socketPool = null;
buckets = null;
consistentBuckets = null;
initialized = false;
}
/**
* Returns state of pool.
*
* @return <CODE>true</CODE> if initialized.
*/
public final boolean isInitialized() {
return initialized;
}
/**
* Sets the list of all cache servers.
*
* @param servers
* String array of servers [host:port]
*/
public final void setServers(String[] servers) {
this.servers = servers;
}
/**
* Returns the current list of all cache servers.
*
* @return String array of servers [host:port]
*/
public final String[] getServers() {
return this.servers;
}
/**
* Sets the list of weights to apply to the server list.
*
* This is an int array with each element corresponding to an element<br/>
* in the same position in the server String array.
*
* @param weights
* Integer array of weights
*/
public final void setWeights(Integer[] weights) {
this.weights = weights;
}
/**
* Returns the current list of weights.
*
* @return int array of weights
*/
public final Integer[] getWeights() {
return this.weights;
}
/**
* Sets the initial number of connections per server in the available pool.
*
* @param initConn
* int number of connections
*/
public final void setInitConn(int initConn) {
if (initConn < minConn)
minConn = initConn;
}
/**
* Returns the current setting for the initial number of connections per
* server in the available pool.
*
* @return number of connections
*/
public final int getInitConn() {
return this.minConn;
}
/**
* Sets the max busy time for threads in the busy pool.
*
* @param maxBusyTime
* idle time in ms
*/
public final void setMaxBusyTime(long maxBusyTime) {
this.maxBusyTime = maxBusyTime;
}
/**
* Returns the current max busy setting.
*
* @return max busy setting in ms
*/
public final long getMaxBusy() {
return this.maxBusyTime;
}
/**
* Set the sleep time between runs of the pool maintenance thread. If set to
* 0, then the maint thread will not be started.
*
* @param maintSleep
* sleep time in ms
*/
public void setMaintSleep(long maintSleep) {
this.maintSleep = maintSleep;
}
/**
* Returns the current maint thread sleep time.
*
* @return sleep time in ms
*/
public long getMaintSleep() {
return this.maintSleep;
}
/**
* Sets the socket timeout for reads.
*
* @param socketTO
* timeout in ms
*/
public final void setSocketTO(int socketTO) {
this.socketTO = socketTO;
}
/**
* Returns the socket timeout for reads.
*
* @return timeout in ms
*/
public final int getSocketTO() {
return this.socketTO;
}
/**
* Sets the socket timeout for connect.
*
* @param socketConnectTO
* timeout in ms
*/
public final void setSocketConnectTO(int socketConnectTO) {
this.socketConnectTO = socketConnectTO;
}
/**
* Returns the socket timeout for connect.
*
* @return timeout in ms
*/
public final int getSocketConnectTO() {
return this.socketConnectTO;
}
/**
* Sets the max idle time for threads in the available pool.
*
* @param maxIdle
* idle time in ms
*/
public void setMaxIdle(int maxIdle) {
this.maxIdle = maxIdle;
}
/**
* Returns the current max idle setting.
*
* @return max idle setting in ms
*/
public int getMaxIdle() {
return this.maxIdle;
}
public final long getMaxWait() {
return this.maxWait;
}
public final void setMaxWait(long maxWait) {
this.maxWait = maxWait;
}
public final int getMinIdle() {
return minIdle;
}
public final void setMinIdle(int minIdle) {
this.minIdle = minIdle;
}
public final boolean getTestOnBorrow() {
return testOnBorrow;
}
public final void setTestOnBorrow(boolean testOnBorrow) {
this.testOnBorrow = testOnBorrow;
}
public final boolean getTestOnReturn() {
return testOnReturn;
}
public final void setTestOnReturn(boolean testOnReturn) {
this.testOnReturn = testOnReturn;
}
public final long getTimeBetweenEvictionRunsMillis() {
return this.timeBetweenEvictionRunsMillis;
}
public final void setTimeBetweenEvictionRunsMillis(long timeBetweenEvictionRunsMillis) {
this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
}
public final int getNumTestsPerEvictionRun() {
return this.numTestsPerEvictionRun;
}
public final void setNumTestsPerEvictionRun(int numTestsPerEvictionRun) {
this.numTestsPerEvictionRun = numTestsPerEvictionRun;
}
public final long getMinEvictableIdleTimeMillis() {
return this.minEvictableIdleTimeMillis;
}
public final void setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis) {
this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
}
public final boolean getTestWhileIdle() {
return this.testWhileIdle;
}
public final void setTestWhileIdle(boolean testWhileIdle) {
this.testWhileIdle = testWhileIdle;
}
public final long getSoftMinEvictableIdleTimeMillis(long softMinEvictableIdleTimeMillis) {
return this.softMinEvictableIdleTimeMillis;
}
public final void setSoftMinEvictableIdleTimeMillis(long softMinEvictableIdleTimeMillis) {
this.softMinEvictableIdleTimeMillis = softMinEvictableIdleTimeMillis;
}
public final boolean getLifo() {
return this.lifo;
}
public final void setLifo(boolean lifo) {
this.lifo = lifo;
}
/**
* Sets the failover flag for the pool.
*
* If this flag is set to true, and a socket fails to connect,<br/>
* the pool will attempt to return a socket from another server<br/>
* if one exists. If set to false, then getting a socket<br/>
* will return null if it fails to connect to the requested server.
*
* @param failover
* true/false
*/
public final void setFailover(boolean failover) {
this.failover = failover;
}
/**
* Returns current state of failover flag.
*
* @return true/false
*/
public final boolean getFailover() {
return this.failover;
}
/**
* Sets the failback flag for the pool.
*
* If this is true and we have marked a host as dead, will try to bring it
* back. If it is false, we will never try to resurrect a dead host.
*
* @param failback
* true/false
*/
public void setFailback(boolean failback) {
this.failback = failback;
}
/**
* Returns current state of failover flag.
*
* @return true/false
*/
public boolean getFailback() {
return this.failback;
}
/**
* Sets the aliveCheck flag for the pool.
*
* When true, this will attempt to talk to the server on every connection
* checkout to make sure the connection is still valid. This adds extra
* network chatter and thus is defaulted off. May be useful if you want to
* ensure you do not have any problems talking to the server on a dead
* connection.
*
* @param aliveCheck
* true/false
*/
public final void setAliveCheck(boolean aliveCheck) {
this.aliveCheck = aliveCheck;
}
/**
* Returns the current status of the aliveCheck flag.
*
* @return true / false
*/
public final boolean getAliveCheck() {
return this.aliveCheck;
}
/**
* Sets the Nagle alg flag for the pool.
*
* If false, will turn off Nagle's algorithm on all sockets created.
*
* @param nagle
* true/false
*/
public final void setNagle(boolean nagle) {
this.nagle = nagle;
}
/**
* Returns current status of nagle flag
*
* @return true/false
*/
public final boolean getNagle() {
return this.nagle;
}
/**
* Sets the hashing algorithm we will use.
*
* The types are as follows.
*
* SockIOPool.NATIVE_HASH (0) - native String.hashCode() - fast (cached) but
* not compatible with other clients SockIOPool.OLD_COMPAT_HASH (1) -
* original compatibility hashing alg (works with other clients)
* SockIOPool.NEW_COMPAT_HASH (2) - new CRC32 based compatibility hashing
* algorithm (fast and works with other clients)
*
* @param alg
* int value representing hashing algorithm
*/
public final void setHashingAlg(int alg) {
this.hashingAlg = alg;
}
/**
* Returns current status of customHash flag
*
* @return true/false
*/
public final int getHashingAlg() {
return this.hashingAlg;
}
/**
* Internal private hashing method.
*
* This is the original hashing algorithm from other clients. Found to be
* slow and have poor distribution.
*
* @param key
* String to hash
* @return hashCode for this string using our own hashing algorithm
*/
private static long origCompatHashingAlg(String key) {
long hash = 0;
char[] cArr = key.toCharArray();