Java – Singleton Design Pattern

The singleton is a creational design pattern. It is useful when you want only one instance of an object regardless of how many times you try to instantiate new instances of it.

Java example

We have a Time class and we want to always have a single instance of it. To do this we set the constructor to private (so we can’t call new Time()).

Then we make sure an instance of Time() can only be acquired from the getInstance() method. This one checks if the instance hasn’t been already initialized. If so, it returns the existing one.

If not, it will create a new one. We wrapped the second check in a synchronized block so only one thread can enter the method.

If we hadn’t done so there was a risk that in a multi threaded environment two threads might enter one after another and create two instances instead of one. Just consider the first thread entered and it is at the following line:

if (instance == null)

The condition is true and proceeds inside of the if statement. But the OS puts it aside and let’s the other thread to the same thing. The second thread checks the above line and the result is also true (remember: first thread didn’t had the chance yet to initialize the object so it’s still null).

Now we have both threads in the if statement and both will execute new Time() and we do not want that.

package net.superglobals.tutorials;

public class Time {
	private long time;
	private static Time instance = null;
	
	private Time() {
		time = System.currentTimeMillis();
	}
	
	public static Time getInstance() {
		if (instance == null) {
			synchronized (Time.class) {
				if (instance == null) {
					instance = new Time();
				}
			}
		}
		return instance;
	}
	
	public long getTime() {
		return time;
	}
}

Test class. We ask the current thread to sleep for 5 seconds then try to create a completely new Time() object. As you can see, both have the same value for time because the constructor was called only once.

package net.superglobals.tutorials;

public class Main {
	public static void main(String[] args) throws InterruptedException {
		Time t = Time.getInstance();
		System.out.println(t.getTime());
		
		Thread.sleep(5000);
		
		Time j = Time.getInstance();
		System.out.println(j.getTime());
	}
}

Output:

1442677660022
1442677660022
FacebookTwitterLinkedin