There is a class RedisLogger.java which used to deal with logger with redis. In RedisLogger.java, I declared a static JedisPool field jedisPool
using this code:
private static JedisPool jedisPool;
Cause JedisPool is thread-safe calss, I want to instantiate jedisPool
only once in my application by using the following code:
public static JedisPool getJedisPool() {
if(jedisPool == null) {
synchronized (JedisPool.class) {
if(jedisPool == null) {
jedisPool = new JedisPool();
}
}
}
return jedisPool;
}
I used this code to test it.
ExecutorService executor = Executors.newCachedThreadPool();
for(int i = 0; i < 1000; i++) {
executor.execute(()->{
System.out.println(RedisLogger.getJedisPool());
});
}
It seems works well from output :
redis.clients.jedis.JedisPool@3d11fc5d
redis.clients.jedis.JedisPool@3d11fc5d
redis.clients.jedis.JedisPool@3d11fc5d
redis.clients.jedis.JedisPool@3d11fc5d
redis.clients.jedis.JedisPool@3d11fc5d
redis.clients.jedis.JedisPool@3d11fc5d
redis.clients.jedis.JedisPool@3d11fc5d
redis.clients.jedis.JedisPool@3d11fc5d
redis.clients.jedis.JedisPool@3d11fc5d
redis.clients.jedis.JedisPool@3d11fc5d
redis.clients.jedis.JedisPool@3d11fc5d
redis.clients.jedis.JedisPool@3d11fc5d
redis.clients.jedis.JedisPool@3d11fc5d
....
But can it really achieve my expectations? Becasue there are many places like this in my application. for example.
private static Cluster getCluster() {
if(cluster == null) {
synchronized (Cluster.class) {
if(cluster == null) {
Builder builder = Cluster.builder();
for (int i = 0; i < MSConfig.SRCDOC_CASSANDRA_ADDRS().length; i++) {
builder.addContactPoint(MSConfig.SRCDOC_CASSANDRA_ADDRS()[i])
.withPort(MSConfig.SRCDOC_CASSANDRA_PORT()[i]);
}
cluster = builder.withCredentials(MSConfig.SRCDOC_CASSANDRA_USERNMAE(), MSConfig.SRCDOC_CASSANDRA_PASSWORD())
.withProtocolVersion(ProtocolVersion.V4)
.withPoolingOptions(getPoolingOptions())
.withSocketOptions(getSocketOptions())
.withRetryPolicy(getRetryPolicy())
.withQueryOptions(getQueryOptions())
.build();
}
}
}
return cluster;
}
Thanks!!!