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.

Similar Messages

  • Singleton Class ArrayCollection within Flashbuilder (Mobile) empty?

    Hi,
    I am currently trying to implememnt a Singleton Class in order to store a ArrayCollection of items that I can then access and manipulate across the lifecycle of my app. I have created the below Singleton Class that is designed to hold the ArrayCollection information:
    package valueObjects
        import mx.collections.ArrayCollection;   
        [Bindable]
        public class Model
            private static var instance:Model = new Model();
            public var ids:ArrayCollection = new ArrayCollection();
            public function Model()
                if(instance)
                    trace("New instance cannot be created. Use Singleton.getInstance()");
            public static function getInstance():Model
                return instance;
    I have then created the following code on the Main Deafult page for my application so that the ArrayCollection is populated as soon as the app is initiated:
                import valueObjects.Model;           
                protected var models:Model = new Model();
                            private function loop():void
                    var index:int;
                    for( index = 0; index < compsCollection.length; index++ )
                        trace( "Element " + index + " is " +  compsCollection[index].comp_id );
                                    models.ids.addItem(compsCollection[index].comp_id);
                        trace(models.ids.length);
    The ArrayCollection in the Singleton Class is being populated as the trace statement that I have entered into the loop clearly shows the build of of data in the ArrayCollection. However then when I move to another view within the application I then try to access this ArrayCollection within the Singleton Class with the following code:
    import valueObjects.Model;
    protected var models:Model = Model.getInstance();
    protected var test:ArrayCollection = new ArrayCollection();
    protected function view1_viewActivateHandler(event:ViewNavigatorEvent):void
                    var index:int;
                    trace("Array Length =" + models.ids.length);
                    for( index = 0; index < models.ids.length; index++ )
                        trace( "Element " + index + " is " + models.ids[index].comp_id );
                        test.addItem(models.ids[index].comp_id);
                    testbox.text = test.toString();
    Now the problem I am having is that when I try to access this ArrayCollection(ids) it appears to be empty for some reason. I have included a trace statement that also says that the length of the ArrayCollection is "0". Can anyone please help??

    if your value object class change this
    change this
    public var ids:ArrayCollection = new ArrayCollection();
    to
    public static var ids:ArrayCollection = new ArrayCollection();
    on your default page change this
    models.ids.addItem(compsCollection[index].comp_id);
    to
    valueObjects.Model.ids.addItem(compsCollection[index].comp_id);
    on your view change to something like this.
    protected
    function view1_viewActivateHandler():void
                   //initialize="view1_viewActivateHandler();"
                   var index:int;
                   trace("Array Length =" + valueObjects.Model.ids.length);
                   for( index = 0; index < valueObjects.Model.ids.length; index++ )
                        trace( "Element " + index + " is " + valueObjects.Model.ids[index].comp_id );
                        test.addItem(valueObjects.Model.ids[index].comp_id);
                   //testbox.text = test.toString();
    good luck let me know if you have any question i tested this and it worked like a charm for me.
    Miguel

  • 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.

  • 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.

  • 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

  • Singleton class within Container

    Let me extend my apologies now if this is to simple of a question for the forum.
    Here is my design issue. We are within a session bean (Stateless) and each session bean will need access to a Singleton class which possesses reference data (has a find method). This Singleton class must be static as we do not wish to replicate the amount of data involved.
    Here is my concern. Based on the fact the EJB container has created 10 session beans which must access this Singleton class and the methods within it, I "think" there will be a concurrency issue with this design.
    Can a EJB guru shade some light on this issue for me?
    Thanks in advance!

    If the the singleton class is used for multiple read and only one specific bean does a write, I dont think there should be a problem.
    However, if there are multiple read and write scenarios, then offcourse concurrency is an issue.
    What kind of data are using inside the single ton class. If you are using a hashtable or Vector inside, they take care of concurreny , as they are synchronized.
    Or else another way I could think of is
    Create a statefull session bean, instead of a java object for your singleton. Make the maximum and minimum cache size to 1.
    This will take care of the object to be singleton. And the bean would take care of the concurreny.
    Just my thoughts, am not an expert,

  • Singleton Class using a constructor not a getInstance method

    Hi,
    I have a class with a couple of contructors, the class is instantiated many times in the application.
    Is there any way by which I can return a single instance of the class when the contructor is called ?.
    I dont want to declare a get instance method to return a single instance is it somehow possible to do this in the contructor itself.
    This is done so I dont have to refactor the whole application and change all the places where this class is instantiated.
    Example
    XXXClass xxx = new XXXClass();
    every time new XXXClass() is called the single instance of the class must be returned.
    I dont want to implement
    XXXClass xxx = XXXClass.getInstance();
    Thanks in advance
    Rgds
    Pradeep Thomas

    The short answer to your question is No. If your class has accessible constructors and your code calls "new" then there will be multiple instances of the corresponding objects.
    Possible ways round your problem are to use static variables in place of instance variables or to use your existing class as a wrapper for another class that is instantiated only once. This second class should include all the variables and methods and the wrapper class would delegate all calls to it. This is not quite a singleton because there would still be multiple instances of the wrapper, but each instance would share the same variables and methods. You could also add a getInstance() method to the wrapper class so that new code could start to use it as a singleton.
    Other than that, it's time to refactor! Good Luck.

  • Is the singleton class single in threads?

    I have a class designed by singleton pattern.
    I use this in many threads in one VM.
    I found every thread had a different instance.
    Why?
    And if I want to share information with different
    threads,how can I apply singleton in this context?

    I know why!
    In my singleton class,I don't add the keyword "synchronized".
    Code below:
    public static MySingleton getInstance(){
    if(instance == null){                       //miss the keyword "synchronized"
    instance = new MySingleTon();
    return instance;
    So when threads call this method at the same time,
    many instances created.

  • Error in creating singleton class

    Hi all:
    I am trying to create a singleton class. The code is the following:
    // begin
    class EdgeIntersectsException extends Exception{
    final static EdgeIntersectsException instance = new
    EdgeIntersectsException();
    private EdgeIntersectsException(){}
    // end
    But eclipse gives me error like this:
    the field instance cannot be declare static; static field can only be declare in static or top level types.
    I don't know why it happens to be like this. Any advice will help. Thank you in advance!

    What benefit do you get by making it a singleton?
    My program is not suppose to use concurrency, so
    , so a singleton design is good, because I am sure
    that the instance is going to be
    used by one thread at any time, and it also saves
    memory space. Being a Singleton has no impact on how many threads can execute code unless every method is synchronized and every member is private. Furthermore, if your program is not using concurrency then this is even more irrelevent because it would only matter if you were using concurrency.
    What logic is there that says only one of these
    things should exist in your system?
    I am not exactly sure here. If I make only one
    one instance of this exception, will it be faster to
    throw it? Currently, the only good thing
    I can think of is that it saves memory. (Since this
    kind of exception may be used a lot as the program
    runs.)If you can't identify a single meaningful reason to be doing something perhaps you should rethink doing it to begin with.

  • SINGLETON CLASSES QUESTIONS

    Hello,
    Could someone please explain what the following code does? How does it work? How can I use it in the real program?
    More importantly, if you are kind enough, please give me some examples how to use singleton class? Why do we have to use this class?
    I spent two days on this topic, Singleton, but my mind still goes blank.....
    thank you.
    public class Singleton
    static public Singleton getInstance()
    if(theInstance == null)
    theInstance = new Singleton();
    return theInstance;
    protected Singleton()
    //initializing instance fields
    //instance fields and methods
    private static Singleton theInstance = null;

    Hello,
    Could someone please explain what the following code
    does? The code defines a class called Singleton. :)
    How does it work? The static method "getInstance()" returns an object of type Singleton. Static methods can be called without having an instance of a class, so you can type:
    Singleton.getInstance();
    How can I use it in the
    real program?This class is pretty useless in a real program. The point of this class is to show you how the Singleton design pattern can be implemented in Java. Any useful Singleton object needs to have additional properties and methods. (Oh I know someone will say that you can still use this class for something, but I'm trying to explain something here...)
    More importantly, if you are kind enough, please give
    me some examples how to use singleton class? Sure, here's an example of a singleton: Suppose you want a debugging class that will simply write text to a file. You want to only have one instance of this class (i.e. you don't want to have multiple log files, you want to provide one single interface point for this):
    class LoggerSingleton
      private static final String LOGFILENAME = "log.txt";
      private BufferedWriter write = null;
      private LoggerSingleton instance;
      synchronized static public LoggerSingleton getInstance()
      { if(instance == null)  instance = new LoggerSingleton(LOGFILENAME);
        return instance;
      protected LoggerSingleton(String filename)
        try {
          write = new BufferedWriter(new FileWriter(filename));
          write.write("Log File Opened");
          write.newLine();
          write.flush();
        catch(IOException ioe)
          System.err.println("Error!  LoggerSingleton could not be initialized");
          ioe.printStackTrace(System.err);
          System.exit(1);
      public log(String text)
        write.write(text);
        write.newLine();
        write.flush();
    }This class will make sure you only have one log file and ensures that all classes are using it:
    class FirstClass {
      SecondClass second = new SecondClass();
      public FirstClass() {
        LoggerSingleton.getInstance().log("Inside FirstClass' constructor");
      public void func1() {
        LoggerSingleton.getInstance().log("Inside FirstClass.func1()");
    class SecondClass {
      public SecondClass() {
        LoggerSingleton.getInstance().log("Inside SecondClass' constructor");
    Why do we have to use this class?You don't have to use this class, but it is one technique to ensure that multiple instances of an object are not instantiated. It is also a technique to ensure that there is only one interface point across the application (you can also use a Singleton object to implement the Bridge and Factory design patterns). The Singleton technique is achieved by making the constructor protected, which means that only methods inside the class (and package) can construct instances of Singleton. The only time an instance of Singleton is constructed is the first time that getInstance() is called.
    I spent two days on this topic, Singleton, but my mind
    still goes blank.....
    Still blank?

  • 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

  • Help required in understanding the rationale behind singleton class

    Can anyone help me in understanding singleton classes?why do we need them?Architecturally when should we go for a singleton class?

    answer lies in GoF book.

  • 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 ?...

  • Singleton class + JTable mouseClicked

    Hi,
    I have a problem with this topic:
    singleton class OR create new class and use one function (not a static func) of this class from else class.
    I have singleton class that return JScrollPane with table, in this table I have tasks..
    in this class I have: public void mouseClicked(MouseEvent e) function.
    when the user clicked --> I create another JTable (table with sub tasks)
    and if the user clicked in this table, I create another JTable (table with sub sub tasks).............................
    I need your help because: if the class that create a JTable singleton type, then I can not get another mouseClicked of jtable that below the new jtable (I can't get another mouseClicked of sub tasks table if I created the sub sub tasks table...).
    But, if I create everytime NEW class that return the scroll JTable --> I get different problem:
    I need to use with some functions from scroll JTable class and I don't know how to do it..I can't do: TaskTable.getInstance().getMyFunc();
    This function must to be in this class, and not static!
    I'm new :) maybe I don't know some else way to get function from regular class.
    Sorry about my english.
    I'm really need your help :)
    Thasks.

    ..if I create everytime NEW class that return the scroll JTable --> I get different problem:
    I need to use with some functions from scroll JTable class and I don't know how to do it..
    TaskTable t1 = new TaskTable();
    t1.getMyFunc();

  • (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.

Maybe you are looking for

  • Here is the scenario of deletion

    Hi i am asked to handle this scenario...... I have a table which stores the list of all phone numbers, owner of the phone in my database..... the front end application is java.... i was told that they (java guys) get the a csv file with the list of a

  • MacBook Disk Space

    Hi, I have a brand-new-just-out-of-the-box Macbook (First Mac to own) I have the 100 gig(92.84) hard drive, and without loading a bit on it it says I am already using 18.37 gigs of space. Can this be true? Does OS X really come pre-packed with 18 gig

  • Employee Rate schedule project to project

    Dear Dina, During approved cost budget preparation i am taking the named resources and the employee rate schedule serve the rate to me...For some of the projects if we need to go for the different rate schedule like mark up % (hike value)...project t

  • Itunes keeps canceling sync on my iphone 5 ios 7

    Syncing my iTunes to my iPhone 5, iOS7, keeps on canceling out before it has gotten all of the music. I've re-updated my phone, cleared music and re-synced and it just cancels at random times. Sometimes gets to 600 of my 2100 songs or sometimes gets

  • NoSuchMethodError from ReferenceableSerializerImpl call

    I have a client program that's generating this error at runtime: java.lang.NoSuchMethodError: com.sun.xml.rpc.encoding.ReferenceableSerializerImpl My client program is trying to connect to a simple webservice that echo's back a message. I used wscomp