0
votes

I'm developing a multi-threaded application in which each thread accesses Cassandra in Java. Shall I create multiple clusters and close them after each access or multiple sessions? Can I create the cluster or the session as static data members?

Here is the log I got when declaring both as static:

14:40:50.361 [cluster1-nio-worker-0] DEBUG com.datastax.driver.core.Connection - Connection[localhost/127.0.0.1:9042-1, inFlight=0, closed=false] was inactive for 30 seconds, sending heartbeat
14:40:50.361 [cluster1-nio-worker-0] DEBUG com.datastax.driver.core.Connection - Connection[localhost/127.0.0.1:9042-1, inFlight=0, closed=false] heartbeat query succeeded
1

1 Answers

3
votes

If you are writing a multi-thread application I would create Cluster and Session as static member. Session maintain multiple threads per instance and is thread-safe. I would use one Session object per keyspace.

From cassandra-java-driver docs:

Session instances are thread-safe and usually a single instance is enough per application. As a given session can only be "logged" into one keyspace at a time (where the "logged" keyspace is the one used by query if the query doesn't explicitely use a fully qualified table name), it can make sense to create one session per keyspace used. This is however not necessary to query multiple keyspaces since it is always possible to use a single session with fully qualified table name in queries.