Yes, you need to make getInstance()
synchronized. If it's not there might arise a situation where multiple instances of the class can be made.
Consider the case where you have two threads that call getInstance()
at the same time. Now imagine T1 executes just past the instance == null
check, and then T2 runs. At this point in time the instance is not created or set, so T2 will pass the check and create the instance. Now imagine that execution switches back to T1. Now the singleton is created, but T1 has already done the check! It will proceed to make the object again! Making getInstance()
synchronized prevents this problem.
There a few ways to make singletons thread-safe, but making getInstance()
synchronized is probably the simplest.