Best Way to Create a Singleton in Java

Nil Seri
2 min readMay 8, 2021

--

Photo by Maxwell Dugan on Unsplash

In my Java project (where I did not use Spring Boot), I had to create a Cassandra connector class. I decided to make it a Singleton to create just one session object in the project as referred here:

https://stackoverflow.com/questions/57141458/how-to-create-a-cassandra-connection-pool-using-datastax-driver

“You just need to create one Session object per your application, and then driver will do all necessary pooling for you. Cassandra protocol allows to execute multiple queries over the one connection, and everything just work out of box - you can execute queries from multiple threads using the same Session object. If necessary (but you need to have a good reason for it), you can increase number of connections from driver to every host in cluster, but in the big cluster this may lead to increased resource consumption.

The complete description on how the pooling is implemented is in the driver’s documentation.”

As I searched for the best way to create a singleton in Java and refresh my knowledge about Java Design Patterns, I came across Bill Pugh Singleton Implementation and Initialization-on-demand holder:

This is my implementation:

Happy Coding!

--

--

Nil Seri
Nil Seri

Written by Nil Seri

I would love to change the world, but they won’t give me the source code | coding 👩🏻‍💻 | coffee ☕️ | jazz 🎷 | anime 🐲 | books 📚 | drawing 🎨

No responses yet