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

Similar Messages

  • How to create Multiple instances of This SingleTon class

    import java.io.*;
    import java.util.Properties;
    import java.net.URLEncoder;
    public class ddd
              // declaring variables
              static private ddd _instance;
              String connectIP;
              int connectPort;
              String systemID;
              String password;
         String systemType;
              // Constructor with arguments
              private ddd()
              globalInit();
         // method returning the ddd instance.
              public static      synchronized ddd getInstance()
              if (_instance == null)
                        _instance = new ddd();
              return _instance;
              // Global initialisations
              public void globalInit()
              systemID ="XXXXX" ;
              password ="XXXXX";
              systemType ="Null";
              public static void main(String[] args)
                   ddd sb;
                   sb = ddd.getInstance();
                   System.out.println(ddd.getInstance());

    Don't cross-post:
    http://forum.java.sun.com/thread.jsp?thread=547911&forum=54&message=2669925
    http://forum.java.sun.com/thread.jsp?thread=547912&forum=31&message=2669928
    Sorry, I can't help but think that this is one of the more foolish questions I've read in a while.
    The pattern Singleton means "I only want one of these in a single JVM". If you want multiple instances, or even a restricted number of instances, then rewrite the class (something like this):
    public class LimitedEdition
        public static final int MAX_EDITIONS = 3;
        private static int numEditions;
        public static void main(String [] args)
            try
                if (args.length > 0)
                    int numEditions = Integer.valueOf(args[0]).intValue();
                    for (int j = 0; j < numEditions; ++j)
                        LimitedEdition limited = new LimitedEdition();
                        System.out.println(limited);
            catch (Exception e)
                e.printStackTrace();
        public LimitedEdition() throws InstantiationException
            if (numEditions < MAX_EDITIONS)
                ++numEditions;
            else
                throw new InstantiationException("Only " + MAX_EDITIONS + " instances allowed");
        public String toString()
            return "[ instance # " + numEditions + "]";

  • Access instance method of a class inside instance method of another class

    Hi Friends
    I have to use one c1->m1.
    c1 is a public instantiation and m1 is a public Instance Method.
    I called this m1 method by creating c1 object for class c1.
    But problem is inise M1 method,i have a statement
    CALL METHOD mo_central_person->if_hrbas_pd_object~read_infty.
    here mo_central_person is of type some other class c2.
    As without creating the object,i didn't use the above interface method.
    Can please suggst me how to handle this.
    Regards,
    Sree

    class a definition.
      public section.
      methods : display,
                disp.
      data : a(10) type c value '10',
             b(5) type c value 'abc'.
    endclass.
    class a implementation.
      method display.
        write : a.
      endmethod.
      method disp.
        write : b.
      endmethod.
    endclass.
    class b definition inheriting from a.
      public section.
      methods : display1.
      data : c(7) type c value '7'.
    endclass.
    class b implementation.
      method display1.
       call method display( ).
        write c.
      endmethod.
    endclass.
    start-of-selection.
    data : o_obj type ref to b.
    create object o_obj.
    call method o_obj->display1.
    the method display is in class a.
    we can call this method in class b using the following statement.
    method display1.
       call method display( ).
        write c.
      endmethod.

  • Trivial Lock Question - nested synchronized instance method call

    Hi there. I have a question surrounding the following code block:
            public synchronized void bow(Friend bower)
                System.out.format("%s: %s has bowed to me!%n",
                        this.name, bower.getName());
                bower.bowBack(this);
            public synchronized void bowBack(Friend bower)
                System.out.format("%s: %s has bowed back to me!%n",
                        this.name, bower.getName());
            }If the bow method is invoked by the currently executing thread that has obtained the lock on the current instance and the
    call "bower.bowBack()" is invoked, what happens? Is the lock released then obtained again by the current thread? or does it hold onto it since the method
    "bowBack" is called within the method "bow"?
    Thank you!
    Regards

    thank you as always mr. verdagen!
    regards

  • To ragnic and other about Singleton class

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

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

  • How to implement a singleton class across apps in a managed server}

    Hi ,
    I tried implementing a singleton class , and then invoking the same in a filter class.
    Both are then deployed as a web app (war file) in a managed server.
    I created a similar app , deployed the same as another app in the same managed server .
    I have a logger running which logs the singleton instances as well.
    But am getting two instances of the singleton class in the two apps - not the same .
    I was under the impression that , a singleton is loaded in the class loader level , and since all apps under the same managed server used the same JVM , singleton will only get initialized once.
    Am i missing something here ? or did i implement it wrong..?
    public class Test
       private static Test ref ;
       private DataSource X; 
       static int Y;
       long Z ;  
       private Test ()
          // Singleton
           Z= 100 ;
       public static synchronized Test getinstance()  throws NamingException, SQLException
          if(ref == null)
             ref = new Test() ;        
             InitialContext ic = new InitialContext();
             ref.X = (DataSource)ic.lookup ("jdbc/Views");
          return ref ;       
       public Object clone()throws CloneNotSupportedException
           throw new CloneNotSupportedException();
       public int sampleMethod (int X) throws SQLException
    public final class Filter implements Filter
         public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException
              try
                   Test ref = Test.getinstance();
                   log.logNow(ref.toString());
    }Edited by: Tom on Dec 8, 2010 2:45 PM
    Edited by: Tom on Dec 8, 2010 2:46 PM

    Tom wrote:
    Hi ,
    I tried implementing a singleton class , and then invoking the same in a filter class.
    Both are then deployed as a web app (war file) in a managed server.
    I created a similar app , deployed the same as another app in the same managed server .
    I have a logger running which logs the singleton instances as well.
    But am getting two instances of the singleton class in the two apps - not the same .Two apps = two instances.
    Basically by definition.
    >
    I was under the impression that , a singleton is loaded in the class loader level , and since all apps under the same managed server used the same JVM , singleton will only get initialized once. A class is loaded by a class loader.
    Any class loader that loads a class, by definition loads the class.
    A VM can have many class loaders. And far as I know every JEE server in existance that anyone uses, uses class loaders.
    And finally there might be a problem with the architecture/design of a JEE system which has two applications but which is trying to solve it with a singleton. That suggests a there might be concept problem with understanding what an "app" is in the first place.

  • Instance methods faster than sync. static methods in threaded env?

    consider the following please:
    (-) i have "lots" of instances of a single Runnable class running concurrently..
    (-) each instance uses a common method: "exponential smoothing" and they do a lot of smoothing.
    so:
    (option #1): include a "smooth()" instance method in the Runnable class.
    (option #2): include a "smooth()" synchronized static method in the Runnable class.
    (option #3): create a MathUtility class, and have "smooth()" as an instance method in this class.
    (option #4): make "smooth()" a synchronized static method in the MathUtility class.
    from OOP point of view, i think i should externalize "smooth()" to a MathUtility class, and then make
    is "synchronized static".
    but then from a performance point of view....
    would not it be optimal to make "smooth()" an instance method in MathUtility and then have each
    instance of the Runnable create its own MathUtility instance so that each thread has its own copy
    of the "smooth()" method??
    well, i can't image there would be a measurable difference so maybe i should not post.
    but, if there is a flaw in my thinking, please let me know.
    thanks.

    kogose wrote:
    from OOP point of view, i think i should externalize "smooth()" to a MathUtility class, and then make
    is "synchronized static".From an OOP point of view you should probably have a class that represents the data that provides a (non-static) smooth() method that either modifies the data or returns a new smoothed data object (depending on whether you want your data objects to be immutable or not).
    but then from a performance point of view....
    would not it be optimal to make "smooth()" an instance method in MathUtility and then have each
    instance of the Runnable create its own MathUtility instance so that each thread has its own copy
    of the "smooth()" method??No, methods are not "copied" for each instance. That just doesn't happen.
    well, i can't image there would be a measurable difference so maybe i should not post.If you don't know, then you should probably try it.
    but, if there is a flaw in my thinking, please let me know.The flaw in your thinking is that you can think that you can intuitively grasp the difference in performance of a change at that level.
    I have yet to meet anyone who can reliably do that.
    Performance optimization is not an intuitive task at that level and you should never do performance optimizations without proving that they are improvements for your particular use case.
    First part: Is the smooth() method really thread-unsafe? Does it use some shared state? My guess would be that it uses only local state and therefore doesn't need any synchronization at all. That would also be the fastest alternative, most likely.

  • Concerns about Singleton classes in EAR archive

    Let's say I have an EAR file with the following structure:
    employee.jar<br>
    employeeSearchEJB.jar<br>
    webApp1.war<br>
    webApp2.war<br>
    META-INF<br>
    application.xml<br>
    If there is a singleton class in the employee.jar utility archive, then does there
    exist a single instance of that singleton class for each web application in
    the EAR? I hope not because that would seriously screw things up with me. I would
    be upset, to say the least.
    SAF

    I tested it out, and you're right, only 1 instance of the singleton exists at the
    EAR level.
    Thanks,
    SAF
    "mike iwaskow" <[email protected]> wrote:
    >
    If there is a singleton class in the employee.jar utility
    archive, then does there exist a single instance of that
    singleton class for each web application in
    the EAR ?
    Based on your scenario, I believe the answer is "No".
    I'm knowledgeable with WLS 5.1 and up, not 4.51.
    Your best bet is to give it a try. If a problem does occur,
    contact BEA support at [email protected]
    Developer Relations
    BEA Support

  • Cannot access instance method

    I want to get a Vector obj result (inside my JSP page) by accessing an instance method of a class I've put in a package and I keep getting a java.lang.NullPointerException.
    The skeleton of the class in the package is:
    MyClass.java
    package myPackage;
    import java.util.*;
    public class myClass {
    String string_A;
    String string_B;
    public myClass(String s_A, String s_B) {
    string_A = s_A;
    string_B = s_B;
    public Vector getVector() {
    Vector myVector = new Vector();
    myVector.add(string_A);
    myVector.add(string_B);
    return myVector;
    ... and the JSP that goes the wrong way is:
    Page.jsp
    <%@ page contentType="text/html;charset=WINDOWS-1253"%>
    <%-- The following String comes from HTTP POST--%>
    <% String request_A = request.getParameter("foo"); %>
    <% String request_B = request.getParameter("bar"); %>
    <html><body><p>
    <% try {
    myPackage.myClass myClassObj =
    new myPackage.myClass(request_A, request_B);
    try {
    Vector v = myClassObj.getVector();
    } catch (Exception e) {
    out.println("Cannot access Obj Method: " + e); (*)
    } catch (Exception e) {
    out.println("Cannot Initialize Obj: " + e);
    %>
    </p></body></html>
    When I run the above JSP page I get:
    "Cannot access obj method : java.lang.NullPointerException" (*)
    Why can't I access this method?!?

    it doesn't matter whether they are in same package or different packages as long as we can resolve the scope properly . Here I assum e that Prog1.java is top level container which is holding the instacnes of prog2 and prog3 . now some action of prog2 should invoke some method on prog3 . Here prog2 doesn't know the existence of prog3 as two are independent and only thing thats linking both of them is Prog1.So its staright forward that any such communication should happen through Prog1. While instantiating Porg2 set the reference of Prog1 in prog2 . soemthing like Prog2 p2 = new Prog2(); p.setTop(this);
    Ofcourse this involves code change in Porg2 . then from the listenere you can simply call method m3 in prog3 like p2.getTop().p3.m3(); hope this helps..

  • Singleton Class using a constructor not a get Instance method ?

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

    Pradeep ,
    You see a constructor does not return anything
    when you tell java
    String str = new String();
    It is into the reference str that a Object of the type String is assigned and used ..
    If you want a single instance to exist in your application ..the best way is to use the singelton approach.
    Alternatively you could create one static instance of the object in a parent class and all the classes that inherit from it will then share access .

  • 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

  • Question about synchronized singleton classes

    Hi,
    I have a singleton class, with only 1 method (which is static), I want access to that method to be synchronized, but someone suggested that I make my getInstance() method synchronized as well.
    Is this neccessary, or is it overkill?
    thanks!

    Example:
    static Instance getInstance() {
    if (instance == null) {
    instance = new Instance();
    return instance;
    }Two threads call it simultaneously:
    1. if (instance == null) { // evaluates true
    2. if (instance == null) { // evaluates true
    1. instance = new Instance(); // first instance
    2. instance = new Instance(); // second instance,
    deleting the reference to the first instance
    1. return instance; // which is not the originally
    created one but the second instance
    2. return instance;There's actually a worse consequence.
    1) T1 sees null
    2) T1 sets instance to point to where the object will live
    4) T2 sees non-null
    3) T2 returns, with a pointer to what's supposed to be an object, but isn't yet inited.
    4) T1 eventually inits the instance
    This can happen even if you use the "double check locking" pattern of synchronization.
    At least under the old memory model. I think the new JMM in effect in 5.0 (and possibly later 1.4) versions fixes it. I don't know if the fact that it can happen in absence of sync/DCL is an error or not, so I'm not sure if that's addressed in the new JMM, or if it's only the synced case that was a bug. (That is, it might be okay that it happens without syncing.)

  • 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 using a constructor not a getInstance method

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

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

  • Whats the difference between a class method and a instance method.

    I have a quiz pretty soon and one of the questions will be: "How does an instance method differ from a class method." I've tried looking this up but they gave me really complicated explanations. I know what a instance method is but not really sure what a class one is. Can someone post an example of a class method and try to explain what makes it so special?
    Edited by: tetris on Jan 30, 2008 10:45 PM

    Just have a look:
    http://forum.java.sun.com/thread.jspa?threadID=603042&messageID=3246191

Maybe you are looking for

  • Problem with a BAPI collecting dunning levels

    Hello all experts, I am having a problem with BAPI “DebtorCreditAccount” (called from a VB program), collecting dunning levels. The BAPIs is called like follows (only the essential code is shown): The first function (GetCustomerCurrentBalance) works

  • External Display won't go Fullscreen

    I have an Intel-based iMac running Snow Leopard with an external display connected. I want to display fullscreen video on the external display but I'm having problems. Specifically, here is what happens: Firstly, the displays are not mirrored - which

  • Required to change the Baseline Date in the MIRO Invocie Document

    Dear Friends, According to the Payment Terms, while doing the MIRO, the Baseline Date getting populated corresponds to the Document Date. However, the users need to replace the same with the GR Date. Is there a way to check for the GR date or the Del

  • Problem with eps transparency, Illustrator CS4

    Hi! I truly hope you can help me with this because I really can't find the answer myself. I need to save eps-versions of the files I make in the Illustrator. I have made a script (using Javascript) to get the right settings for eps automatically and

  • How do I download a new version of Mac OS X?

    I am trying to upgrade my iTunes, and am unable to because my Mac Book Pro is a version Mac OS X 10.5.8, and I am told I need Mac OS X version 10.6.8 or higher. How do I upgrade to this version?