【发布时间】:2017-04-26 10:25:37
【问题描述】:
This doc guides how to use Cassandra prepared and bound statements.
上面写着:
您应该只准备一次,并将 PreparedStatement 缓存在您的 应用程序(它是线程安全的)。 ... BoundStatement 不是 线程安全。您可以使用不同的方式多次重用一个实例 参数,但仅来自单个线程并且仅当您使用 同步调用:
BoundStatement bound = ps1.bind();
// This is safe:
bound.setString("sku", "324378");
session.execute(bound);
bound.setString("sku", "324379");
session.execute(bound);
// This is NOT SAFE. executeAsync runs concurrently with your code, so the first execution might actually read the
// values after the second setString call, and you would insert 324381 twice:
bound.setString("sku", "324380");
session.executeAsync(bound);
bound.setString("sku", "324381");
session.executeAsync(bound);
很明显上面不是线程安全的,但是如果我们这样改代码:
BoundStatement bound1 = ps1.bind();
BoundStatement bound2 = ps1.bind();
bound1.setString("sku", "324380");
session.executeAsync(bound1);
bound2.setString("sku", "324381");
session.executeAsync(bound2);
即:多个线程使用共同的PreparedStatement,每个线程使用自己的BoundStatement。
1) 这个线程安全吗?
2) 这是否是使用准备好的语句进行并行执行的其他推荐方法?或者 BoundStatements 是否昂贵/创建速度慢/消耗大量内存等原因来保持它们的数量较少?
【问题讨论】:
标签: java multithreading cassandra thread-safety prepared-statement