A source code with Threads usage — lynda.com

Understanding thread safe methods with practical example of a Singleton class

So multi-threading! was very popular topic and nowadays it is being used in numerous applications of computer science. Single threaded models are having various sorts of drawbacks because,

  • Each instruction is executed in sequence manner; there is no parallel approach.

Let’s back to topic. What is thread?

In computer science, a thread of execution is the smallest sequence of programmed instructions that can be managed independently by a scheduler, which is typically a part of the operating system — Wikipedia

Thread safety

Let’s begin with a practical example. We are going to create a simple singleton class without using thread safe mechanisms.

public class SingletonSample {
private static SingletonSample instance = null;

private SingletonSample() {}

static SingletonSample getInstance () {
if(instance == null) {
instance = new SingletonSample();
}
return instance;
}
}

Singleton should return same object reference all the time. This class will work fine in single thread. SingletonSample getInstance() will return same instance since code snippet calls new SingletonSample(); only one time.

for(int i = 0; i < 4; i++){
System.out.println(SingletonSample.getInstance().hashCode());
}

Above code gives same references as per below

366712642
366712642
366712642
366712642

Now we are going to do the same but with multi-threading approach. Let’s see what will be the output for portion of code shown in below.

public class SingletonSampleThreads extends Thread {@Override

public void run() {
System.out.println(SingletonSample.getInstance().hashCode());
}


public static void main(String[] args) {
for(int i = 0; i < 4; i++){
new SingletonSampleThreads().start();
}

}
}

Note that this output may give different patterns. you may get same references too.

1740525517
1740525517
1740525517
1062666470 <- Singleton seriously!! 🧐

Why we are getting different references?. The reason is that multiple threads will access the Singleton class and its static method. Think! thread T1 and T2 are running parallel; assume T1 and T2 access if(instance == null) same time, the condition is true for both threads and two objects will be created by T1 and T2. Eventually SingletonSample.getInstance() gives us different references.

Thread safe methods

We can block the concurrent access using synchronized keyword. When T1 and T2 are trying to execute SingletonSample.getInstance() synchronized keyword limits the concurrent access for only one thread. Therefore other thread is going to wait until previous thread modifies data (then instance != null ).

public class SingletonSample {
private static SingletonSample instance = null;

private SingletonSample() {}

static synchronized SingletonSample getInstance () {
if(instance == null) {
instance = new SingletonSample();
}
return instance;
}
}

When we execute same driver code for above class. program will return same references as per expected.

1740525517
1740525517
1740525517
1740525517

Source code is on Github. Having an idea to write another article about locks and mutex. See you soon!

Please note that instead just printing object reference I used java.lang.Object.hashCode() which gives an integer hash value.

Happy multi-threading! :)

Programmer | Author of Neutralinojs | Technical Writer

Programmer | Author of Neutralinojs | Technical Writer