Here is my class:
In this class I am trying to implement the Singleton design patter with double check synchronization so only one instance of Session object presents in my application at any time.
However this synchronization does not quite work, can you figure out why ? Well the problem, as it turns out is the, static modifier, quoting from Oracles Java tutorials
staticmodifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. All instances of some class shares its class variables, which is in a one fixed location in memory. Any object can change the value of a class variable, if its modifier allows to, but class variables can also be manipulated without creating an instance of a class
Now notice the synchronized block in the code, the lock I am using to synchronize the lazy creation of Session object is “this” keyword which is associated with(refers to) a particular instance of the class DefaultCassandraDriver, meaning that if two instance of this class are created and two different threads call createSession method on the two the different instances and return the created session they can concurrently create two different instance of the Session object because each thread will acquire a different lock object to modify the same variable session.
Multithread programming is one of the most complex aspect of programming so careful with it and always double and triple check your code before sending it to production.