Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Datastax - Is PreparedStatement threadsafe?

Should a com.datastax.driver.core.PreparedStatement instance be a singleton in an application ?

If so, what happens if the connection is lost ? Does the PreparedStatement become invalid and a manual action must be taken to 'reprepare it' ?

A simple example of PreparedStatement usage (other than preparing + executing in the same method) would be brilliant !

like image 253
user2373241 Avatar asked May 11 '13 16:05

user2373241


1 Answers

PreparedStatement objects are threadsafe. You can mutate them (setting the default consistency level for example) in ways that could lead to inconsistencies if multiple threads did that simultaneously, but that’s anorher thing.

Prepared statements are basically wrappers around an ID and metadata, and the server will keep the prepared statement for as long as it is up (but a node crash or restart will mean that it is lost and has to be reprepared). In theory a prepared statement could be serialized and deserialized somewhere else and still work, bit I wouldn’t recommend it.

Prepared statements are local to a node, and as I mentioned, do not survive restarts, so if you’re going to keep them around you need to be sure that you clean them out when connections fail or nodes restart. I would try to scope them the same way you scope your connections, recreate them on connects and reconnects. Maybe not great advice, but it depends so much on how your application is structured.

like image 75
Theo Avatar answered Sep 27 '22 22:09

Theo