Pattern Reminder: Singleton

| | Comments (0) | TrackBacks (0)

Definition: The pattern is used to ensure that only one instance of an class is used. It offers a global point of access to this object. Before Java5 consider double checked locking to be thread-safe.

Example: Lets think of using only one connection to whatever throughout the program.

singleton.jpg

Connection:

public class Connection {
//volatile !!!!
private static volatile Connection connection;
//private Constructor
private Connection(){}
public static Connection getInstance(){
if (connection == null)//check first
{
synchronized(Connection.class) //one access per thread. sync only once
{
if (connection == null) //check again
return new Connection();
}
}
return connection;
}
}

Categories

,

0 TrackBacks

Listed below are links to blogs that reference this entry: Pattern Reminder: Singleton.

TrackBack URL for this entry: http://www.innoq.com/mt4/mt-tb.cgi/2466

Leave a comment

About this Entry

This page contains a single entry by Christian Albrecht published on November 15, 2006 12:16 PM.

Pattern Reminder: Command was the previous entry in this blog.

Google Space ? is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.

Powered by Movable Type 4.0