私はCassandraと協力し、Datastax Javaドライバを使用しています。準備した文をキャッシュして再利用しようとしています。"putIfAbsent"はCHMでどのように機能しますか?
private static final ConcurrentHashMap<String, PreparedStatement> holder = new ConcurrentHashMap<>();
public BoundStatement getStatement(String cql) {
Session session = TestUtils.getInstance().getSession();
PreparedStatement ps = holder.get(cql);
// no statement is cached, create one and cache it now.
if (ps == null) {
holder.putIfAbsent(cql, session.prepare(cql));
}
return ps.bind();
}
Prepared StatementおよびBoundStatementのdatastax java driverです。
このgetStatement
メソッドは複数のスレッドで呼び出されるため、スレッドセーフであることを確認する必要があります。私はJava 7で作業しています。
2つの同じcqlプリペアドステートメントを取得すると、putIfAbsent
はどうなりますか?コードスレッドは安全で、競合状態はありませんか?
アップデート: -
public BoundStatement getStatement(String cql) {
Session session = TestUtils.getInstance().getSession();
PreparedStatement ps = holder.get(cql);
// no statement is cached, create one and cache it now.
if (ps == null) {
synchronized (this) {
ps = holder.get(cql);
if (ps == null) {
ps = session.prepare(cql);
holder.put(cql, ps);
}
}
}
return ps.bind();
}
今はどうですか?それは正しいか? – john
はい、そうです。 – Holger