Thread Safe Singleton

A Netbeans template for a thread safe singleton in java.

/*
 * __NAME__.java
 *
 * @author __USER__
 *
 * Created on __DATE__, __TIME__
 */
 
package Templates.Classes;
 
/** __NAME__
 * uses the singleton pattern to prevent multiple instances.
 * NOTE: provides only a single instance per classloader.
 * see Singleton Pattern [GOF:127]
 * @author __USER__
 */
public class __NAME__
  {
  /** a private static reference to this object.
  */
  private static __NAME__ instance ;
 
  /** construct a singleton instance of this on class loading.
   */
  static
    {
    try
      {
      instance = new __NAME__() ;
      }
    catch (Exception initialisationException)
      {
      throw new ExceptionInInitializerError( initialisationException ) ;
      }
    }
 
  /** Constructor
   *  Creates a new instance of __NAME__ 
   *  private ensure no wild construction.
   *  @throws java.lang.Exception
   */
  private __NAME__()
    throws java.lang.Exception
      {
      // throw new Exception( "TODO: Define suitable Exception" ) ;
      }
 
  /** getInstance()
   * static method supplies reference of the single instance of this class
   * @return __NAME__ reference.
   */
  public static __NAME__ getInstance()
    {
    return instance;
    }
 
  /** test1()
   *  a test case for this class to ensure singleton
   *  @param args as String[]
   */
  public static void test1( String[] args )
    {
    __NAME__ reference_1 = __NAME__.getInstance() ;
    __NAME__ reference_2 = __NAME__.getInstance() ;    
    if (reference_1 == reference_2)
      {
      System.err.println( __NAME__.class.getName()+".test() = PASS") ;
      }
    else
      {
      System.err.println(
          reference_1.toString()+" != "+
          reference_2.toString()+" = FAIL") ;
      }
    }
 
  /** test2()
   *  a test case for this class to ensure singleton
   *  @param args as String[]
   */
//  public static void test2( String[] args )
//    {
//    __NAME__ reference = __NAME__.getInstance() ;
//    reference.function() ;
//    }
 
  /** main()
   *  Program entry point.
   *  @param args as String[]
   */  
  public static void main( String[] args )
    {
    test1( args ) ;
    // TODO: your tests
//    test2( args ) ;
    }
  }

oo_java_singleton_example.txt ยท Last modified: 2009/09/22 14:46 (external edit)