1

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昂贵/慢创建/消耗大量内存等原因,以保持其数量低?

回答

2

简短的回答是,如果你正在考虑使用同一个PreparedStatement对象多次,但使用不同的参数,每次使用不同BoundStatement对象界,那么它是线程安全的,因为PreparedStatement是线程安全的,所以你可以resuse其多线程和BoundStatement不是线程安全的,所以你每次都有不同的对象。

只要是明确的 - 所以,你的线程1将创建您使用ps1 = session.prepare("insert into product (sku, description) values (?, ?)");准备语句和所有其他线程将使用此ps1对象来创建自己的BoundStatement对象,因为每次都会有自己的价值观传递,例如:

线程1将结合并执行作为(注意使用相同ps1对象):

BoundStatement bound = ps1.bind().setString("sku", "001").setString("description", "LCD screen"); 
session.execute(bound); 

线程2将结合并执行作为(注意使用相同ps1对象):

BoundStatement bound = ps1.bind().setString("sku", "002").setString("description", "TFT screen"); 
session.execute(bound); 

线程3将结合并执行作为(注意使用相同ps1对象):

BoundStatement bound = ps1.bind().setString("sku", "003").setString("description", "LED screen"); 
session.execute(bound); 

在简而言之:主要性能成本招致在创建PreparedStatement对象,因为它往返DB服务器(见下面的描述),所以你重复使用它,并且它是线程安全的,而你每次创建一个单独的BoundStatement,因为它不是线程安全的,也不是一个沉重的创建对象并且不需要往返DB服务器。

enter image description here

+0

感谢您的明确答案。希望他们将这些信息添加到下一版Cassandra手册中。 – user4955663