gpt4 book ai didi

java - 我的 getStatement 方法线程安全吗?

转载 作者:行者123 更新时间:2023-11-29 04:37:18 26 4
gpt4 key购买 nike

我有一个下面的 Singleton 类,在我的 getStatement 方法中,我通过执行 if 检查来填充 CHM。

public class CacheHolder {
private static final Map<String, PreparedStatement> holder = new ConcurrentHashMap<>();

private static class Holder {
private static final CacheHolder INSTANCE = new CacheHolder();
}

public static CacheHolder getInstance() {
return Holder.INSTANCE;
}

private CacheHolder() {}

public BoundStatement getStatement(String cql) {
Session session = TestUtils.getInstance().getSession();
PreparedStatement ps = holder.get(cql);
if (ps == null) {
ps = session.prepare(cql);
holder.put(cql, ps);
}
return ps.bind();
}
}

我的 getStatement 方法线程安全吗?

最佳答案

@javaguy 提供的答案是正确的,但只是一个小的优化,以确保在不需要时不会为每个线程执行同步块(synchronized block)。

public static BoundStatement getStatement(String cql) {
PreparedStatement ps = null;
Session session = null;
try {
session = TestUtils.getInstance().getSession();
PreparedStatement ps = holder.get(cql);
if(ps == null) { // If PS is already present in cache, then we don't have to synchronize and make threads wait.
synchronized {
ps = holder.get(cql);
if (ps == null) {
ps = session.prepare(cql);
holder.put(cql, ps);
}
}
}
} finally {
//release the resources
}
return ps.bind();
}

您还可以使用 Guava Cache或者如果你想要一张 map ,那么 Guava MapMaker .

使用 Guava 缓存:

LoadingCache<String, PreparedStatement> cache = CacheBuilder.newBuilder()
.maximumSize(1000)
.expireAfterWrite(10, TimeUnit.MINUTES)
.build(
new CacheLoader<String, PreparedStatement>() {
public PreparedStatement load(String cql) throws Exception {
return createPreparedStatement(cql);
}
});

使用 map 制作工具:

ConcurrentMap<String, PreparedStatement> cache = new MapMaker()
.concurrencyLevel(32)
.weakValues()
.makeComputingMap(
new Function<String, PreparedStatement>() {
public PreparedStatement apply(String cql) {
return createPreparedStatement(cql);
}
});

此外,我建议不要缓存 PreparedStatement 的,因为这些资源需要释放 AFAIK。

关于java - 我的 getStatement 方法线程安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40794939/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com