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,

Similar Messages

  • Singleton Class ArrayCollection within Flashbuilder (Mobile) empty?

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

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

  • 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

  • How to import .jar files in order to use the classes within this file

    hello guys,
    I'm just wondering how can i import .jar files in order to uses the classes within this file.
    let's take an example:
    i have a folder in which I have many .jar files which contain classes to be called. the full path of this folder is set in the Classpath inside the enviroment variables.
    so does anyone have any idea how can i import these .jar files so i can use the classes?
    thank you.

    Hi,
    My problem is that: I created a Serializable class in a project. And I added this project (first project) to another project (second project). First project is appearing in the second project' s Libraries folder. No problem. I want to create a jar file from second project. i.e. I want to Build second project (I use NetBeans IDE). I am using Build Main Project tab under Run. It is falling out. I am finding it second project' s jar file under its folder. I am clicking on it. But it is NOT WORKING. Do you know WHY. Could you help me please?
    Thanks,

  • Synchronized Instance Methods in Singleton Class

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

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

  • 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

    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

  • Trying to create object of a class within servlet - help!!

    I have created and compiled the following classes within
    C:\bea\wlserver6.1\config\mydomain\applications\DefaultWebApp\WEB-INF\classes
    1)LoginServlet
    2)LoginManager
    3)I have LoginServlet trying to create an object of type LoginManager, very simple,
    but I get the following errors:
    Cannot resolve symbol: LoginManager lm = new LoginManager();
    ^
    Cannot resolve symbol: LoginManager lm = new LoginManager();
    ^
    4)I have the .java and .class files located within the same directory, so I don't
    see what's wrong here??? HELP!
    LoginManager looks like:
    public class LoginManager {
    public boolean authenticateUser(String username, String password){
              boolean status = false;
    //simple code for string matching
              return status;
    LoginServlet looks like:
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    public class LoginServlet extends HttpServlet {
         // Constructors
         // Variables
         public static final String CONTENT_TYPE = "text/html";
         public boolean LOGIN_STATUS;
         // Methods
         public void service (HttpServletRequest req, HttpServletResponse res)
              throws IOException {
              String username = "";
              String password = "";
              LoginManager lm = new LoginManager();
              username = req.getParameter("username");
              password = req.getParameter("password");
              LOGIN_STATUS = lm.authenticateUser(username, password);
              res.setContentType(CONTENT_TYPE);
              PrintWriter out = res.getWriter();
              out.println("<html><head><title>Hello World</title></head>" +
                             "<body>Hello! Your login status is " + LOGIN_STATUS +
                             "</body>" +
                             "</html>");
         public void init (ServletConfig config) throws ServletException {
              super.init(config);

    Do you have . in the CLASSPATH when compiling your servlet?
    ron <[email protected]> wrote:
    I have created and compiled the following classes within
    C:\bea\wlserver6.1\config\mydomain\applications\DefaultWebApp\WEB-INF\classes
    1)LoginServlet
    2)LoginManager
    3)I have LoginServlet trying to create an object of type LoginManager, very simple,
    but I get the following errors:
    Cannot resolve symbol: LoginManager lm = new LoginManager();
    ^
    Cannot resolve symbol: LoginManager lm = new LoginManager();
    ^
    4)I have the .java and .class files located within the same directory, so I don't
    see what's wrong here??? HELP!
    LoginManager looks like:
    public class LoginManager {
    public boolean authenticateUser(String username, String password){
              boolean status = false;
    //simple code for string matching
              return status;
    LoginServlet looks like:
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    public class LoginServlet extends HttpServlet {
         // Constructors
         // Variables
         public static final String CONTENT_TYPE = "text/html";
         public boolean LOGIN_STATUS;
         // Methods
         public void service (HttpServletRequest req, HttpServletResponse res)
              throws IOException {
              String username = "";
              String password = "";
              LoginManager lm = new LoginManager();
              username = req.getParameter("username");
              password = req.getParameter("password");
              LOGIN_STATUS = lm.authenticateUser(username, password);
              res.setContentType(CONTENT_TYPE);
              PrintWriter out = res.getWriter();
              out.println("<html><head><title>Hello World</title></head>" +
                             "<body>Hello! Your login status is " + LOGIN_STATUS +
                             "</body>" +
                             "</html>");
         public void init (ServletConfig config) throws ServletException {
              super.init(config);
    Dimitri

  • Help required in understanding the rationale behind singleton class

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

    answer lies in GoF book.

  • Java Inner classes within the Threading paradigm

    Hi all.
    Im familiar with static nested classes, method local classes, inner classes and anonymous classes.
    But what I am a little perplexed by, is when exactly to use inner classes or static nested classes? (forgetting anonymous classes and method local classes).
    I read this article (http://www.javaworld.com/javaworld/javaqa/2000-03/02-qa-innerclass.html) and the first point makes for a good argument, but why nest the class? Why not define it as an external class?
    Also you typically find nested classes within the Threading paradigm, but why?
    I typically would create a top level class (non nested) that would implement the Runnable interface, override run() and then
    use this class when constructing a new Thread.
    Any clarification would be greatly received.
    Thanks and Happy Friday.

    Boeing-737 wrote:
    I read this article (http://www.javaworld.com/javaworld/javaqa/2000-03/02-qa-innerclass.html) and the first point makes for a good argument, but why nest the class? Why not define it as an external class?
    I was going to provide some reasons, but when I read the article I found they were already there. Following the DRY principle I'm going to let the article speak for itself.
    Also you typically find nested classes within the Threading paradigm, but why?No, I don't. If that's where you typically find them then you haven't had a varied experience.
    I typically would create a top level class (non nested) that would implement the Runnable interface, override run() and then
    use this class when constructing a new Thread.So carry on doing that, if it works for you.

  • To ragnic and other about Singleton class

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

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

  • Singleton class with static method

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

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

  • Singleton class + JTable mouseClicked

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

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

  • (retain) properties in the singleton class

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

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

Maybe you are looking for