【发布时间】:2018-08-27 06:51:44
【问题描述】:
有一个类 RedisLogger.java 用来处理 redis 的 logger。在 RedisLogger.java 中,我使用以下代码声明了一个静态 JedisPool 字段 jedisPool:
private static JedisPool jedisPool;
因为 JedisPool 是线程安全的类,我想使用以下代码在我的应用程序中只实例化一次 jedisPool:
public static JedisPool getJedisPool() {
if(jedisPool == null) {
synchronized (JedisPool.class) {
if(jedisPool == null) {
jedisPool = new JedisPool();
}
}
}
return jedisPool;
}
我用这段代码来测试它。
ExecutorService executor = Executors.newCachedThreadPool();
for(int i = 0; i < 1000; i++) {
executor.execute(()->{
System.out.println(RedisLogger.getJedisPool());
});
}
从输出看来效果不错:
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
....
但它真的能达到我的期望吗? 因为我的申请中有很多这样的地方。例如。
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;
}
谢谢!!!
【问题讨论】:
-
但真的能达到我的预期吗。它应该。为什么不应该呢?你看到不一致了吗?我们不知道您的代码,因此我们无法通过查看您的最后一个 sn-p 来判断它是否有效。我们需要全貌,但这会打破这个问题的框架
标签: java multithreading static synchronized