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

Similar Messages

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

  • 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"});

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

  • Singleton Classes in Weblogic cluster

    Hi
    Our application is having singleton classes which we refresh programatically ;though very rarely. We need to move our application into a weblogic cluster. The sigleton class refresh also needs to reflect across the servers :
    I could see the SingletonService API here http://download.oracle.com/docs/cd/E12839_01/apirefs.1111/e13941/weblogic/cluster/singleton/SingletonService.html. This contain an activate() and deactivate() .Can we call this activate() method to refresh the singleton object whenever there is a refresh required ? Can we define multiple singleton service classes in the cluster ?
    Thanks
    Suneesh

    I've same issue with singleton service...
    1) I’ve created a cluster MyCluster with Man1 & Man2 managed instances.
    2) I’ve created singleton.jar out of TestCache.java, which is a singleton cache and have deployed it to the MyCluster.
    3) I’ve created man.jar out of StartupClassMan.java, which is a startup class and have deployed it to the MyCluster. And I’ve specified this as startup class for the whole MyCluster.
    4) For MyCluster, I’ve specified com.mytest.TestCache.class as singleton service with preferred server as Man1 with migratable to Man2.
    5) I run Man1, startup class StartupClassMan is invoked and it gets reference to TestCache, populates the cache & prints size as 1.
    6) Now when I run Man2, startup class StartupClassMan is invoked and it get references to TestCache & populates the cache & prints size as 1 only.
    For some reason, TestCache is not considered as true singleton. If it is true singleton, running Man2 should have printed size 2 as Man1 has already put one entry into the cache.
    And I also don't see activate & deactivate method being called when I run Man1 or Man2 servers. Any help on this is really appreciated.
    package com.mytest;
    import java.util.Map;
    import java.util.HashMap;
    public class TestCache implements weblogic.cluster.singleton.SingletonService
    private static TestCache testCache = new TestCache();
    private Map<String, String> mapCache = new HashMap<String, String>();
    private TestCache() {}
    public void activate() {
    System.out.println("TestCache activate called");
    public void deactivate() {
    System.out.println("TestCache deactivate called");
    public static TestCache getTestCache() {
    return testCache;
    public void put(String key, String value) {
    mapCache.put(key, value);
    public String get(String key) {
    return mapCache.get(key);
    public void remove(String key) {
    mapCache.remove(key);
    public int size() {
    return mapCache.size();
    package com.mytest;
    public class StartupClassMan
    public static void main(String args[]) {
    System.out.println("StartupClassMan loaded");
    TestCache testCache = TestCache.getTestCache();
    testCache.put("Man1","Man1");
    System.out.println("size: "+testCache.size());
    }

  • Singleton class instantiated several times

    Hi all,
    I am trying to implement an inter-applet communication using a singleton class for registering the applets. The applets are in different frames on my browser; they are placed in the same directory and they use the same java console, so I am pretty sure they are running on the same JVM...
    However, when I register my applets, every applet creates its "own" registry class. I have put a message in the constructor of the register class to check what's happening:
    public class AppletRegistry extends Applet 
        //static hashtable maintaining the applet map
        private static Hashtable appletMap;
        private static int ct=0;
        protected static AppletRegistry registry;
        protected AppletRegistry()
            appletMap = new Hashtable();
    //  Returns the long instance of the registry. If there isn't a registry
    //  yet, it creates one.
          public synchronized static AppletRegistry instance()
               if (registry == null) {
                         System.out.println("new register");
                    registry = new AppletRegistry();
               return registry;
        //registers the given applet
        public void register(String name, Applet applet)
            appletMap.put(name, applet);
            ct++;
            System.out.println("Register: "+name+" "+Integer.toString(ct));
    }The output "new register" appears for every applet I register... What am I doing wrong?
    Thea

    I must admit that I never heard of classloader until
    now :-( (learning java for two or three months). Do
    you know a good tutorial about using classloaders? I
    have no idea where to start checking which
    classloaders are used.
    Thanks!
    TheaHi,
    I don't think there are much you can do about it. Two different applets can't share an instance.
    /Kaj

  • 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

    Hi everybody
    Need to programm a calculation project and got the advice to use an singleton class. What the h... is that, how does it work and what is it good for. Anyone who can give me code samples and a short explanation?

    Slight correction: There are two main ways to implement singleton. In the way fluca has shown, you have to synchronize getInstance. The other way is to assign the instance at declaration time, and skip the check for null in getInstance.
    These were just illustrated quite well by jschell or DrClap or jsalonen or somebody within the last few days, probably either on this forum or on New to Java Technology. (Might have been Advanced Lang Topics, but I doubt it). Do a search on Singleton and you'll find that thread (and a lot more, I imagine).
    Hi,
    well a singleton is a class, from which is
    instantiable only one object for every JVM.
    Tipically it's obtained dclaring private (or
    protected) the constructor, and using a static method
    (and an internal staic reference) to get the
    instance.
    For example:
    public class MySing
         private MySing()
         // reference to myself
         private static myself;
         // get the instance
         public static MySing getInstance()
              if(myself==null)
                   myself=new MySing();
              return myself;
    A singleton class is useful for object that must be
    used by various threads, but that at the same time
    needs to mantaine a particular
    coerence. For example, if you deploy a database 100%
    pure Java, then it must run as singleton, because two
    threads must obtain the same reference, and can't
    create two different database.
    Hope this helps

  • Singleton class issue

    I have a singleton class. A method in this class creates an array of structures. This class is shared across different process. So there is a chance that some one unknowigly calls the method to create the array of structures and hence the member variable may now points to another array of structure.
    Is there any way in Java to restict invoking of a function only once.
    A static variable with a check will solve this issue, but any other method so that calling of method itself becomes invalid to avoid RT usage?.

    Hi,
    I think, I understood know.
    You want to have a singleton holding a defined number of other objects (your arrays).
    This objects (your arrays) are semantically singletons itsself, because they should be constructed only once and than reused.
    Assuming I interpreted right, see my comments inline below.
    I know that who ever participate in this discussion is
    pretty sure about singleton class. Some of the code
    what I gave was irretating as Martin pointed out. So
    let me try to give more transparent code snippet,Thanks, that helped.
    >
    My aim :- I need a global object which is going to
    hold some arrays(data structures). This should be
    shared across various threads. (forget about the
    synchronousation part here). All these arrays won't be
    of same size, so I need methods for each
    datastructures to initialise to its required size.That's a little bit part of your problem, see below.
    My wayforward :- Create the global object as
    singleton. This object has methods for initialising
    different data structures.OK, fine.
    What is my doubt :- please see the following code
    fragment,
    public class Singleton {
    private Singleton singleton;
    private Singleton() {
    public static Singleton getInstance() {
    if (singleton == null) {
    singleton = new Singleton();
    return singleton;
    //other methods for the class
    private someObjType1 myArray1 = null;
    private someObjType2 myArray2 = null;
    private someObjType3 myArray3 = null; // etc....This "smells" like an candidate for another data structure, so that you don't have a fixed number of array.
    F.E.
    // Associate class of array elements (someObjTypeX) as keys with arrays of someObjTypeX
    private Map arrayMap = new HashMap();>
    public void CreateArray1(int size) {
    if (myArray1 == null) {
    myArray1 = new someObjType1[size];
    }Using the map, you create array should look like
    public void CreateArray(Class clazzOfArrayElem, int size)
      Object arr = arrayMap.get(clazzOfArrayElem)
      if(arr == null)
        arr = java.lang.reflect.Array.newInstance(clazzOfArrayElem, size);
        arrayMap.put(clazzOfArrayElem, arr);
    }Additionally the "ugliness" of this method results from the problem, that don't know the size of arrays at compile time.
    So it seem to be preferable to use a dynamic structure like a Vector instead of array. Then you don't have the need to pass the size in the accessor method.
    Then you can use a "cleaner" accessor method like
    public Vector getVector(Class clazzOfArrayElem)
      Vector vec = arrayMap.get(clazzOfArrayElem)
      if(vec == null)
        vec = new Vector();
        arrayMap.put(clazzOfArrayElem, vec); 
    return vec;
    }If you want to expose an array oriented interface f.e. for type safety you can have an accessor like
    public Object[] getAsArray(Class clazzOfArrayElem)
      Vector vec = arrayMap.get(clazzOfArrayElem)
      if(vec == null)
        vec = new Vector();
        arrayMap.put(clazzOfArrayElem, vec);
      arr = java.lang.reflect.Array.newInstance(clazzOfArrayElem, 0);
      return (Object[])vec.toArray(arr);
    // Real typesafe accessors as needed following
    public SomeClass1[] getAsArrayOfSomeClass1()
      return (SomeClass1[])getAsArray(SomeClass1.class);
    /.....This accessor for array interface have the additional advantage, that they return a copy of the data (only the internal arrays, no the object within the arrays!), so that a least a client using your class doesn't have access to your internal data (with the Vector he has).
    >
    // similarly for other data structures...
    So here CreateArray1 method will work fine because of
    the check myArray1 == null.
    Actual question :- Can I remove this check and
    restrick call to CreateArray1 more than one time ?.No. As I understood you want to have something like a "only-use-once-method". There is no such thing in Java I know of.
    But I don't see the need to remove this check. Reference comparison should have no real impact to the performance.
    this is going to benifit me for some other cases
    also.How?
    Hope this helps.
    Martin

  • Inherit Singleton class?

    hi there,
    We are learning Java at University and are supposed to develop a program to manage an art exhibition.
    The art exhibition is limited to 100 Objects (paintings and sculptures). Every object has a name, a value, an insurance, etc. and type specific attributes.
    So basically I've got three classes: Object, Painting extends Object and Sculpture extends Object.
    Now the easy way to limit the number of Objects to 100 would be to store them in an array with 100 fields.
    My idea was, that its way more elegant to have Object as a singleton class with 100 instances. But since I made the Object constructor private I cant extend Painting and Sculpture to Object any more.
    Is there a way round that?
    My singleton class is based on this example: http://www.javaworld.com/javaworld/javaqa/2001-11/01-qa-1102-singleton.html

    100 really puts the 'multi' in multi-ton, no? :^)
    And the "ton" as well :o)
    But it doesn't solve my problem of inheritance since the constructor is private.
    You don't need a multiton. It's inappropriate. You need a restricted collection.
    Let's imagine a few scenarios for a moment.
    You have an exhibition with a capacity of 100 artefacts, and it is fully populated. Now let's say someone submits an artefact for the exhibition, and if it's more interesting than the current least interesting artefact, the old one is removed and the new one is added in its plaace.
    Your 100-instance multiton can't cope with that: the additional artefact simply cannot exist.
    Let's also imagine that you want to open a second exhibition. Your multiton can't cope with that: at the most they will have 100 artefacts to share between them.
    Does that make sense?
    Think about the real world. There are lots of artefacts. Exhibitions are of limited size.

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

  • Static Class in Java

    Hi All,
    I have gone through en number of web-sites but i don't get a clear definition and a clear cut picture about static class in java
    I had plenty of questions in my mind. Somebody here - Java gurus and experts kindly please help me to understand about these things.
    What is static class ? When to declare a class as Static ? What is the difference between a singleton class and a static class ? It is allowing to create an instance of a static class . why ?
    Thanks,
    With Love,
    J.Kathir

    Sometimes you want to use a class merely as a place to put utility methods and/or constants. Such classes are never instanciated. There's no special syntax, it's simply a class consisting of static methods, and perhaps static fields. You give it a single private constructor so it can't be accidentally instanciated.
    In use it's not that different from a singleton. Generally I'd use a singleton if there was going to be non-constant global data values in it.

  • AVI classes in Java

    Does anybody know how to work with AVI in java (I mean, read avi, take images from avi and so on)? Help me please!!!

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

  • 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

Maybe you are looking for

  • Problem while using aggregate functions in EJB QL 2.1

    Hai all,    I am using aggregate function as follows    select max(c.id) from customer as c   for this iam selected check box EJB QL 2.1 in persistent.xml   this is validated by nwds, but while deploying server raising error like ejb ql syntax error.

  • Print payment advice

    Dear Sapgurus, We raise 10 p.os based on 10 pos invoice happen, 1 p.o value 10,000 total 1,00,000  finance team will pay the amount 100000 with reference of 10 invoices, i need print out for vendor payment with refernce of 10 invoices , How i will ta

  • WebLogic does not validate minOccurs="1" in webservices

    Hello, My WebService is deployed on WebLogic 10.3.3. WSDL/XSD describes input parameter number as mandatory: <xs:element minOccurs="1" maxOccurs="1" name="number" type="xs:int"/> MinOccurs="1" means that XML message must contain <number> tag, isn't i

  • Automatically rename photos?

    HI All, I have moved from a Samsung S2 to the Xperia Z1 and I think it is a brilliant phone but............. The problem I have is that I use it daily to take photos at work, and after I have taken a batch of photos I connect it to my pc and cut & pa

  • Flash Pro is ignoring changes to my base class when publishing / debugging

    Hi, I hope this will be in the correct section of the forum. I've been working with Actionscript 3 since a while now although most of the time I've just done straightforward coding using Flash Develop. This is the first time I'm building a more or le