Image for post
Image for post
A source code with Threads usage —

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.
  • If CPU has multiple cores(parallelism is possible), resources are not being used efficiently.

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.

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.

Above code gives same references as per below

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.

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

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 ).

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

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! :)

Written by

Software Engineer at 99x | Apache PMC member | Open Source Contributor (Author of Neutralinojs) | Technical Writer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store