You're here: Snippet Directory » Java (241)
Language:

Singleton

Language: English
Programming Language: Java
Published by: jacobbay [not registered]
Last Update: 5/15/2006
Views: 278


Description

A superclass for implementing the Singleton pattern, without the risk of being garbage collected.

Code

1 /** Easy implementation of new singleton classes. 2 * 3 * To create a new singleton class, simply extend <CODE>Singleton</CODE> and add: 4 * 5 * <PRE> 6 * private static &lt;singleton&gt; instance = null; 7 * private &lt;singleton&gt;() { 8 * super(); 9 * &lt;more code ..&gt; 10 * } 11 * public synchronized static &lt;singleton&gt; getInstance() { 12 * if (instance == null) instance = new &lt;singleton&gt;(); 13 * return instance; 14 * } 15 * </PRE> 16 * @author Jacob Bay Hansen 17 * @version 1.1 18 */ 19 public class Singleton extends java.lang.Object implements Runnable { 20 21 private static final Object lock = new Object(); 22 23 public Singleton() { 24 new Thread(this).start(); 25 } 26 27 public void run() { 28 synchronized (lock) { 29 try { 30 lock.wait(); 31 } catch (InterruptedException e) {} 32 } 33 } 34 35 } 36 37

No comments avaiable

Add a comment

Name *  

Email (won't be displayed) *    

Website  

Comment *  

Sicherheitscode Security Code *    

RSS