What is Singletone class?

I would desire to apprehend the brief description about usage of Singletone class and where it can be applied.plz help me

example
public class Singleton {
private static Singleton INSTANCE = null;
// Private constructor suppresses
// default public constructor
private Singleton() {}
//synchronized creator to defend against
multi-threading issues
//another if check here to avoid multiple
instantiation
private synchronized static void createInstance()
if (INSTANCE == null) {
INSTANCE = new Singleton();
public static Singleton getInstance() {
if (INSTANCE == null) createInstance();
return INSTANCE;
Thanks
Siju Kurian
Starmark service ltdDon't use this example in real applications, it has a serious flaw. Read http://java.sun.com/developer/technicalArticles/Programming/singletons/ .This example is implementation of Double-checked locking, which lacks proper synchronization.
In almost all cases, solution provided by georgemc is applicable - it is simple and provides lazy initialization unless class have other non-private static methods/fields or non-private constructors (which may trigger initialization of class when used) (JLS, 12.4.1).

Similar Messages

  • Singleton Classes in Java

    What are SingleTon Classes in Java and what are their applications?

    Singleton is a class in Java that can be instantiated only once after it's coded ... Applications can be many ...
    Say you are coding for a game of Poker, and the deck of cards is to be instantiated only once in the whole application ..

  • What does a Singleton class do?

    Hello All,
    I would like to know what functioanlity can be achieved using Singleton classes?It was an interview question.
    can Anyone help me explaining from the basic about a Singleton class?
    Thanks in advance,
    Vijay

    A singleton class only has one instance. I've used it once for databas connection pooling. Permitting only one instance of a class may sometimes be desirable, there isn't any magic about it.
    This is a singleton class:
    public class MySingleton
        private static MySingleton instance;
        private MySingleton() {}
        public static getInstance()
            if (instance == null) instance = new MySingleton();
            return instance;
    }

  • Can not access the Instance Data of a Singleton class from MBean

    I am working against the deadline and i am sweating now. From past few days i have been working on a problem and now its the time to shout out.
    I have an application (let's call it "APP") and i have a "PerformanceStatistics" MBean written for APP. I also have a Singleton Data class (let's call it "SDATA") which provides some data for the MBean to access and calculate some application runtime stuff. Thus during the application startup and then in the application lifecysle, i will be adding data to the SDATA instance.So, this SDATA instance always has the data.
    Now, the problem is that i am not able to access any of the data or data structures from the PerformanceStatistics MBean. if i check the data structures when i am adding the data, all the structures contains data. But when i call this singleton instance from the MBean, am kind of having the empty data.
    Can anyone explain or have hints on what's happening ? Any help will be appreciated.
    I tried all sorts of DATA class being final and all methods being synchronized, static, ect.,, just to make sure. But no luck till now.
    Another unfortunate thing is that, i some times get different "ServicePerformanceData " instances (i.e. when i print the ServicePerformanceData.getInstance() they are different at different times). Not sure whats happening. I am running this application in WebLogic server and using the JConsole.
    Please see the detailed problem at @ http://stackoverflow.com/questions/1151117/can-not-access-the-instance-data-of-a-singleton-class-from-mbean
    I see related problems but no real solutions. Appreciate if anyone can throw in ideas.
    http://www.velocityreviews.com/forums/t135852-rmi-singletons-and-multiple-classloaders-in-weblogic.html
    http://www.theserverside.com/discussions/thread.tss?thread_id=12194
    http://www.jguru.com/faq/view.jsp?EID=1051835
    Thanks,
    Krishna

    I am working against the deadline and i am sweating now. From past few days i have been working on a problem and now its the time to shout out.
    I have an application (let's call it "APP") and i have a "PerformanceStatistics" MBean written for APP. I also have a Singleton Data class (let's call it "SDATA") which provides some data for the MBean to access and calculate some application runtime stuff. Thus during the application startup and then in the application lifecysle, i will be adding data to the SDATA instance.So, this SDATA instance always has the data.
    Now, the problem is that i am not able to access any of the data or data structures from the PerformanceStatistics MBean. if i check the data structures when i am adding the data, all the structures contains data. But when i call this singleton instance from the MBean, am kind of having the empty data.
    Can anyone explain or have hints on what's happening ? Any help will be appreciated.
    I tried all sorts of DATA class being final and all methods being synchronized, static, ect.,, just to make sure. But no luck till now.
    Another unfortunate thing is that, i some times get different "ServicePerformanceData " instances (i.e. when i print the ServicePerformanceData.getInstance() they are different at different times). Not sure whats happening. I am running this application in WebLogic server and using the JConsole.
    Please see the detailed problem at @ http://stackoverflow.com/questions/1151117/can-not-access-the-instance-data-of-a-singleton-class-from-mbean
    I see related problems but no real solutions. Appreciate if anyone can throw in ideas.
    http://www.velocityreviews.com/forums/t135852-rmi-singletons-and-multiple-classloaders-in-weblogic.html
    http://www.theserverside.com/discussions/thread.tss?thread_id=12194
    http://www.jguru.com/faq/view.jsp?EID=1051835
    Thanks,
    Krishna

  • To ragnic and other about Singleton class

    Hi ragnic. Thanks for your reply. I posted the code wrong. Heres' my correct one.
    I have a GUI first loaded information and the information is stored in a databse, I have some EJB classes..and my singleton class ABC has some method to access to the EJB..
    so my first GUI will gather info using singleton class and later if I click on
    a button in my first GUI class, will pop up another frame of another class , this class also need to class setPassword in my Singleton..
    are my followign codes correctly??
    iS my Class ABC a SINgleton class? thanks
    Is my class ABC use as single correctly. And It is called from other classes is also correct?
    I'm new to java and like to learn about Singleton class.
    But I really dont' understand it clearly after reading many examples of it.
    I have a project to convert my class abc to a singleton.
    But I dont know how to do it.
    In my class(soon will become a singleton) will have few methods that later I need to use it from another class A and class B.
    I have a GUI application that first load my class A..and my class will call
    class abc(singleton) to get some information from it.
    and then in class A has a button, if I click on that button I will call SIngleton class again to update my password, in the singleton class has method calls updatePassword. But I dont know how to call a singleton from other class.
    I have my code for them below:
    1)public class ABC //attempt using a singleton
    private static ABC theABC = null;
    private ABC(){}
    public synchronized static ABC getABC()
    if(theABC == null)
    theABC= new ABC();
    return the ABC;
    public void updateUserInfo(SimpleUser user)
    throws UserNotFoundException, DelegateException
    try
    UserCollectionHome userCollectionHome = (UserCollectionHome)
    EJBHomeFactory.getFactory().lookupHome("vista/UserCollection",
    UserCollectionHome.class);
    UserHome userHome = (UserHome)
    EJBHomeFactory.getFactory().lookupHome("vista/User",UserHome.class);
    UserCollection uc = userCollectionHome.create();
    uc.updateUserInfo(user, userHome);
    } catch(HomeFactoryException hfe) {
    hfe.printStackTrace();
    throw new DelegateException(hfe);
    } catch(RemoteException re) {
    re.printStackTrace();
    throw new DelegateException(re);
    } catch(CreateException ce) {
    ce.printStackTrace();
    throw new DelegateException(ce);
    } catch(FinderException fe) {
    fe.printStackTrace();
    throw new UserNotFoundException();
    public SimpleUser getID(String id)
    throws UserNotFoundException, DelegateException
    try
    UserCollectionHome userCollectionHome = (UserCollectionHome)
    EJBHomeFactory.getFactory().lookupHome("vista/UserCollection",
    UserCollectionHome.class);
    UserHome userHome = (UserHome)
    EJBHomeFactory.getFactory().lookupHome("vista/User",UserHome.class);
    UserCollection uc = userCollectionHome.create();
    SimpleUser su = uc.getID(id, userHome);
    return su;
    } catch(HomeFactoryException hfe) {
    throw new DelegateException(hfe);
    } catch(RemoteException re) {
    throw new DelegateException(re);
    } catch(CreateException ce) {
    throw new DelegateException(ce);
    } catch(FinderException fe) {
    throw new UserNotFoundException();
    public void setPassword(String lname,String pw)
    throws UserNotFoundException, DelegateException
    try
    UserCollectionHome userCollectionHome = (UserCollectionHome)
    EJBHomeFactory.getFactory().lookupHome("vista/UserCollection",
    UserCollectionHome.class);
    UserHome userHome = (UserHome)
    EJBHomeFactory.getFactory().lookupHome("vista/User",UserHome.class);
    UserCollection uc = userCollectionHome.create();
    uc.setPassword(lname,pw, userHome);//assume that all lname are differents.
    } catch(HomeFactoryException hfe) {
    hfe.printStackTrace();
    throw new DelegateException(hfe);
    } catch(RemoteException re) {
    re.printStackTrace();
    throw new DelegateException(re);
    } catch(CreateException ce) {
    ce.printStackTrace();
    throw new DelegateException(ce);
    } catch(FinderException fe) {
    fe.printStackTrace();
    throw new UserNotFoundException();
    }//Do I have my class as a Singleton correctly???
    2)//Here is my First Frame that will call a Singleton to gather user information
    public A(Frame owner)
    super(owner, "User Personal Information",true);
    initScreen();
    loadPersonalInfo();
    * This method instantiates all the GUI widgets and places them into panels and
    * onto the frame.
    private void initScreen()
    txtFname = new JTextField(20);
    txtLname=new JTextField(20);
    btnsave =new JButton("Save");
    btnChange= new JButton("Click here to change PW");//when you click this button there will be a frame pop up for you to enter informaton..this iwll call class B
    JPanel pnlMain=new JPanel();
    JPanel pnlFname= new JPanel();
    pnlFname.setLayout(new BoxLayout(pnlFname, BoxLayout.X_AXIS));
    pnlFname.setBorder(BorderFactory.createEmptyBorder(0,87,0,90));
    pnlFname.add(new JLabel("First Name:"));
    pnlFname.add(Box.createRigidArea(new Dimension(5,0)));
    pnlFname.add(txtFname);
    JPanel pnlLname= new JPanel();
    pnlLname.setLayout(new BoxLayout(pnlLname, BoxLayout.X_AXIS));
    pnlLname.setBorder(BorderFactory.createEmptyBorder(0,87,0,90));
    pnlLname.add(new JLabel("Last Name:"));
    pnlLname.add(Box.createRigidArea(new Dimension(5,0)));
    pnlLname.add(txtLname);
    pnlMain.add(pnlFname);
    pnlMain.add(pnlLname);
    pnlMain.add(btnsave);
    pnlMain.add(btnChange");
    btnSave = new JButton("Save");
    btnSave.setActionCommand("SAVE");
    btnSave.addActionListener(this);
    btnCancel = new JButton("Cancel");
    btnCancel.setActionCommand("CANCEL");
    btnCancel.addActionListener(this);
    JPanel pnlBottom = new JPanel();
    pnlBottom.setLayout(new BoxLayout(pnlBottom, BoxLayout.X_AXIS));
    pnlBottom.setBorder(BorderFactory.createEmptyBorder(25,55,0,0));
    pnlBottom.add(btnSave);
    pnlBottom.add(Box.createRigidArea(new Dimension(25,0)));
    pnlBottom.add(btnCancel);
    pnlMain.add(pnlBottom);
    this.setContentPane( pnlMain);
    setSize(500,500);
    GraphicUtilities.center(this);
    theABC=ABC.getABC();
    //Do I call my ABC singleton class correctly??
    private void loadPersonalInfo()
    String ID= System.getProperty("user.name");
    SimpleUser user = null;
    try {
    user = ABC.getID(ID);
    //I tried to use method in ABC singleton class. IS this correctly call?
    } catch(UserNotFoundException nfe)
    JOptionPane.showMessageDialog(new JDialog(),"You have not yet registered.",
    "User Not Found",JOptionPane.WARNING_MESSAGE);
    System.exit(0);
    } catch(DelegateException de) {
    JOptionPane.showMessageDialog(new JDialog(),"You have not yet registered",JOptionPane.ERROR_MESSAGE);
    System.exit(0);
    currentUser = user;
    txtFname.setText(currentUser.getFirstName());
    txtLname.setText(currentUser.getLastName());
    //This information will be display in my textfields Fname and Lname
    //I can change my first and last name and hit button SAVE to save
    public void actionPerformed(ActionEvent e)
    if(e.getActionCommand().equals("SAVE")) submitChanges();
    if(e.getActionCommand().equals("CHANGE_PASSWORD")) {
    changepassword=new ChangePassword(new Frame(),name,badgeid);
    public void submitChanges(){
    String currentNTUsername = System.getProperty("user.name");
    SimpleUser user =null;
    try {
    user = theABC.getID(ID);
    user.setFirstName(txtFname.getText().trim());
    user.setLastName(txtLname.getText().trim());
    currentUser = user;
    theABC.updateUserInfo(currentUser);
    //IS this correctly if I want to use this method in singleton class ABC??
    } catch(UserNotFoundException nfe)
    JOptionPane.showMessageDialog(new JDialog(),"You have not yet registered",
    "User Not Found",JOptionPane.WARNING_MESSAGE);
    } catch(DelegateException de) {
    JOptionPane.showMessageDialog(new JDialog(),"You have not yet registered",JOptionPane.ERROR_MESSAGE);
    System.exit(0);
    this.setVisible(false);
    3) click on ChangePassword in my above GUI class A..will call this class B..and in this class B
    I need to access method in a Singleton class- ABC class,,DO i need to inititates it agian, if not what should I do? thanks
    package com.lockheed.vista.userinfo;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    import javax.swing.table.*;
    import javax.swing.tree.*;
    import java.util.StringTokenizer;
    import java.util.Vector;
    import java.io.*;
    import javax.swing.text.*;
    import javax.swing.text.html.*;
    import javax.swing.colorchooser.*;
    import javax.swing.filechooser.*;
    import javax.accessibility.*;
    import java.beans.*;
    import java.applet.*;
    import java.net.*;
    import org.apache.log4j.*;
    import com.lockheed.common.gui.GraphicUtilities;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import vista.user.UserServicesDelegate;
    import vista.user.SimpleUser;
    import vista.user.UserNotFoundException;
    import vista.user.*;
    import com.lockheed.common.ejb.*;
    import com.lockheed.common.gui.*;
    import com.lockheed.vista.publish.*;
    * This program allow users to change their Vista Web Center's password
    public class ChangePassword extends JDialog
    implements ActionListener{
    protected final Logger log = Logger.getLogger(getClass().getName());
    private UserServicesDelegate userServicesDelegate;
    private User currentUser = null;
    private JPasswordField txtPasswd, txtVerifyPW;
    private JButton btnSubmit,btnCancel;
    private JLabel lblName,lblBadgeID;
    private String strBadgeID="";
    * This is the constructor. It creates an instance of the ChangePassword
    * and calls the method to create and build the GUI.
    public ChangePassword(Frame owner,String name,String badgeid)
    super(owner, "Change Password",true);
    initScreen(name,badgeid);//build the GUI
    * This method instantiates all the GUI widgets and places them into panels and
    * onto the frame.
    private void initScreen(String strname,String strBadgeid)
    txtPasswd = new JPasswordField(20);
    txtVerifyPW=new JPasswordField(20);
    txtPasswd.setEchoChar('*');
    txtVerifyPW.setEchoChar('*');
    JPanel pnlMain=new JPanel();
    pnlMain.setLayout(new BoxLayout(pnlMain, BoxLayout.Y_AXIS));
    pnlMain.setBorder(BorderFactory.createEmptyBorder(20,0,20,0));
    JPanel pnlPW=new JPanel();
    pnlPW.setLayout(new BoxLayout(pnlPW, BoxLayout.X_AXIS));
    pnlPW.setBorder(BorderFactory.createEmptyBorder(0,96,0,30));
    pnlPW.add(new JLabel("Password:"));
    pnlPW.add(Box.createRigidArea(new Dimension(5,0)));
    pnlPW.add(txtPasswd);
    JPanel pnlVerifyPW=new JPanel();
    pnlVerifyPW.setLayout(new BoxLayout(pnlVerifyPW, BoxLayout.X_AXIS));
    pnlVerifyPW.setBorder(BorderFactory.createEmptyBorder(0,63,0,30));
    pnlVerifyPW.add(new JLabel("Verify Password:"));
    pnlVerifyPW.add(Box.createRigidArea(new Dimension(5,0)));
    pnlVerifyPW.add(txtVerifyPW);
    JPanel pnlTop= new JPanel();
    pnlTop.add(pnlPW);
    pnlTop.add(Box.createRigidArea(new Dimension(0,10)));
    pnlTop.add(pnlVerifyPW);
    pnlMain.add(pnlTop);
    btnSubmit = new JButton("Submit");
    btnSubmit.setActionCommand("SUBMIT");
    btnSubmit.addActionListener(this);
    btnCancel = new JButton("Cancel");
    btnCancel.setActionCommand("CANCEL");
    btnCancel.addActionListener(this);
    JPanel pnlBottom = new JPanel();
    pnlBottom.setLayout(new BoxLayout(pnlBottom, BoxLayout.X_AXIS));
    pnlBottom.setBorder(BorderFactory.createEmptyBorder(25,55,20,30));
    pnlBottom.add(btnSubmit);
    pnlBottom.add(Box.createRigidArea(new Dimension(25,0)));
    pnlBottom.add(btnCancel);
    pnlMain.add(pnlBottom);
    this.setContentPane( pnlMain);
    setSize(350,230);
    setVisible(true);
    public void actionPerformed(ActionEvent e)
    if(e.getActionCommand().equals("CANCEL")) this.setVisible(false);
    if(e.getActionCommand().equals("SUBMIT")) submitPW();
    * This method is called when the submit button is clicked. It allows user to change
    * their password.
    public void submitPW(){
    myABC= ABC.getABC();//Is this correct?
    char[] pw =txtPasswd.getPassword();
    String strPasswd="";
    for(int i=0;i<pw.length;i++){
    strPasswd=strPasswd+pw;
    char[] vpw =txtVerifyPW.getPassword();
    String strVerifyPW="";
    for(int i=0;i<vpw.length;i++){
    strVerifyPW=strVerifyPW+pw;
    if((strPasswd==null)||(strPasswd.length()==0)) {
    JOptionPane.showMessageDialog(new JDialog(),"You have not enter a password. Please try again.",
    "Invalid Password",JOptionPane.ERROR_MESSAGE);
    if((!strPasswd.equals(strVerifyPW)))
    //password and verify password do not match.
    JOptionPane.showMessageDialog(new JDialog(),"Your passwords do not match. Reenter and try again.",
    "Invalid Password",JOptionPane.ERROR_MESSAGE);
    try
    myABC.setUserPassword(strPasswd);//try to use a method in Singleton class
    txtPasswd.setText("");
    txtVerifyPW.setText("");
    this.setVisible(false);
    } catch(DelegateException e) {
    JOptionPane.showMessageDialog(new Frame(),
    "Error.",
    "Unable to change password information.",JOptionPane.WARNING_MESSAGE);
    } catch(UserNotFoundException e) {
    JOptionPane.showMessageDialog(new Frame(),
    "Error.",
    "Unable to change password information.",JOptionPane.WARNING_MESSAGE);
    And ofcourse I have other EJB classes to work with these classes.
    ***It compiles okey but when I ran, it say "NullPointerException"
    I think I call my Singleton wrong.
    Please help me.thanks

    1. When replying, use <reply>, don't post a new topic.
    2. Implementing a singleton is a frequently asked question. Search before you post.
    3. This is not a question about Swing. A more appropriate forum would be "New To Java Technology" or perhaps "Java Programming", but see point 1.
    4. When posting code, keep it short. It increases the chance of readers looking at it. And in composing your shorter version for the forum, you just may solve your problem.

  • Singleton class with static method

    Hi,
    I have made a fairly simple singletion class STClass. EX:
    Consider tow cases
    CASE-1:
    private static STClass singleInstance;
    private static int i;
    private STClass()
    public static STClass instance()
         if (singleInstance == null)
              singleInstance = new STClass();
              loadConfigFile("XYZ");
         return singleInstance;
    private static void loadConfigFile(String fileName)
         //SOME CODE in which use private variable "i"
    CASE-2:
    private static STClass singleInstance;
    private int i;
    private STClass()
         loadConfigFile("XYZ");
    public static STClass instance()
         if (singleInstance == null)
              singleInstance = new STClass();
         return singleInstance;
    private void loadConfigFile(String fileName)
         //SOME CODE in which use private variable "i"
    What is the differnce between two case and which one will be best and why???
    Someone told me "If u keep variables and methods as static the the whole purpose of singleton class is defeated"
    please justify this statement

    It seems to me that this way should be more "correct":
    public class STClass {
    private static STClass singleInstance;
    private int i;
    private STClass() {
    public static STClass getInstance() {
    if (singleInstance == null) {
    singleInstance = new STClass();
    singleInstance.loadConfigFile("XYZ");
    return singleInstance;
    private void loadConfigFile(String fileName) {
    //SOME CODE in which use private variable "i"
    }And it is also compatible with your CASE-2.
    Hope this helped,
    Regards.I wouldnot agree with this piece of code here because of JMM bug. check this
    http://www.javaworld.com/jw-02-2001/jw-0209-double-p2.html
    What about proposing your own version, explained ?...

  • (retain) properties in the singleton class

    Hi,
    What happens with the properties declared with (retain) in the singleton class:
    MyClass *foo;
    @property (nonatomic, retain) MyClass *foo;
    I am using a singleton class as explained http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/CocoaFunda mentals/CocoaObjects/CocoaObjects.html#//apple_ref/doc/uid/TP40002974-CH4-SW32 which should NOT be released.
    I see no way to call
    [foo release].
    My guess is that these properties will be allocated once and persist though entire life of the singelton - which is not a leak.
    correct?

    leonbrag wrote:
    My guess is that these properties will be allocated once and persist though entire life of the singelton - which is not a leak.
    correct?
    Yes. Of course, there are still ways to get rid of singletons if you really want/had to. In some cases, you could have a singleton that allocated system resources that aren't automatically released when a program ends. There are ways to clean up such things if you run across them. Look at the "applicationWillTerminate:" notification, for example.

  • How to make Singleton Class secure

    I have a Singleton class which I instantiate using reflection by a call to a public getInstance method that return the object from a private constructor. I have to use reflection as I dont have any other options since my class instantiation is decided on runtime. How will I secure other form instantiating the same class again by using reflection on my private constructor? Any ideas?

    How much do these different implementations of your singleton have in common? What I'm getting at is, is there some common code you could extract out of them all, and make that a singleton in it's own right? Needing to do this sort of hacking is often a sign you're fudging something together, that could be solved more elegantly. We use the Singleton pattern generally when the state of the object needs to exist exactly once. Can you extract that from the disparate objects?
    The singleton classes that I load do not have anything in common. They are all similar but unique, and independant in their own respect. I will have to decide only on what singleton object I have to load in runtime, based on certain criterion. This is done by reflection, by a call to the public getInstance() method of the respective singleton classes, since I am deciding on runtime. My problem is that can I prevent others from accessing my private constructor from outside the class using reflection, which enables them to create another duplicate object. Can I restrict them to use only my getInstance() method instead?? I know this is hacking to access the private members, but I want to know whether there is any way where I can restrict this hacking???In the above code I dont want these statements to work at any case
    java.lang.reflect.Constructor[] c = cl.getDeclaredConstructors();
    c[0].setAccessible(true);
    A anotherA  = (A) c[0].newInstance(new Object[]{"Duplicate"});

  • TestStand create different object for singleton class

    Hi all,
    we have a singleton class which has some functions used to do testing a harware.
    Our main Exe will create an object for that singleton class(which opens Com1 port and communicate with hardware). so the Exe will do basic communication test with hardware it is working well. We are using Teststand operator interface to do various testing by using sequence files. Main exe will use teststand usercontrols to execute tests when the user clicks Testbutton. after that, teststand try to create an object for that singleton but it returns new object not the existing one which is created by EXE. So it throwing me exeception "Com1 port access denied." (since we created object for signleton class @ very first in EXE)
    My question is Since that teststand runs in a separate Appdoamin will the singltonclass create separate object for different appdomain? if so is there any solution to reslove this?
    Hope i clearly explained my probs.
    Thanks in advance
    Srini 

    Hi Srini,
    How are you calling the executable?  From a Call Executable step?  Or are you using another means of calling it?   Also, why is TestStand trying to recreate the object?  As long as you have the correct handle to the object I don't think it matters what app domain you are in.
    Regards,
    jigg
    CTA, CLA
    teststandhelp.com
    ~Will work for kudos and/or BBQ~

  • How to implement a singleton class across apps in a managed server}

    Hi ,
    I tried implementing a singleton class , and then invoking the same in a filter class.
    Both are then deployed as a web app (war file) in a managed server.
    I created a similar app , deployed the same as another app in the same managed server .
    I have a logger running which logs the singleton instances as well.
    But am getting two instances of the singleton class in the two apps - not the same .
    I was under the impression that , a singleton is loaded in the class loader level , and since all apps under the same managed server used the same JVM , singleton will only get initialized once.
    Am i missing something here ? or did i implement it wrong..?
    public class Test
       private static Test ref ;
       private DataSource X; 
       static int Y;
       long Z ;  
       private Test ()
          // Singleton
           Z= 100 ;
       public static synchronized Test getinstance()  throws NamingException, SQLException
          if(ref == null)
             ref = new Test() ;        
             InitialContext ic = new InitialContext();
             ref.X = (DataSource)ic.lookup ("jdbc/Views");
          return ref ;       
       public Object clone()throws CloneNotSupportedException
           throw new CloneNotSupportedException();
       public int sampleMethod (int X) throws SQLException
    public final class Filter implements Filter
         public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException
              try
                   Test ref = Test.getinstance();
                   log.logNow(ref.toString());
    }Edited by: Tom on Dec 8, 2010 2:45 PM
    Edited by: Tom on Dec 8, 2010 2:46 PM

    Tom wrote:
    Hi ,
    I tried implementing a singleton class , and then invoking the same in a filter class.
    Both are then deployed as a web app (war file) in a managed server.
    I created a similar app , deployed the same as another app in the same managed server .
    I have a logger running which logs the singleton instances as well.
    But am getting two instances of the singleton class in the two apps - not the same .Two apps = two instances.
    Basically by definition.
    >
    I was under the impression that , a singleton is loaded in the class loader level , and since all apps under the same managed server used the same JVM , singleton will only get initialized once. A class is loaded by a class loader.
    Any class loader that loads a class, by definition loads the class.
    A VM can have many class loaders. And far as I know every JEE server in existance that anyone uses, uses class loaders.
    And finally there might be a problem with the architecture/design of a JEE system which has two applications but which is trying to solve it with a singleton. That suggests a there might be concept problem with understanding what an "app" is in the first place.

  • How to ensure singleton classes no longer exist

    hi all not sure if this is the right forum....
    I am writting an application that integrates another, I wish to stop and then restart the integrated application but it seems that the singleton classes of which there are quite a few ( each being statically initalised) do not disappear when I try to shut them dowm. (if I am shutting them down that is ...)
    is there a way to ensure these instances are terminated so I can restart the integrated application inside my application?
    is there a way to see what instances exist so I can see if in fact I am disposing of any?
    thanks for ur help

    is there a way to ensure these instances are
    terminated so I can restart the integrated application
    inside my application?
    is there a way to see what instances exist so I can
    see if in fact I am disposing of any?
    What exactly are you trying to achieve?
    Do these hold on to resources which you must clean first? Then you must have a clean/dispose method. There is no other option. You can use a registration class to make this easier.
    Do you simply want to reinitialize them? Then you could use a class loader but it probably going to take less time to simply do the same as above and add a reinit method to each. Again you can use a registration class to make this easier.

  • Any adverse effects from singleton classes?

    We're trying to decide whether it is a good/bad/indifferent idea to use
    singleton classes in various places in an application (servlets, session
    EJBs, BMP entity EJBs), in a clustered environment. Our app designers
    have a number of different potential uses in mind, such as storing some
    rarely changed data, and localised caches. We're happy with the
    restriction that they obviously wouldn't be replicated. However, we're
    not sure about what other implications there might be, especially when
    the thing is scaled up. Questions that spring to mind include:
    - any inbuilt synchronisation that WL may do (if the singleton had to
    dive off to a database to get some further info we wouldn't necessarily
    want to have other callers to it synchronise at that point)
    - the effect on the JVM if we tie up some of its virtual memory
    - any other considerations
    Note that they are considering using this technique in both the web app
    and the ejbs (which will reside in different clusters).
    Are there any guidelines available for the use of singletons,
    particularly from a performance point of view?
    Thanks
    Chris

    For caching in clustering, read only entity beans are best bet.
    You must not bind a cach ( HashMap or soemthing) object in JNDI tree in
    clustering. This could lead to mess as this binding is not cluster aware. You
    might see conflict messages in your log file or your local bidning could fail
    in one or other server depending upon timing.
    Other than that as long as you don't have synchronization in singleton classes
    that leads to deadlocks, there should not be a problem.
    Viresh Garg
    Principal Developer Relations Emgineer
    BEA Systems
    Larry Presswood wrote:
    Well duno if this helps but their new Jolt Pool Manager is a singleton
    class.
    Also you could use JNDI as a data cache but be careful as it replicates
    across
    the cluster.
    Chris Palmer wrote:
    We're trying to decide whether it is a good/bad/indifferent idea to use
    singleton classes in various places in an application (servlets, session
    EJBs, BMP entity EJBs), in a clustered environment. Our app designers
    have a number of different potential uses in mind, such as storing some
    rarely changed data, and localised caches. We're happy with the
    restriction that they obviously wouldn't be replicated. However, we're
    not sure about what other implications there might be, especially when
    the thing is scaled up. Questions that spring to mind include:
    - any inbuilt synchronisation that WL may do (if the singleton had to
    dive off to a database to get some further info we wouldn't necessarily
    want to have other callers to it synchronise at that point)
    - the effect on the JVM if we tie up some of its virtual memory
    - any other considerations
    Note that they are considering using this technique in both the web app
    and the ejbs (which will reside in different clusters).
    Are there any guidelines available for the use of singletons,
    particularly from a performance point of view?
    Thanks
    Chris

  • Synchronized Instance Methods in Singleton Class

    If I've a TransactionManager class that's a singleton; meaning one manager handling clients' transaction requests, do I need to synchronize all of the instance methods within that singleton class?
    My understanding is that I should; otherwise, there's a chance of data corruption when one thread tries to update, but another thread tries to delete the same record at the same time.

    Let's say that you have a singleton that is handling
    the printing in a desktop application. This could be
    time consuming and it will not probably be used too
    often. What's time consuming about instantiating the object?
    On the other hand you could not say that it
    will never be used.Exactly. If that were so, why write it?
    In a web application, response time is much more
    important than initialization time (which can be
    easily ignored). Never ignored. It's just a question of when you want to pay.
    Web app as opposed to desktop app? Does response time not matter for them?
    In this case, of course, eager
    initialization makes much more sense.I'm arguing that eager initialization always makes more sense. Lazy for singletons ought to be the exception, not the norm.
    %

  • Place of Singleton class in OO Design

    Hi
    Can any body make me clear on, why we make use of Singleton Class and how it is related to Object Oriented world.
    Thanks,
    Prasanth

    Personally, I�ve never seen a case where singletons
    are being badly used. In this forum, I�ve always been
    reading a lot of people saying that Singleton is
    anti-pattern, Singleton is evil, Singleton is
    abusively implemented, etc, etc. It�s very easy to
    say those things, perhaps because of some authorities
    who endorse what you say, but nobody has said WHY
    EXACTLY Singletons are bad.I thought I did say exactly that in this thread.
    Let me try again.
    Some people believe that simply by using Singletons that their designs follow OO principals. In effect it is quite possible to create an entire application or most of an application using procedural programming by using singletons.
    In terms of OO it is considered a bad design when the design is procedural.
    >
    If it is anti-pattern, then it would be better if it
    were not used. But if it is in fact used and it is
    considered good sometimes, then we can conclude that
    it is not an anti-pattern. This is just logic.
    Incorrect. Everything can be both abused and used correctly.
    However at some point the incorrect usage and the complications from that outweigh the benefits of the correct usage. That might be a subjective or objective determination.
    Examples of this.
    1. In two shops where I worked that used unix and C++ exclusively the use of operator overloading and multiple inheritence was completely banned. The majority of developers (I never found one that disagreed) believed that the usage of those two would be detrimental to the code that was being created.
    2. The creators of java decided that pointers should not be allowed.
    Now it could be that that all of those people are wrong. Or it could be that many of them were going on ancedotal evidence learned either first hand, second hand (or many hands) and yet that evidence was wrong.
    Myself I suspect it would be very expensive to determine objectively many thing that technological decisions are made upon. So one is left with whatever one can find.
    I�ve already googleg for some information, but what I
    found are just lots of sites that repeat what a lot
    of people here say, more or less.
    I think people have to have a good explanation for
    what they say.Not necessarily. Most larger technological decisions are often made with only subjective knowledge. Many people insist that unix is more stable than windows. Or that java/C++/C# (pick one) is better than java/C++/C3 (pick another) with seldom any more reason than just because they like one or the other.
    Finally you might note that I haven't seen the abuse that is being reported here. I do however recognize the possibility that it could be occurring.

  • Use Of SUPPLY Function & Singletone Class?

    Hi,
    What is the Use of Supply Function & What is Sigletone Class?
    Thanks
    Ranveer

    Hi Ranveer,
    Each context node of a controller can be assigned a supply function. This supply
    function is called by the runtime when the data of the context node is used. This is the case
    when a UI element is to be displayed for the first time with the data of the corresponding
    context.
    In general, the supply function is called when one or more elements of a context node are
    accessed and when
    &#9679; the context node is not filled yet or is initial, or
    &#9679; the context node has been invalidated in a previous step.
    Supply Functions of Singleton Nodes
    The supply function is especially useful in combination with singleton nodes.The
    values of subnode elements of the type Singleton depend on the element of the parent node
    to which the lead selection is currently assigned. If the lead selection is changed by the user,
    the supply function can access the new lead selection element and recalculate the values of
    the subnode elements accordingly.
    You can only create such a view when the lead selection element of the node
    CARRIER_NODE is read in the supply function of the node CONNECTION_NODE:
    For eg:
    method GET_CONNECTIONS .
    data: CARR_ATTR type IF_MAINVIEW=>ELEMENT_CARRIER_NODE,
    FLIGHTS type SPFLI_TAB.
    get filled structure for parent node
    PARENT_ELEMENT->GET_STATIC_ATTRIBUTES( importing
    STATIC_ATTRIBUTES = CARR_ATTR ).
    get connections from help class
    FLIGHTS = CL_WD_GET_SPFLI=>GET_FLIGHTS_BY_CARRID(
    CARRID = CARR_ATTR-CARRID ).
    NODE->BIND_ELEMENTS( FLIGHTS ).
    endmethod.
    Explanation:
    An internal variable of the type of a context element of the parent node
    CARRIER_NODE and another internal variable of the Dictionary type SPFLI_TAB are
    declared.
    &#9679; The attribute values of the lead selection element of the parent node CARRIER_NODE
    are then passed to the internal variable CARR_ATTR.
    For this transfer, each supply function uses the parameter
    PARENT_ELEMENT of the reference type IF_WD_CONTEXT_ELEMENT.
    PARENT_ELEMENT is a reference to the lead selection element of the parent node of
    the current node. The parameter is automatically displayed in the signature of the
    supply function.
    Each time the user selects another table element as the lead selection in the table Carrier,
    the value of the parameter PARENT_ELEMENT changes. The supply function of the context
    node CONNECTION_NODE is called and the values of its attributes are newly filled
    according to the selected table line in the table Carrier.
    Supply functions can only access context data that
    &#9632; is contained in the corresponding parent node or
    &#9632; is contained in another node that is on a next-highest level compared to
    the node filled by the corresponding supply function.
    Cheers,
    Mary

Maybe you are looking for