Singleton Pattern In Java

Filed in JavaTags: , , ,

Singleton pattern is probably one of most popular widely used patterns that I have seen. It’s implemented to create an access restriction to a specific resource like: printer, network, pooling, memory, logging.

Here is a simple and correct implementation:

public class Singleton implements Serializable{
	private static Singleton _INSTANCE = null;

	static{
  		_INSTANCE = new Singleton();
 	}

	private Singleton() {
  	}

	public static Singleton getInstance() {
		return _INSTANCE;
	}
 }

Lets look at one by one.

private static Singleton  _INSTANCE keeps reference of the instance
static block this will prevent multi-thread initialization
readResolve() to make sure a new instance is not created by deserialization process

Beware that double locking solution will not work:

class Singleton {
  private static  Singleton singleton = null;
  public static Singleton getSingleton() {
    if (singleton == null){
        synchronized(this) {
           if (singleton == null)
              singleton = new Singleton ();
        }
   }
    return singleton ;
    }
  }

Please read the article for further information.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

 
 
January 2012
M T W T F S S
     
 1
2345678
9101112131415
16171819202122
23242526272829
3031