Search code examples
cassandrasingletonprepared-statement

PreparedStatement should be prepared once in a singleton class and then reference in the DAO implementation


PreparedStatement is being created in every call and hence there are performance impacts due to load. Hence, I need to make sure that the PreparedStatement should be prepared once in a singleton class and reused again. How to achive this? Can anoyone give a sample code for this please?


Solution

  • In the simplest case it could be like this:

    public class PrepStatementCache {
      private static ConcurrentHashMap<String, PreparedStatement> cache = new ConcurrentHashMap<>();
    
      static PreparedStatement getStatement(Session session, final String query) {
        return cache.computeIfAbsent(query,  q -> session.prepare(query));
      }
    }
    

    but because the map could be blocked during computation, then it could be better to implement function getStatement as following:

      static PreparedStatement getStatement(Session session, final String query) {
        PreparedStatement preparedStatement = cache.get(query);
        if (preparedStatement == null) {
          preparedStatement = session.prepare(query);
          if (preparedStatement != null) {
            PreparedStatement p2 = cache.putIfAbsent(query, preparedStatement);
            preparedStatement = p2 == null ? preparedStatement : p2;
          }
        }
    
        return preparedStatement;
      }
    

    But take into account, that for Java driver 4, this is done automatically, so if you're starting the new project, then it's better to use it as it contains more functionality.