This post is not another Java synchronization tutorial in this post I will discuss an error code that a colleague of mine commented during a code review – which is extremely important and useful for clean and minimum bugs provided code.

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 

Fields that have the static modifier 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
The problem here is that I’ve declared Session object to be static meaning that I will have only on Session object in mu application,  associated with the class not its concrete instances.
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. 
To solve the problem we modify our class like this:
Here we introduced a private static lock that will be associated with the class and when two thread tries to concurrently call createSession method even called on two instance of DafaultCassandraDriver class.
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.
Thanks for reading.

Leave a comment

Your email address will not be published. Required fields are marked *