About singleton pattern

if i use Class.forName(MyClass).newInstance() to init MyClass and MyClass uses singleton pattern, i wonder what is the difference between Class.forName(MyClass).newInstance() and Class.forName(MyClass).newInstance().getInstance(),i meant whether the former object is singleton or not(plz tell me why). or i should never let sth like this happen(i should not use both Class and singleton,plz tell me the reason 2) or is there any other pattern than can combine both of them.
any discussion will be appreciated.thanx in advance
Ciao,
zhxt

hi scratchback,
are you sure that MyClass uses singleton pattern? I haven't tried Class.forName(MyClass).newInstance() in a singleton class before, but I don't think it will work if your constructor is private.
singleton pattern is used for classes that you think should exist in the application only once.
hope it helps..
ronron

Similar Messages

  • A question about singleton pattern

    Will a singleton instance be a bottleneck of an application when many client address this instacne?
    and How can I do to deal with this problem?
    help me!

    Unless the singleton has synchronized methods or blocks of code that are synchronized there should be no bottle neck, as multi threads can access it at the same time.

  • Serializing a class that implements the Singleton pattern

    Hello,
    I am relatively new to Java and especially to serialization so the answer to this question might be obvious, but I could not make it work event though I have read the documentation and the article "Using XML Encoder" that was linked from the documentation.
    I have a class that implements the singleton pattern. It's definition is as follows:
    public class JCOption implements Serializable {
      private int x = 1;
      private static JCOption option = new JCOption();
      private JCOption() {}
      public static JCOption getOption() { return option; }
      public int getX() { return x; }
      public void setX(int x) { this.x = x; }
      public static void main(String args[]) throws IOException {
        JCOption opt = JCOption.getOption();
        opt.setX(10);
        XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(new FileOutputStream("Test.xml")));
        encoder.setPersistenceDelegate(opt.getClass(),  new JCOptionPersistenceDelegate());
        encoder.writeObject(opt);
        encoder.close();
    }Since this class does not fully comply to the JavaBeans conventions by not having a public no-argument constructor, I have create a class JCOptionPersistenceDelegate that extends the PersistenceDelegate. The implementation of the instantiate method is as follows:
      protected Expression instantiate(Object oldInstance, Encoder out) {
           Expression expression = new Expression(oldInstance, oldInstance.getClass(), "getOption", new Object[]{});
            return expression;
      }The problem is that the resulting XML file only contains the following lines:
        <java version="1.5.0_06" class="java.beans.XMLDecoder">
            <object class="JCOption" property="option"/>
        </java> so there is no trace of the property x.
    Thank you in advance for your answers.

    How about this:
    import java.beans.DefaultPersistenceDelegate;
    import java.beans.Encoder;
    import java.beans.Expression;
    import java.beans.Statement;
    import java.beans.XMLEncoder;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    public class JCOption {
        private int x = 1;
        private static JCOption option = new JCOption();
        private JCOption() {}
        public static JCOption getOption() { return option; }
        public int getX() { return x; }
        public void setX(int x) { this.x = x; }
        public static void main(String args[]) throws IOException {
          JCOption opt = JCOption.getOption();
          opt.setX(10);
          ByteArrayOutputStream os = new ByteArrayOutputStream();
          XMLEncoder encoder = new XMLEncoder( os );
          encoder.setPersistenceDelegate( opt.getClass(), new JCOptionPersistenceDelegate() );
          encoder.writeObject(opt);
          encoder.close();
          System.out.println( os.toString() );
    class JCOptionPersistenceDelegate extends DefaultPersistenceDelegate {
        protected Expression instantiate(Object oldInstance, Encoder out) {
            return new Expression(
                    oldInstance,
                    oldInstance.getClass(),
                    "getOption",
                    new Object[]{} );
        protected void initialize( Class<?> type, Object oldInstance, Object newInstance, Encoder out ) {
            super.initialize( type, oldInstance, newInstance, out );
            JCOption q = (JCOption)oldInstance;
            out.writeStatement( new Statement( oldInstance, "setX", new Object[] { q.getX() } ) );
    }   Output:
    <?xml version="1.0" encoding="UTF-8"?>
    <java version="1.5.0_06" class="java.beans.XMLDecoder">
    <object class="JCOption" property="option">
      <void property="x">
       <int>10</int>
      </void>
    </object>
    </java>

  • Implementing Singleton Pattern in ESB

    How do I go about implementing a singleton pattern within the ESB. Example usage would be for a cache. Prior to making an expensive service call I want to make sure that the data does not already exist within the cache.

    Have a look at metalink note 746108.1
    cheers
    James

  • Per Web Application singleton pattern

    Hello
    I have a application (ear) file that look something like this:
    App.ear
    -- Web_1.war
    ----- WEB-INF/lib/helper.jar
    -- Web_2.war
    ----- WEB-INF/lib/helper.jar
    -- Web_3.war
    ----- WEB-INF/lib/helper.jar
    inside helper.jar there is a singleton class., which get initialised differently depending on which Web_<X> it is loaded in. This currently works because each lib directory get loaded by each own classloader.
    I would really like to move the helper.jar up to the <ear file>/lib directory, but that means it is only loaded by the classloaders once anf thus the 3 singletons break as there is now only one.
    I would like to have some sort of "Per Web application" globally reachable "singleton".
    I have thought about using ServletContext, but it appears that there is no easy ways for helper classes to look it up, unless it is passed as a parameter.
    A second idea would be to use ThreadLocals, but that would rely on the Web container not reusing threads accross web applications. I am not sure if this is guranteed not to happen ...
    In any case, what is the best way to handle this ? is there any standard way or a design pattern to follow...

    I suppose another way of asking this question is this:
    is there a way to use the singleton pattern on a
    per-web-application basis without storing the
    singleton in the ServletContext? If I can find a way
    to do that, I can solve my initial problem.Some web application servers run each webapp in a separate JVM, or at least a separate classloader. If yours does either of those, then each webapp will have its own instance of the singleton. Try it.

  • Re: Singleton Pattern

    At PerSe Technologies, we have implemented the singleton pattern in our
    Enterprise Component Toolkit Framework. We have what we call our "shared
    data managers", which are visible to the appropriate architecture layer.
    We did not implement this as a service object and do not use a Forte
    "Shared" object. Instead, we use mutexes to control data locking ourselves
    which allows multiple tasks to execute against the shared data manager
    concurrently. This approach ensures us that we have one and only one copy
    of a given object at a time. Our approach also gives another benefit in
    that it caches frequently accessed data and has improved overall
    performance of our applications.
    Dustin Breese
    [email protected]
    Supervising Technical Consultant
    PerSe Technologies
    From: Mark Addesso <[email protected]>
    Date: Mon, 2 Feb 1998 12:36:02 -0500
    Subject: Implementing the Singleton pattern
    Has anyone implemented the singleton pattern in Forte? A singleton is =
    simply ensuring that there is one unique instance of a class. In other =
    OO languages I would create a class method which would use a class =
    variable to hold onto the unique instance. Since forte doesn't have =
    either of these (class methods or variables), I'm not sure how to do it.=
    I thought of using named objects, but it seems like a heavy =
    implementation. Any ideas.

    Is the danger that someone might make the Singleton
    cloneable really a the most important reason to make a
    Singleton non-extensible? I think not.It IS a good reason if cloning or subclassing it means
    you can end up with more than one in the same JVM. If
    you really implemented Singleton because "There Can
    Only BE One", I'd say prohibiting subclassing and
    cloning might be important.
    I gotta go with the OP on this. That comment is abit queer.
    I gotta go with the definition of Singleton on this
    and disagree. It's not like it's that difficult.
    Don't implement Cloneable or Serializable and make
    the constructors private. Done. What's the
    problem?
    At some point it is just too much.
    Are you going to implement a security manager as well? Because unless you do I can create JNI method and create a new object as well.
    If they don't understand that the singleton is a singleton then are you going to assume that that is the only problem that they are having?
    When I program I make assumptions about those that I work with and those that will come after me. I like to think that they have a minimal level of intelligent. They might not write the best code all the time but they do understand most of the ideas. And given that singleton the most used and probably easiest pattern to understand is it really necessary to be so protective?

  • May I make a singleton pattern like this

    as well know, singleton pattern in java always like the codes below:
    public class ClassicSingleton {
    private static ClassicSingleton instance = null;
    protected ClassicSingleton() {
    // Exists only to defeat instantiation.
    public static ClassicSingleton getInstance() {
    if(instance == null) {
    instance = new ClassicSingleton();
    return instance;
    but, when I read the java non-static initialization block section, I had an new idea about a this pattern. how about like this:
    public class ClassicSingleton {
         private static ClassicSingleton instance = null;
         protected ClassicSingleton() {
              // Exists only to defeat instantiation.
         static{
              instance = new ClassicSingleton();
         public static ClassicSingleton getInstance() {
              return instance;
    or like this
    public class ClassicSingleton {
         private static ClassicSingleton instance = null;
         protected ClassicSingleton() {
              // Exists only to defeat instantiation.
              instance = new ClassicSingleton();
         public static ClassicSingleton getInstance() {
              return instance;
    could anybody here tell me what's the different? thanks.

    I usually do something like this:
    public class ClassicSingleton {
      private static ClassicSingleton instance = new ClassicSingleton();
      private ClassicSingleton() {
        try{
          /* Construction logic here. */
        }catch(Exception e){
          /* Something bad happened, decide what to do, like set a flag indicating singleton isn't valid. */
      public static ClassicSingleton getInstance() {
        return instance;
    }

  • Do I need a Singleton pattern for this case

    Hello,
    I'm writing a game in Java and I have a very simple score manager class which just tracks the points the player so far has. I need to access this class in different pars of my app (gui, game core ...) so I created a singleton class which looks like this
    public class ScoreManager {
            private static ScoreManager instance = new ScoreManager();
            private int score = 0;
         private int highScore = 0;
         public static ScoreManager getInstance() {
              return instance;
         public int getScore() {
              return score;
         public int getHighScore() {
              return highScore;
         public void addScore(int scoreToAdd){
              score += scoreToAdd;
              if(score > highScore) {
                   highScore = score;
    }so far so good ..
    I would like to read the "highScore" from a file when the game starts and write it back when the game ends. I added those two methods:
         public void init(File highScoreFile) {
              highScore = readFromFile(highScoreFile);
                    score = 0;               
         public void dispose(File highScoreFile) {
                   writeToFile(highScoreFile);
         }So basically I call the init() method when the game stars and the dispose() when the game ends.
    It works but what I don't like is that the init() and dispose() methods are exposed and someone could call them in a wrong place.
    What would be a better way to do this ?
    Thanks for your help,
    Jesse

    safarmer wrote:
    You could keep track of the state (initialised, destroyed etc) in the manager and only perform the action if it is an expected state.
    private enum State { NOT_INITIALISED, INITIALISED, DESTROYED};
    private State currentState = State.NOT_INITIALISED;
    // i will leave the rest up to your imagination :) this looks good, thanks
    anotherAikman wrote:
    >
    It works but what I don't like is that the init() and dispose() methods are exposed and someone could call them in a wrong place. And who would that be? You´re the only one using the code, aren´t you?
    If not, you could still include in the documentation where to call those methods.
    no I'm not the only one working on this. Documentation can be useful but does not prevent calling wrong methods.
    YoungWinston wrote:
    I don't see any constructor. Usually, a singleton class should have a private one, even if it has no parameters. If you don't have any, Java will create a public no-parameter one as default.ok I forgot the private constructor.
    It works but what I don't like is that the init() and dispose() methods are exposed and someone could call them in a wrong place. Then my advice would be not to make them public. After all, your code is the only one calling these methods - yes?yes only the code of the app calls it.
    If you are convinced that your game requires one and only one score manager, then a singleton is probably the best way to go.
    I'm a little worried about the init() and dispose() methods though, because these suggest state changes, which is unusual for the singleton pattern. You may want to think about synchronizing them.
    An alternative might be to use properties to get and store your scores.ok for the synchronization. What would using the properties ? It would be just another type of storage backend and I'd still need to read/write it.
    Thanks for your help,
    J

  • Alternative Singleton pattern

    I'm sure someone must have thoguht of this before - but it struck me when I was using the Singleton pattern today.
    Obvisouly we know that the getInstance() method must be synchronized to prevent "mutliple singletons" being created, and the whole Double checked locking issues that arise from tryig to get around this.
    So, how about the following (non synchronized) version?
    class Singleton{
        private static Singleton staticInstance = new Singleton();
        private Singleton(){
            //private constructor
        public static Singleton getInstance(){
            return staticInstance;
    }Ok, so the instance isn't created "on demand", but lets face it all singletons are accessed at some point, so why not just create it when the class is loaded? Surely this will garuntee that only one copy is ever created or am I missing something obvious?

    It isn't obvious
    to me why the class would be loaded before the first
    reference to it, but perhaps there are some nuances
    (such as the EJB example) that I am not seeing.The difference is very nuanced. Actually I'm glad you posted this because I had the mistaken belief that the static initialization occured before the code started executing. However, there is still a difference.
    The static version gets loaded when the class is loaded. The lazy version gets executed when the getInstance method is executed. I had to contrive an example to show this, but I'm pretty sure that it does come up in certain environments.
    public class Garbage
        static String value = new String("Garbage");
        public static void main(String[] args)
            StaticSingleton.nothing();
            LazySingleton.nothing();
    class StaticSingleton
        private static StaticSingleton instance;
        static
            instance = new StaticSingleton();
        private StaticSingleton(){
            System.out.println("Constructing StaticSingleton");
        public static StaticSingleton getInstance(){
            return instance;
        public static void nothing()
    class LazySingleton
        private static LazySingleton instance;
        private LazySingleton(){
            System.out.println("Constructing LazySingleton");
        public synchronized static LazySingleton getInstance(){
            if (instance == null)
                instance = new LazySingleton();
            return instance;
        public static void nothing()
    }

  • Singleton pattern, scheduled receive location and suspended orchestrations

    Hello,
    In our project we have several orchestrations that are triggered every minute with the Scheduler Adapter (business requirement is near real-time).
    Each of these orchestration must have only 1 instance running at the same time, so we have implemented the singleton pattern. We followed a design like this one: https://fehlberg.wordpress.com/2008/06/06/biztalk-singleton-orchestration-design/
    But we end up having suspended orchestrations with the error "The instance completed without consuming all of its messages. The instance and its unconsumed messages have been suspended."
    I know it's a risk with this pattern. I thought it would happen only when the instance would run in more than 1 min (because the scheduler adapter is sending a file every minute).
    But it happens even with some instances running in about 15sec, so there is something I don't understand, here is an example:
    Here we can see that the TransferRegion orchestration started at 10:26:00 (which is expected) and failed.
    When I open the orchestration debugger, the time is different, the orchestration is shown starting at 10:26:44 (44 sec later):
    And the orchestration ended at 10:27:00:453.
    The message not consumed that caused the error has been triggered at 10:27:00.
    So I understand that the message arrived just after the listen shape but before the orchestration ends, but I don't understand why the orchestration started 44 sec after is was supposed to ...
    Any idea? I'm kind of clueless for now ...

    So, are these 8 Orchestrations actually processing messages or are they doing some other work every minute or so?
    If they're not processing actual messages, maybe a Windows Service or job scheduled by the SQL Agent or Windows Scheduler would be more...appropriate.  We all love BizTalk, but some parts of the stack do some things better.
    If they are processing messages or doing some genuine BPI type work, calling services, transformations etc., then maybe a Singleton+Scheduled Task is not the best solution.
    I'm assuming the actual requirement is the process must run with no less than 1 minute between executions, but if an execution takes >1 min, don't overlap.  An internal 1 min timer would probably work very well, but you still have the problem of
    activating and deactivating the Orchestration.  You'd basically have to build some control infrastructure similar to the EDI Batching Service.
    Here's a completely different suggestion:
    SQL Table that maintains the state of each process, say Active or Complete.
    Poll every 15 seconds a Stored Procedure that tests the status and returns an activation message when that process shows Complete.  It would flip it to Active at the same time.
    Orchestration runs and the last shape sends a message to change the status to Complete.
    Rinse Repeat.  No long running Orchestrations, Singletons, Correlations, etc...
    Hi John,
    We have 8 independent orchestrations. Each of them is triggered by different scheduled receive location.
    The orchestrations then process messages (calling stored procedures, mapping and calling web services).
    You are right for the requirement. I tried to deactivate the receive location at the beginning of the process and restart it at the end, but I ran into some weird errors on the SSO DB and others like "Could not retrieve transport type data for Receive
    Location 'Trigger_xxxxx_SCHEDULE' from config store. The transaction associated with the current connection has completed but has not been disposed.  The transaction must be disposed before the connection can be used to execute SQL statements."
    Thanks for the new design suggestion, I will see the effort required and if the client approves it ;)

  • Question about singleton design

    Hi all
    i have a question about singleton design. as i understood it correctly, this pattern garantees us a single instance of a class at any time. in a environment of concurrent access(multiple user access at the same time) , does this single instance put a constraint on concurrency(singleton == synchronization)? i have developed a service object that reads in properties and constructs some other objects. the reason i made it singleton is that i only want this service object to load the properties once. and when it is called to create other objects, it always has one copy of the propertis. making this service singleton, will it limit the threads to access it and construct other objects? thanks for your help.

    If there's no write access to the HashMap, then
    you're thread safe.You were probably typing at the same time as the previous post, which explicitly says there IS write access to the HashMap.
    I don't know what it is, but people seem to have this magical view of concepts. Singleton is just what it is. It doesn't have a magical aura that causes other things to behave differently. A singleton is just Java code that can have thread safety problems just like any other Java code. So to the OP: forget about the fact that this is a singleton. That's irrelevant. Ask if a method needs to be synchronized.
    (And yes, a method that tests if a variable is null and assigns an object to it if it isn't null does need to be synchronized if it's going to have multiple threads accessing it.)

  • How we can limit the number of concurrent calls to a WCF service without use the Singleton pattern or without do the change in BizTalk Configuration file?

    How can we send only one message to a WCF service at a time? How we can limit the number of concurrent calls to a WCF service without use the Singleton pattern or without do the change in BizTalk Configuration file? Can we do it by Host throttling?

    Hi Pawan,
    You need to use WCF-Custom adapter and add the ServiceThrottlingBehavior service behavior to a WCF-Custom Locations.
    ServiceThrottlingBehavior.MaxConcurrentCalls - Gets or sets a value that specifies the maximum number of messages actively processing across a ServiceHost. The MaxConcurrentCalls property specifies the maximum number of messages actively
    processing across a ServiceHost object. Each channel can have one pending message that does not count against the value of MaxConcurrentCalls until WCF begins to process it.
    Follow MSDN-
    http://msdn.microsoft.com/en-us/library/ee377035%28BTS.10%29.aspx
    http://msdn.microsoft.com/en-us/library/system.servicemodel.description.servicethrottlingbehavior.maxconcurrentcalls.aspx
    I hope this helps.
    Rachit
    If this answers your question please mark it accordingly. If this post is helpful, please vote as helpful by clicking the upward arrow mark next to my reply.

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

  • Use of Singleton pattern in Distributed environment

    Can somebody say why it is not advisable to use Singleton pattern for developing client server applications.

    Client-server does not imply distributed environment, IMHO. There are pretty simple C/S architectures where Singleton pattern is not generally a bad thing.
    Distributed environments usually have multiple VMs running, while the singleton pattern typically implemented is a per-VM singleton.

  • Best Practice:  Using a static variables and methods vs singleton pattern

    Just curious, since when anything, within a class, is denoted as static it typically will be stored in main memory as a class property(method, variables, etc). Is it a good practice to be doing this all the time or is the singleton pattern a better choice. Please explain why. Thanks.

    I wouldnot make anything other than the constants and the instance itself static. And I cant think of a reason wjy one would.

Maybe you are looking for

  • SPA2102 hotline feature with Voice Over IP solution

    I have a VPBX and use a call box at the front entrance to a local jail. When the Avaya LUADS Dev 156 goes off hook the dial plan dials an extension inside the jail. The call is properly routed from the callbox through a Linksys SPA2102 through the VP

  • My iPhone 3gs is lagging and searching for signal all the time. Help!!

    Well, my phones like 3 years old...and latley it's been lagging, turning it's self off, not sending my messages, when I call other people it doesn't go through, and if it does they can barly hear me. I thought it was my sim card so I got a new one an

  • How do you change/adjust border width for all the cells in a table created in Pages?

    How do you change/adjust border width for all the cells in a table created in Pages? Note- I am trying to figure out how to create and format tables in the latest version of the Pages app on an iPad air (iOS 8.1.1.1) . Creating tables, adding or remo

  • Error opening PDF

    Hi all,     I'm having problems opening PDF files. I'm using FM CONVERT_OTFSPOOLJOB_2_PDF to generate the file into the server. Then I'm using class/method VIEWER->VIEW_DOCUMENT_FROM_TABLE to open it. The problem is that some files are opened and oth

  • Updateproblem MUSE 2014

    hallo Ich nutze MUSE CC und erhalte nach einem UpDate ein weiteres Programm mit dem Namen MUSE CC 2014. Das irritiert und sieht auch anders aus. Ein UpDate ist das ja dann im eigentlichen Sinne nicht. Nun wurden für beide Versionen !! Updates angebot