Singleton for multithreading in Java

October 26, 2014
1 min read

​Everyone knows what is singleton pattern, but how to implement a singleton class in multithreaded environment? Next, I’m going to present best approaches for this use case.

Bill Pugh Singleton Implementation


public class Singleton {
	private Singleton() { }

	private static class SingletonHolder {
		private static final Singleton INSTANCE = new Singleton();
	}

	public static Singleton getInstance() {
		return SingletonHolder.INSTANCE;
	} 
}

Thread Safe Double Checked Singleton Implementation


public class Singleton {
	private static Singleton instance;

	private Singleton() { }

	public static Singleton getInstance() {
		if(instance == null) {
			synchronize (Singleton.class) {
				if(instance == null) {
					instance = new Singleton();
				}
			}
		}
		return instance;
	} 
}

Share on:

Want to stay on top of everything?

Get updates on industry developments and the software solutions we can now create for a smooth digital transformation.

* I read and understood the ASSIST Software website's terms of use and privacy policy.

Frequently Asked Questions

ASSIST Software Team Members

See the past, present and future of tech through the eyes of an experienced Romanian custom software company. The ASSIST Insider newsletter highlights your path to digital transformation.

* I read and understood the ASSIST Software website's terms of use and privacy policy.

Follow us

© 2024 ASSIST Software. All rights reserved. Designed with love.