作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个下面的 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/
我是一名优秀的程序员,十分优秀!