Use of singleton calss

hi
can any one tell me
singleton class: -- we cant create object directly from out side, using factory method we can create object for that class.
that means we are creating the object for singleton class.
my doubt is why we go singleton class in sted of create the object directly using new key word.
what is the difference between using singleton factory method to create object and using new key word to create object.
thanks in advance.

You're mixing up the factory method pattern and the singleton pattern here. Probably because most people implement their singletons using a factory method as well. The reason we use singletons (those of us who still do) is to ensure that only one instance of a class can exist. There are several reasons to use factory methods. We might want to optionally create an instance of a subclass, for example. Or give the methods meaningful names that a mere constructor can't communicate.

Similar Messages

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

  • When a context node use non-singleton, how to invoke the supply funtion eve

    when a context node use non-singleton, how to invoke the supply funtion everytime the lead selection is changed ?

    Hi wei,
    <b>Non-singleton nodes:</b>
    Web Dynpro allows you to define non-singleton nodes. Each non-singleton node has one node instance for each node element of the parent collection at runtime. The advantage is that each instance can be accessed directly. When using non-singleton nodes, the nodes are only created when the node values are retrieved. This can save resources that otherwise would slow down the performance of the application.
    <b>Supply function:</b>
    The Web Dynpro tools also automatically enhance the corresponding controller class with a supply function including the user coding area contained in it
    Supply functions are implemented as methods of type
    <b>public void supplyChildNodeElements(SomeChildNode node,
                                        SomeParentNodeElement)</b>
    in a Web Dynpro controller (view controller or custom controller). Supply functions and context nodes have a 1..1 relationship, that is, supply functions are specific for individual context nodes. Under certain conditions, supply functions are called by pages in the Web Dynpro runtime environment.
    Hope this helps u,
    Regards,
    Nagarajan.

  • Using a Singleton Mediator to provide loose coupling

    I need to discuss the pros and cons of using a singleton mediator to provide loose coupling between component implementation classes.
    Suppose you are building a SE or a BC where an endpoint is defined upon a SU deployment. In this scenario, you will end up finding out that the Component, ComponentLifeCycle and ServiceUnitManager implementations should know each others instances. I can figure out these solutions:
    -     Use tight coupling
    -     The component implements the three interfaces (or two of them and associates the third)
    -     Use a singleton mediator to hold the instances
    -     Use a third party solution, like Spring's ApplicationContext and ApplicationContextAware contracts
    -     Some other solution I didn't think of (the scenario has to be more specific)
    Assuming the scenario as described above, I prefer the third solution.
    I appreciate your opinions.
    Hossam Karim

    When you evaluate the JBI implementations available, you will notice that each one has built a less abstraction layer over the JBI component contracts in order to simplify its subsequent tasks. As a component builder, you would either reuse one of these layers and get tight with a specific implementation, or start writing your own.
    I recently proposed a simple framework to my team; you can find a class diagram here (http://www.gaiati.com/products/emee/framework.png), it has the following elements:
    �     AbstractBootstrapAdapter: Simple adapter for the Bootstrap interface
    �     ComponentApplicationContext: Provides a Spring based Application context for this component, the context beans should be loaded upon component initialization. An instance of this class will be available to all classes or interfaces that extend the ApplicationContextAware Spring interface. All classes and interfaces on the previous diagram that associate a ComponentApplicationContext instance (applicationContext) implement the ApplicationContextAware interface. One exception is the AbstractComponentAdapter class, because it actually creates the instance.
    �     AbstractComponentAdapter: Adapter for the component and lifecycle contracts. Upon initialization, this class creates a ComponentApplicationContext instance, and uses the beans to configure itself, the class recognizes other framework contracts and able to communicate with them.
    �     AbstractMessageListener: Consumes this component's DeliveryChannel message exchanges, and fires a handling trigger.
    �     DeployedEndpoint: Represents an endpoint that was deployed using a SU
    �     DeployedEndpointConfiguration: Holds the configuration needed by a DeployedEndpoint instance
    �     DeployedEndpointTarget: Represents the target JBI specific address that a DeployedEndpoint instance should route the messages to.
    �     GenericMessageListener: Handles the trigger fired by the AbstractMessageListener, delegating the work to an instance of the DeployedEndpoint interface
    �     GenericServiceUnitManager: Handles GenericServiceUnit instances
    �     GenericServiceUnit: Acts as a proxy and encapsulates a DeployedEndpoint instance
    �     AbstractDeployedEndpointFactory: An abstract factory for creating DeployedEndpoint instances using DeployedEndpointConfiguration instances
    Yes, I ended up using Spring, and you are right, it might not be appropriate to attempt to separate the interfaces, may be I misunderstood or was mislead by Open-ESB implementation of the SOAP and file binding components.
    It is true sometimes you can have "personal taste", but most important is to achieve best practice.
    Finally, I hope the specification in its next versions, would provide us with a best practice framework or proposal, instead of so much choices.
    Hossam Karim

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

  • Candidates for use of Singleton Pattern

    Hi
    Can any guide me , where to use Single Design pattern in Java Based Applications
    Should i use Singleton Pattern in the following situations
    1)RMI Server
    2)Controller Classes ( MVC) invoked by Servlet
    3)Database cashing /handling classes
    Please suggest other suitable places also
    Thanks in Advance

    Hii
    Typical uses of a singleton pattern are in those cases where you have to have a single instance of a class.For example if u have an RMI based application and the client needs to perform a RMI lookup(for the URL etc)in that case for a particular user you wud like to have just a single instance for the lookup.
    In case of controller classes invoked by the servlet you would typically not want a Singleton as multiple instances of the servlet might require to use a controller object.As the request parameters would be different for each servlet instance,you would need a controller object for each of them.

  • Can I Use Singletone  Pattren for DAO in Stateless EJB?

    Hi friends,
    I have a design in which i am creating an Business Layer using EJB (Stateless). In my case i have only read only to DataBase and at one case where i will be updating the database. But my application will be accessed by many concurrent users.
    My problem is if i create a DAO with singleton pattren then it will be returning the same instance to all the person who access the DB. So if one person is reading the database and at the same moment one more person request for update since the DAO is singleton object will there be any conflict?
    Reply soon

    Hi Martin.S
    Thanks for your suggestion.
    U Asked
    You need to think about why have you have made your DAO a Singleton. You need to ask yourself, SHOULD it be a Singleton? It may be valid decision but I find that doubtful. Singleton DAO's suit only limited set of circumstances. Why i decided to use singleton pattren was :
    Since i am using session bean and if i won't use Singleton pattren and
    If my app was used by say 1000 users
    Then 1000 Dao instaces whould be created!
    The App Server will have 1000 refrences which may be a performance issue and may slow down the server due to more usage of server resource. So i need to know weather is it a good idea to use the Singleton pattren for DAO when using SessionBeans?
    And one more doubt I have Martin
    If i use One Dao Class Per One Table Then How about the factories if i use singleton? Need to create so many factories as DAO's? *reply
    Also i think if i use Single DAO per Table and if i have say 1 user accessing the DAO and he is in the Middle of his execution and user 2 requests for the same DAO once again the situation is worse! Am i right?
    So I think Singleton pattren comes into handy only when one person is accessing the DAO at a time. After he completes then only we can give access to some one else.
    And also while Using EJB's Using syncronized DAO is not preffered since EJB's are for multiple access
    So do you have any solution for the same? Currently I am using ordinary DAO and creating multiple instances in the Session Bean.
    Is there any way to Use SingleTon Pattren inside SessionBean?
    Reply
    A Singleton DAO would be valid choice when you are doing performance/throughput optimisation for read only access to dataset which you have cached for speed, but need to ensure only one copy exists for memory efficiency.One more query martin,
    How can we use it for read only access to a data set?
    For example i have a DAO which queries and returns some result sets based on some input value given by the user
    Now take a senario1: User1 supplys some input value and executes method1() and he is in the middle.
    User2 comes in and acess the same method1() with different input value
    Since it is a SingleTon Pattren The User2 will get same refrence
    So user1 will get the result set that is having the input parameters of user2. Right?????????
    So my inference is we cannot use singelton pattren for concurrent acess of the DAO.What do you say
    Please Reply Martin

  • Can i use singleton for storing current login id

    hello,
    can i use a singleton for storing login userid temporarilary for application lifetime. Is there any issue if more than 2 users login at the same time as the singleton object will be static ! ..

    let me ask more precisely..
    is there anything of concern if i run my program(involving statics) by 2 jvm instances.
    public class Demo extends Thread
         static String[] myargs ;
         public static void main(String args[])
              myargs = args;     
              try
                   Demo.sleep(5000);
              catch(InterruptedException e)
              System.out.println(myargs[0]);
    }look at the pre code...what if i try to run it by using 2 command promptS
    giving different aruements (a bit quick)
    Edited by: rajat on Dec 28, 2007 7:14 AM

  • How do I use multiple classes to access the same object?

    This should be staightforward. I have and object and I have multiple GUIs which operate on the same object. Do all the classes creating the GUIs need to be inner classes of the data class? I hope this question makes sense.
    Thanks,
    Mike

    public final class SingletonClass {
    private static SingletonClass instance;
    private int lastIndex = 10;
    public final static SingletonClass getInstance()
    if (instance == null) instance = new SingletoClass();
    return instance;
    public int getLastIndex() {
    return lastIndex;
    }1) This won't work since one could create a new SingletonClass. You need to add a private constructor. Also, because the constructor is private the class doesn't have to be final.
    2) Your design isn't thread-safe. You need to synchronize the access to the shared variable instance.
    public class SingletonClass {
        private static SingletonClass instance;
        private static Object mutex = new Object( );
        private int lastIndex = 10;
        private SingletonClass() { }
        public static SingletonClass getInstance() {
            synchronized (mutex) {
                if (instance == null) {
                    instance = new SingletonClass();
            return instance;
        public int getLastIndex() {
            return lastIndex;
    }if you are going to create an instance of SingletonClass anyway then I suggest you do it when the class is loaded. This way you don't need synchronization.
    public class SingletonClass {
        private static SingletonClass instance=new SingletonClass();
        private int lastIndex = 10;
        private SingletonClass() { }
        public static SingletonClass getInstance() {
            return instance;
        public int getLastIndex() {
            return lastIndex;
    }If you don't really need an object, then you could just make getLastIndex() and lastIndex static and not use the singleton pattern at all.
    public class SingletonClass {
        private static int lastIndex = 10;
        private SingletonClass() { }
        public static int getLastIndex() {
            return lastIndex;
    }- Marcus

  • Best practice using regular properties

    What is considered best practice when it comes to using properties ? Example like hostname, port number when connecting towards an external resource.
    Should property files be used ? Is this considered a bad practice ? Should deployment descriptors be used - if so - how do one update these properties when changed ?
    Are there any utility classes that makes easy access to this kind of properties ?
    ---- Trond

    Depends on what properties. Many properties like hostname etc can be retrieved using different API calls - such as the request object or other portal specific objects.
    Properties that you applications need, that might change - can be stored in a properties file. I use a singleton to retreive them - and have a reload method on the singleton that I can call if I need to reload the properties once the server has started.
    Kunal

  • Use of synchronisation with the SUN DAO Pattern

    With reference to the design pattern Core J2EE Patterns Data Access Object: http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.html
    I am writing a DAO package to handle access to multiple datasources at a record level (e.g. user records may be located at datasource A, but customer records at datasource B). The role of the package is to provide DAO objects to clients (e.g. business objects in an application package to come later). Nothing too unusual. I have digested the SUN design pattern for DAO.
    As I understand it, it can be summarised as: client code calls on an abstract DAOFactory to provide the appropriate concrete DAOFactory . The concrete factory can then supply the correct DAO object. The concrete DAOFactory is also responsible for providing the connection services (such as pooling). So far so good. I have pasted the concrete DAOFactory code form the design pattern page:
    // Cloudscape concrete DAO Factory implementation
    import java.sql.*;
    public class CloudscapeDAOFactory extends DAOFactory {
    public static final String DRIVER=
    "COM.cloudscape.core.RmiJdbcDriver";
    public static final String DBURL=
    "jdbc:cloudscape:rmi://localhost:1099/CoreJ2EEDB";
    // method to create Cloudscape connections
    public static Connection createConnection() {
    // Use DRIVER and DBURL to create a connection
    // Recommend connection pool implementation/usage
    *** can a connection pool be implemented in a static method? ***
    public CustomerDAO getCustomerDAO() {
    // CloudscapeCustomerDAO implements CustomerDAO
    return new CloudscapeCustomerDAO();
    public AccountDAO getAccountDAO() {
    // CloudscapeAccountDAO implements AccountDAO
    return new CloudscapeAccountDAO();
    public OrderDAO getOrderDAO() {
    // CloudscapeOrderDAO implements OrderDAO
    return new CloudscapeOrderDAO();
    I have some questions on this overall design.
    1)     The design for the factories as given looks inelegant and requires upgrading each time a new DAO is added ? much better surely to dynamically generate the DAOs using reflection. If I implement a mapping of data type to data source using a properties file (typical entry, Key = Role, Value = Oracle), the use of abstract and concrete factories can be reduced to a single factory. The single factory reads in the mapping on initialisation and provides a method getDAO to client code. The method takes the data type, looks up the data source and returns the correct DAO class using reflection (e.g. the client passes ?Role? to getDAO and the factory returns Oracle + DAO + Role = OracleDAORole.class). This also has the advantage that the client code does not need to specify the data source to use. I have read some forums and note that performance is an issue with reflection; however I have not seen any significant difference in performance between using reflection to generate a class name and using a factory pattern (e.g. testing just the code paths, for 10 million operations, both reflection and factory took 2.5 seconds each). Does anyone have any opinions on the pros and cons of this approach?
    2)     If we go with the original DAO design (ignoring 1 above) I have marked the part of the concrete factory code that I have a problem with: using a connection pool in the concrete factory. As the factory?s createConnection method is static, you cannot use NotifyAll or Wait methods here, and therefore you cannot synchronise access to the pool (correct?). I have therefore created a separate connection pool class (which uses the singleton pattern and uses synchronised methods to manage the pool). Is this a sensible way to approach this or is there a clever way to synchronise access to static methods?
    Thanks in advance - Alan

    These resources may be helpful:
    http://daoexamples.sourceforge.net/related.html
    http://daoexamples.sourceforge.net/index.html

  • To ragnic and other about Singleton class

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

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

  • Singleton? Don't want to keep reading database

    Hi there,
    I have a java web application, when it starts up I want it to load some information into a singleton so that all requests for this information come from memory not via a database call. The information will change very infrequently but I don't want to hard-code it (I guess I could use a property file). Anyway if I use a singleton will it not be garbage collected as soon as no other objects reference it? If it's garbage collected then the next time some accesses it another database call with be made and I don't want that to happen. I want this object to reside in memory always (it's not large so the hit is not that great). The singleton will basically hold a Vector of "objects" and one of this "objects" attributes is another Vector. To populate it requires 3 trips to the database each time. I would prefer 3 trips up front upon application loading and then no more until a restart occurs. Any suggestions?
    Cheers, Max

    The Singleton pattern is a fairly straightforward pattern. I have used it succesfully several times. Here is an example.
    public class GetInfo {
      private static GetInfo singleton;
      private static Object dataSavedInMemory;
      //Prevent anyone from instantiating this object
      private GetInfo() {
      private static synchronized void initialize() {
        singleton = new GetInfo();
        //One time database processing to save data in memory would go here
        dataSavedInMemory = new String("Hello World");  //just for illustration purposes
      public static GetInfo instance() {
        if (singleton == null)
          initialize();
        return singleton;
      public Object getData() {
        return dataSavedInMemory;
      //Example usage
      public static void main(String[] args) {
        //Get data saved in memory
        Object data = GetInfo.instance().getData();
        System.out.println(data);
        //or
        GetInfo inst = GetInfo.instance();
        Object data2 = inst.getData();
        System.out.println(data2);
    }

  • How to set a specific width to all the TextInputs used in a mxml file on its creation complete?

    How to set a specific width to all the TextInputs used in a mxml file on its creation complete?

    Hi subhajit nag,
    I think the best approach would what I say is if you can make use of a Global variable or using a Singleton class having a variable which can be accessed globally through out the application.
    Below is the sample what I am talking to:
    So in below example you can access the variables textInputWidth and textInputHeight globally throghout the application since you have decalred them in main mxml file.
    You can access these variabled in another mxml file as Application.application.textInputWidth and Application.application.textInputHeight. So if at all you are required to modify these values you are only required to modify at a single place in main mxml file..thats it.
    If you are use any Singleton classes like ModelLocator you can place these variables in this class and refer from that class.
    Hope this resoved your problem..
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical">
    <mx:Script>
      <![CDATA[
       [Bindable]private var textInputWidth:int = 250;
       [Bindable]private var textInputHeight:int = 25;
      ]]>
    </mx:Script>
    <mx:Canvas id="canvas1">
      <mx:TextInput id="txt1" width="{textInputWidth}" height="{textInputHeight}"/> 
    </mx:Canvas>
    <mx:Canvas id="canvas2">
      <mx:TextInput id="txt2" width="{textInputWidth}" height="{textInputHeight}"/> 
    </mx:Canvas>
    <mx:Canvas id="canvas3">
      <mx:TextInput id="txt3" width="{textInputWidth}" height="{textInputHeight}"/> 
    </mx:Canvas>
    <mx:TextInput id="txt4" width="{textInputWidth}" height="{textInputHeight}"/>
    <mx:TextInput id="txt5" width="{textInputWidth}" height="{textInputHeight}"/>
    </mx:Application>
    If this post answers your question or helps, please kindly mark it as such.
    Thanks,
    Bhasker Chari 

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

  • Retina Display MacBook Pro image persistence problem.

    Hello, I have recently ( about 3 months ago) bought a Retina MacBook Pro and installed Windows via Bootcamp on it. I unfortunately am used to Windows. Well recently I tried to migrate to OS X and use it more often. Whilst doing so something caught my

  • ** Transformation step - 1:n mapping error - BPM

    Hi friends, In my BPM transformation step I am doing 1:n mapping. I created & tested the message mapping and Interface mapping for this. Its working fine there. But, while I put the payload, the message is not splitted. Instead only the first message

  • Let me know how to Implement Drill throughs in the NW verdion

    Hi, I am doing BPC migration project from MS7 to NW7.5. There are some Drill throughs are developed in the MS version,And there is no URL in the MS fro this.They stored the data in a table in the backend (SQL) Let me know how to Implement Drill throu

  • Please help Z77MA-G47

    So i just got my MSI Z77MA-G45 LGA 1155 Intel Motherboard z77  slotted it all together all seemed fine untill it wouldn't recognize my hard drive. I currently dont have a dvd drive at the moment so i put all the files of the win7 and msi drivers on t

  • How to correct the corrupted archive log files?

    Friends, Our restore method is cloning type. today i fired this statement(this is one is usually do for the restore) "recover database until cancel using backup controlfile" i have 60 files in the archive folder. it executs only 50 files when it come