Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Java Singleton Template for Eclipse (See related posts)

This is a template for easily creating an implementation of the Singleton Pattern on Eclipse. Open Window->Preferences->Java->Editor->Templates click on New and insert the code below on the pattern text area; add a name (I suggest "singleton") - whenever you type this name and press Ctrl+Space the code will be inserted in your class - and you're good to go.

private static ${enclosing_type} instance;

private ${enclosing_type}(){}

public static ${enclosing_type} getInstance(){
	if(null == instance){
		instance = new ${enclosing_type}();
	}
	return instance;
}

Comments on this post

salient1 posts on Mar 02, 2007 at 18:22
Unfortunately this isn't the correct way to code a singleton in Java. The object needs to be instantiated on the line it's defined. Your if check is just creating a race condition that will not guarantee you a single instance.
khattaksd posts on Mar 04, 2007 at 09:32
see here for brief intro to concurrent programming and how this code will create a race condition
http://java.sun.com/developer/Books/performance2/chap3.pdf
khattaksd posts on Mar 04, 2007 at 10:34
my previous comment got screwed and there is no way to delete it so sorry and here goes

http://jroller.com/trackback/need2know/Weblog/race_condition_and_singleton_pattern
wjchay posts on Mar 22, 2007 at 07:43
best way i know of implementing a singleton: http://snippets.dzone.com/posts/show/3519

although, be careful of using singletons in clustered environments. try something cluster-aware caching mechanisms, like OSCache, instead.

You need to create an account or log in to post comments to this site.


Click here to browse all 5140 code snippets

Related Posts