Re-using PreparedStatement when using Datastax Cassandra Driver?

TinusSky picture TinusSky · Apr 7, 2014 · Viewed 14.4k times · Source

I'm currently using the Datastax Cassandra driver for Cassandra 2 to execute cql3. This works correctly. I started using PreparedStatement's:

Session session = sessionProvider.getSession();
try {
    PreparedStatement ps = session.prepare(cql);
    ResultSet rs = session.execute(ps.bind(objects));
    if (irsr != null) {
       irsr.read(rs);
    }
}

Sometimes I get a warning from the driver in my log:

Re-preparing already prepared query . Please note that preparing the same query more than once is generally an anti-pattern and will likely affect performance. Consider preparing the statement only once.

This warning makes sense, but i'm not sure how i should reuse the PreparedStatement?

Should I just create all my PreparedStatement in a constructor/init method and than simply use them?

But does this go well when multiple threads use the same PreparedStatement at the same time (especially calling PreparedStatement.bind() to bind objects)

Answer

Daniel S. picture Daniel S. · Apr 7, 2014

You may just initialize the PreparedStatement once and cache it while the app is running. It should be available for use as long as the Cassandra cluster is up.

Using the statement from multiple threads is fine (as long as you don't modify it throught setXXX() methods). When you call bind(), the code underneath only reads the PreparedStatement and then creates a new instance of BoundStatement() which the caller thread is then free to mutate.

Here is the source code, if you're curious (search for bind()).