Thursday, July 4, 2013

How to Implement Singleton in Java

There are multiple solutions for this. Let me describe one by one.

Solution 1:

Solution 2:
Compared to Solution 1, this one is easier to change the singularity if things change.

Solution 3:
Compared to Solutions 1 and 2, this one is lazy instantiation and used double checked locking. Do not synchronize the method instead because for most cases if the instance is already initialized, threads want to return right away. Also, note the volatile in Line 2. This is used to avoid the out-of-order issue of double checked locking solution.

Solution 4:
This is a preferred solution as of Java v5.0.

No comments:

Post a Comment