ThreadSafeLazyLoading of a Singleton Object

Hi,
Do anyone know the mechanism and necessity of this ThreadSafe Lazy loading of a singleton object?
Thanks.

I know the mechanism (I believe Enum is the popular choice these days).
The necessity is dubious. Most people don't need lazy loading singletons, they just think it's a part of the Singleton pattern.

Similar Messages

  • SingleTon object of WebServices (Please be specific as required and not be generic)

     // Singleton Object of viewservice
    private ViewService WorkListView = null;
    ViewServiceObjectCreation viewstrWorkListView =  ViewServiceObjectCreation.GetObject();
    // Object Creation
    public  class ViewServiceObjectCreation
            private static ViewServiceObjectCreation singleTonObject=null;
            private static readonly object lockingObject = new object();
            private ViewServiceObjectCreation()
            public static ViewServiceObjectCreation GetObject()
                if(singleTonObject == null)
                     lock (lockingObject)
                          if(singleTonObject == null)
                               singleTonObject = new ViewServiceObjectCreation();
                return singleTonObject;
    But this is not creating singleton object of webservice. How to create singleton object of webservice.
    Vivek

    Read my post again: Please describe your concrete problem which made you think you need a singelton.
    A singelton only works per domain. Thus it will not help in your sketched scenario. Cause it cannot prevent an user or administrator for starting another domain (a.k.a. process).
    In this case you should consider using a mutex, which is aquired when the web service is started and released when stopped.
    While singeltons are a cool pattern per se, they are one of those evil ones. They are often not a correct solution and much worse, the kill testability cause the represent a global state.

  • Singleton object in clustered enviornment

    Hi,
              In my web application which is deployed in clustered enviornment, I am facing problem for singleton object.
              I need to share object among all servers in the clustered.
              I am using weblogic server 9.2. I have tried its Singleton services, but it doesnt work as expected.
              what could be other solution to solve the problem?

    No. If you need this type of functionality, use Coherence.
              http://www.tangosol.com/coherence.jsp
              Peace,
              Cameron Purdy
              Tangosol, Inc.
              http://www.tangosol.com/coherence.jsp
              Tangosol Coherence: Clustered Replicated Cache for Weblogic
              "Ferruccio" <[email protected]> wrote in message
              news:[email protected]..
              > Hi,
              > I have a very basic question. In a WebLogic clustered
              > environment, is a Singleton replicated? In other words, if the
              > mySingleton on node A in a cluster is updated with a piece of data,
              > will this show in the mySingleton in node B?
              >
              > Thanks
              >
              > Ciao
              > Ferruccio
              

  • Multiple instances of a Singleton-Object by updaterule ?

    Hi folks,
    I'm trying to load > 1 Mio. records from an ODS into another InfoProvider. Every record gets some keyfigures out of a very very expensive table-join.
    I tried creating this join in an ABAP-Singleton-Object to reduce uploading-time.
    This object holds a private-static attribute 'instance' as a reference to a instance of the object and a public-static 'getInstance()'-method, which returns the 'instance'-value. This method is standard-Singleton-like designed.
    Then I created a process-chain with:
    - an ABAP-process, which calls the 'getInstance()'-method
      of this Singleton.
      At the first pass this method calls the constructor and
      after that a private method, which creates the join and
      holds the result in an internal table.
      So the constructor is empty.
    - after that the data should be transfered (by an Info-
      Package) from the ODS to the other InfoProvider. In some
      fields of the update-rule and in the startroutine of
      the rule the 'getInstance()'-method of the Singleton is
      been called and by this reference to the only (so I
      thought) instance some other methods should return a
      calculated value out of the join.
    So theory .... the startroutine is been called for multiple datapackages (no problem) --- but for every package in the startroutine the 'getInstance()'-method calls the constructor, so I get multiple instances of a Singleton.
    The time-gap between the package-calls is > 10 secs., so the static-attribute should been set immediately in the first pass of the 'getInstance()', since the constructor is empty.
        Any ideas ???
        Bye Ralf

    -/-

  • Singleton Object With Anonymouse Methods

    I'm trying to create a singleton object using a GUI interface. The problem which I'm getting is that I can't find a way to create the object inside an .addActionListener() method while storing it for other .addActionListener() methods.
    CreditCard.java
       public class CreditCard {
           private static CreditCard uniqueInstance = null;
          final String creditCardNumber;
          String name;
          float creditLimit;
          float creditBalance;
           private CreditCard(String creditCardNumber,String name,float creditLimit) {
               this.creditCardNumber = creditCardNumber;
               this.name = name;
               this.creditLimit = creditLimit;
           public static CreditCard getInstance(String creditCardNumber,String name,float creditLimit)
               if (uniqueInstance == null)
                   uniqueInstance = new CreditCard (creditCardNumber, name, creditLimit);
               return uniqueInstance;
    Here's some code
    main class call
             CreditCard Student;
             JButton enterCardButton = new JButton("Edit Card");      
             enterCardButton.addActionListener(
                    new ActionListener() {
                       public void actionPerformed(ActionEvent ae) {
                         String cCNumber = creditCardNumberField.getText();
                         String cName = nameField.getText();
                         String cStringLimit = creditLimitField.getText();
                         float cLimit = Float.parseFloat(cStringLimit);
                         Student = CreditCard.getInstance(cCNumber, cName, cLimit);
             buttonPanel.add(enterCardButton);Of course the compiler error I get is that you must declare the CreditCard Student to be final. But if i make it final, I cannot create it in the method! I'm stuck :/

    You do need to call getInstance on a
    singleton. The compiler doesn't treat them specially.
    So, outside of the singleton itself you need
    something like
    String ccNumber =
    CreditCard.getInstance().getCreditCardNumber();(and it's probably best to define accessor methods
    for singleton fields).I actually do this for my other methods, thank you malcolmmc :). But the problem right now is the inablity to create the class using the ActionListener. I'm goign to Paste my whole code segment this time to try to provide a better picture.
    *          MAIN CLASS
    package Project2;
       import java.awt.BorderLayout;
       import java.awt.GridLayout;
       import java.awt.event.ActionEvent;
       import java.awt.event.ActionListener;
       import javax.swing.DefaultListModel;
       import javax.swing.JButton;
       import javax.swing.JFrame;
       import javax.swing.JLabel;
       import javax.swing.JList;
       import javax.swing.JPanel;
       import javax.swing.JScrollPane;
       import javax.swing.JTextField;
       import java.io.*;
       import java.lang.*;
       import java.util.*;
        public class Project2TestFrame {
          // public enum transactionType { LIMIT_CHANGE, CHARGE, PAYMENT}
           public static JFrame getTestFrame() {
             JFrame testFrame = new JFrame("Project 2 Tester");
          // Build the data portion of the frame
             final JTextField creditCardNumberField = new JTextField(15);
             final JTextField nameField = new JTextField(15);
             final JTextField creditLimitField = new JTextField(15);
             final JTextField chargeAmountField = new JTextField(15);
             JPanel dataPanel = new JPanel();
             dataPanel.setLayout(new GridLayout(4,2));
             dataPanel.add(new JLabel("Credit Card Number"));
             dataPanel.add(creditCardNumberField);
             dataPanel.add(new JLabel("Name"));
             dataPanel.add(nameField);
             dataPanel.add(new JLabel("Credit Limit"));
             dataPanel.add(creditLimitField);
             dataPanel.add(new JLabel("Charge Amount"));
             dataPanel.add(chargeAmountField);
             testFrame.add(dataPanel, BorderLayout.CENTER);
          // Add the buttons to the frame.  Note only the Exit button is
          // given here.  You should add other buttons.
             JPanel southPanel = new JPanel();
             southPanel.setLayout(new GridLayout(2,1));
             JPanel buttonPanel = new JPanel();
             southPanel.add(buttonPanel);
          // Add the messageField and
             String[] sarray = {"", "", "", "", ""};
             DefaultListModel dlm = new DefaultListModel();
             dlm.copyInto(sarray);
             final JList messageList = new JList(dlm);
             final JScrollPane jsp = new JScrollPane(messageList);
             southPanel.add(jsp);
             testFrame.add(southPanel, BorderLayout.SOUTH);
          // Add your buttons here.
             //Main Class Instance of CreditCard class.
             CreditCard Student;
             JButton enterCardButton = new JButton("Edit Card");
             enterCardButton.addActionListener(
                    new ActionListener() {
                       public void actionPerformed(ActionEvent ae) {
                         String cCNumber = creditCardNumberField.getText();
                         String cName = nameField.getText();
                         String cStringLimit = creditLimitField.getText();
                         float cLimit = Float.parseFloat(cStringLimit);
                         //***Compile Error** Needs to be final, but if final still complains
                         Student = CreditCard.getInstance(cCNumber, cName, cLimit);
             buttonPanel.add(enterCardButton);
             JButton chargeButton = new JButton("Charge Credit Card");
             chargeButton.addActionListener(
                    new ActionListener() {
                       public void actionPerformed(ActionEvent ae) {
                           String cStringCharge = chargeAmountField.getText();
                           float cAmount = Float.parseFloat(cStringCharge);
             buttonPanel.add(chargeButton);
             JButton paymentButton = new JButton("Payment");
             paymentButton.addActionListener(
                    new ActionListener() {
                       public void actionPerformed(ActionEvent ae) {
             buttonPanel.add(paymentButton);
             JButton dummyButton = new JButton("Transactions");
             buttonPanel.add(dummyButton);
             dummyButton.addActionListener(
                    new ActionListener() {
                       public void actionPerformed(ActionEvent ae) {
                         DefaultListModel messageData = (DefaultListModel)messageList.getModel();
                         messageData.clear();
                         messageData.addElement("String1");
                         messageData.addElement("String2");
                         messageData.addElement("String3");
             JButton exitButton = new JButton("Exit");
             buttonPanel.add(exitButton);
             exitButton.addActionListener(
                    new ActionListener() {
                       public void actionPerformed(ActionEvent ae) {
                         System.exit(0);
          // Finish and return data.
             return testFrame;
        * @param args
           public static void main(String[] args) {
             JFrame p2tf = getTestFrame();
             p2tf.pack();
             p2tf.setVisible(true);
        class Transaction {
          public enum transactionType { LIMIT_CHANGE, CHARGE, PAYMENT}
        //enum transactionType;
          int date;
          int amount;
           public Transaction(int date, int amount)
            //this.transactionType = transactionType;
             this.date = date;
             this.amount = amount;
    * CreditCard.java
    * Created on June 21, 2006, 9:27 AM
    * To change this template, choose Tools | Options and locate the template under
    * the Source Creation and Management node. Right-click the template and choose
    * Open. You can then make changes to the template in the Source Editor.
    package Project2;
       import java.io.*;
       import java.lang.*;
       import java.util.*;
       public class CreditCard {
           private static CreditCard uniqueInstance = null;
          final String creditCardNumber;
          String name;
          float creditLimit;
          float creditBalance;
          ArrayList<String> transactionHistory;
           private CreditCard(String creditCardNumber,String name,float creditLimit) {
               this.creditCardNumber = creditCardNumber;
               this.name = name;
               this.creditLimit = creditLimit;
           public static CreditCard getInstance(String creditCardNumber,String name,float creditLimit)
               if (uniqueInstance == null)
                   uniqueInstance = new CreditCard (creditCardNumber, name, creditLimit);
               return uniqueInstance;
           public void setName(String name)
             this.name = name;
           public String getName()
             return this.name;
           public String getCreditCardNumber()
             return this.creditCardNumber;
           public float getCreditLimit()
             return this.creditLimit;
           public void setCreditLimit(float creditLimit)
             this.creditLimit = creditLimit;
           public float getAvailableCredit()
             return this.creditBalance;
           public void addCharge(float chargeAmount)
            this.creditBalance -= chargeAmount;
           public void paymentReceived(float paymentAmount)
            this.creditBalance += paymentAmount;
        //public String[] getTransactions()
        //    return this.transactionHistory.toArray();
       class NumberOutOfBoundsException extends Exception {
        private int number;
        public NumberOutOfBoundsException() {
            number = 0;
        public NumberOutOfBoundsException(String Message) {
            super(Message);
        public NumberOutOfBoundsException(int number) {
            this.number = number;
        public NumberOutOfBoundsException(String Message, int number) {
            super(Message);
            this.number = number;
        public int getNumber() {
            return number;
    }

  • How to create more kinds of singleton objects?

    Hello,
    in my application I need to create more objects. Every object does during its creation same actions (they differ only in one parameter) and add some own methods.
    These all objects should behave as a singleton pattern.
    Could you help me (different design pattern) how to achieve this?
    Thank you.

    I have such slightly modified Multiton pattern class.
    Now I want create a method that returns database server IP address from database setting type - try to tell me (exactly) how to write this method.
    public class Setting {
         public enum Type {
              database, application, mail
         private static final Map<Object, Setting> instances = new HashMap<Object, Setting>();
         protected PropertiesFile file = null;
         private Setting(Setting.Type key) throws IOException {
              file = new PropertiesFile(key.toString() + ".properties");
         public static Setting getDatabase() throws IOException {
              return Setting.getInstance(Setting.Type.database);
         public static Setting getApplication() throws IOException {
              return Setting.getInstance(Setting.Type.application);
         public static Setting getMail() throws IOException {
              return Setting.getInstance(Setting.Type.mail);
         private static Setting getInstance(Setting.Type key) throws IOException {
              Setting instance = instances.get(key);
              if (instance == null) {
                   instance = new Setting(key);
                   instances.put(key, instance);
              return instance;
    }

  • How can we destroy the instance of a singleton object?

    I think by writing a method like getInstance and making null in that method will not the correct answer of this. Can someone tell me what should I do.

    why do you need to destroy the singleton?
    normally..it should live for the duration of the application.
    most singleton i've worked with are used by sevarals different classes.
    if you're singleton use by only one class...refactor your code to make the singleton an inner class. so the singleton will be destroy when that class is no longer references 9and gc kick in)
    if the singleton is share among several class...you can have a destroy method...like destroyInstance() where you null the singleton. keep in mind about synchronization of the method as well as the instance ... example createInstance() and destroyInstance() get call at the same time.. Also, make sure you have condition to check to determine if your singleton class is null or not
    example
    MySingleton s = MySingleton.createInstance();
    Object obj = s.getData(); // what happen when another thread call MySingleton.destroyInstance() you're s.getData would result in NullPointerException
    so..it's not wise to destroy a singleton.
    I think what is better for your app is an Object Pool that create new instance (if none exist) and hand it out to any requester...and recycle the object...or null it after use)

  • Light memory singleton object.

    Let's say you wanna build singleton but you want it to be kept in memory as long as someone is using it. This is possible if the instance static object is maintained via Soft or Weak reference. Here is how it is done:
    class MySingleton
      private static Object objLock = new Object();
      private static WeakReference instance = null;
       * Gets the instance of this class.
       * @return MySingleton
      public static MySingleton getInstance()
        synchronized (objLock)
          if (instance == null || instance.get() == null)
            instance = new WeakReference(new MySingleton());
        return (MySingleton)instance.get();
    }

    Once you create the instance of the Sibgleton the GC
    CANNOT clear it because of the static refernec to it.
    If you don't know that fact first read more. I do understand what you want to do. I have been programming in Java for 10 years and have never heard about a person who has needed what you are trying to do, and I don't think that it is a good idea.
    I can of course be 100% wrong on this since there are many different environments.
    With the
    weak or soft reference the GC can clear it anytime it
    goes or needs memory (depending whether is weak or
    soft). I know what weak a soft references do, but I don't understand why you want to use them. Your singleton will not be a singleton since instances will be created and destroyed. Creating your "heavy" object many times is worse than creating it one time.
    That's the usefulness. It isn't useful. It's a singleton which isn't a singleton, and it's only good for read only data.
    Let's say you have a
    module that operates with huge objects and that
    module is singleton. Once the application gets the
    singleton it's created and never destroyed until the
    app goes away. This way you ensure that this memory
    is released after you don't use the singleton. Haven't you considered that you might create that huge object many many times with your design?
    Kaj

  • Singleton Object

    Hi all,
    is it possible to create systemwide unique objects?
    I know of the singleton class, but I do not want to create a unique class instance,
    but I want to create some kind of factory class which gives unique objects.
    For instance I want to create delivery objects and I do not want multiple users
    to create the same delivery object (you can imagine why).
    How can I achieve this?
    Greetings Fred.

    What you are doing here is as you've found out is to try and get round the limits of  using OO in a " Classic Relational Database" system.
    When SAP starts using OBDBMS  (Object database system)  and can geuninely save objects as "persistent" in this type of database system then it probably can be done.
    However in the current SAP system  complex objects can only be built from data held in large numbers of different tables which may have a complex relationship  (by virtue of the RDBMS - relational data base system) so "Locking" this stuff system wide is not really (AFAIK) an option.
    A possibility is to use the JDO in JAVA where you can create genuine persistant objects which are held in a type of "OBDBMS" or Object data base management system as opposed to the traditional RDBMS (Relational model) that SAP uses.
    The JAVA JDO handles the actual SAP data base updates and maintains Data integrity between the JAVA object and the various SAP tables.
    Classic ABAP currently isn't really geared to handle this yet. OO Abap is a HUGE improvement but still essentially limited by use of the underlying RDBMS (relational data base system) and (internal) SQL queries to retrieve the data from various tables when "constructing" / instantiating your object.
    Graham's suggestion seems to be the nearest you can get to answering this problem.
    However if anybody does have an answer to this I'll also be interested so please post on this thread.

  • Synchronizing Creation of a Singleton Object

    I've encountered a synchronization issue I haven't seen covered in the material I've read so far. My server app uses message driven beans that maintain a variety of lookup tables (maps, actually), to do data validation. Each map is a singleton, and is created with lazy instantiation (i.e., not created until requested the first time). The problem is this: I want to prevent one thread from trying to read the map while another is creating it. Until the map is created, there's nothing to synchronize, but after it's created, there's no point in synchronizing either, because it will never change. The only time I need synchronization is during the one time the map is created. I don't want to synchronize later accesses to the map, for performance reasons. The code examples I've seen so far don't address this particular issue. Here's a code snippet of how I'm thinking of implementing this. Any comments or criticisms would be greatly appreciated.
    This code is from the the superclass of my data validation classes. The design is that a thread/bean needing map access would call getMapIfNeeded(), then do the lookup. The buildMap() method calls a separate, unsynchronized database class
    * Builds the lookup map if it doesn&rsquo;t already exist.
    * @param attribute Name of the attribute in table <span class="oracle">efm_accp_valu</span>.
    * @param map Map against which we&rsquo;ll validate values. If non-null, nothing is done.
    * @return The map (newly created if the input argument was <code>null</code>).
    * @throws APISystemException If a serious system error occurs.
    * @see #getListIfNeeded(String, List)
    protected static Map getMapIfNeeded(final String attribute, Map map)
       throws APISystemException
       if (map == null)
          map = buildMap(attribute);
       return map;
    * Builds the lookup map if it doesn&rsquo;t already exist.
    * @param attribute Name of the attribute in table <span class="oracle">efm_accp_valu</span>.
    * @param map Map against which we&rsquo;ll validate values. If non-null, nothing is done.
    * @return The map (newly created if the input argument was <code>null</code>).
    * @throws APISystemException If a serious system error occurs.
    * @see #getListIfNeeded(String, List)
    protected static synchronized Map buildMap(final String attribute)
       throws APISystemException
       return AcceptableValueDAO.getMap(attribute);
    {code}

    After doing some more research, I've concluded that, in my scenario at least, a better solution is to create the maps in static blocks. This avoids synchronization issues altogether, with the disadvantage being that if a database exception is thrown in the static block, I can't do much except print the stack trace. If anyone knows better, don't be shy about speaking up!

  • Can a object created using static keyword be recreated? Singleton Pattern

    Hi All
    To implement a Singleton I can use the following code
    public Singleton {
    private Singleton(){
    private static final s_instance = new Singleton();
    public Singleton getInstance(){
    return s_instance;
    Now if the Class Singleton gets unloaded during a program execution and again get loaded won't s_instance be recreated? If my question is correct this would lead to be leading to a new Singleton class instance with all the original variables.
    Having answered the above question if I lazily initialize my Singleton using the following code won't the above problem still occur.
    public Singleton {
    private Singleton(){}
    private final volatile Singleton s_instance = null;
    public Singleton () {
    if(s_instance != null) {
    synchronized (s_instance) {
    s_instance = new Singleton();
    return s_instance;
    Having answered all the above questions what is the best way to write a Singleton?

    Would the class get unloaded even if the Singleton object has some valid/reachable references pointing to it?
    On a different note, will all the objects/instances of a class get destroyed if the class gets unloaded.That's the other way round, really: instances cannot be garbage-collected as long as they are strongly reachable (at least one reference pointing to them), and classes cannot be unloaded as long as such an instance exists.
    To support tschodt's point, see the JVM specifications: http://java.sun.com/docs/books/jvms/second_edition/html/Concepts.doc.html#32202
    *2.17.8 Unloading of Classes and Interfaces*
    A class or interface may be unloaded if and only if its class loader is unreachable. The bootstrap class loader is always reachable; as a result, system classes may never be unloaded.
    Will the same case (Custom ClassLoader getting unloaded) occur if I write the singleton using the code wherein we lazily initialize the Singleton (and actually create a Singleton instance rather than it being a Class/static variable).You should check the meaning of this vocabulary ("object", "instance", "reference"): http://download.oracle.com/javase/tutorial/java/javaOO/summaryclasses.html
    The difference between the lazy vs eager initializations is the time when an instance is created. Once it is created, it will not be garbage collected as long as it is reachable.
    Now I'm wondering, whether being referenced by a static attribute of a class guarantees being reachabe. I'm afraid not (see the JLS definition of reachable: http://java.sun.com/docs/books/jls/third_edition/html/execution.html#44762). That is, again, unless the class has been loaded by the system class loader.

  • Object Singleton Thread question

    Thanks for taking a second to read this. Please consider the following.
    class Single{
      private static Single instance;
      private Single(){}
      public Single getInstance(){
        if(instance == null) instance = new Single();
        return Single;
      public static kill(){
        instance = null;
    class Watch{
      public DO_IT(){
        Single S = Single.getInstance();
        // Sys out here says
        // Single.instance is live as is S
        Single.kill();
        // Sys out here says
        // Single.instance is null
        // BUT S is not null
    }Can someone tell my why this happens (see comments if you missed it).
    Thanks

    I'm sorry and don't mean to be dense but in teh case
    of a singleton object, multiple callers to
    getInstance() are insured to get the same object
    right? No, they get copies of references to the same object
    caller1s_instance   ---+
                           |
                           |
                        +-----------+
    caller2s_instance---| singleton |
                        +-----------+
    If caller A calls a method on their version of
    instancee the change will show up in caller B's
    version right? Yes, because the references both point to the same object, and that object's methods may change its internal state, and both refs would see that.
    So why does something nulling the
    object not make it go away?Becuase you don't "null the object." You set the reference to null. Setting one reference to null does not affect the object that referenc refers to, and does not affect other references to that object. Simliarly having caller1 set its instance to new Singleton() (thus violoating the singleton pattern, but that's not the issue here), you'd have two Singleton objects, and changing caller1 to point to the new one wouldn't affect the original object or caller1's reference.
    caller1s_instance---null
                        +-----------+
    caller2s_instance---| singleton |
                        +-----------+
    Instance is RescU.RescU_Main@92d342
    MyVersion is RescU.RescU_Main@92d342
    After calling kill() they are
    Instance is null
    MyVersion is RescU.RescU_Main@92d342I hope the above explains this. If not let me know.

  • How to make Singleton Class secure

    I have a Singleton class which I instantiate using reflection by a call to a public getInstance method that return the object from a private constructor. I have to use reflection as I dont have any other options since my class instantiation is decided on runtime. How will I secure other form instantiating the same class again by using reflection on my private constructor? Any ideas?

    How much do these different implementations of your singleton have in common? What I'm getting at is, is there some common code you could extract out of them all, and make that a singleton in it's own right? Needing to do this sort of hacking is often a sign you're fudging something together, that could be solved more elegantly. We use the Singleton pattern generally when the state of the object needs to exist exactly once. Can you extract that from the disparate objects?
    The singleton classes that I load do not have anything in common. They are all similar but unique, and independant in their own respect. I will have to decide only on what singleton object I have to load in runtime, based on certain criterion. This is done by reflection, by a call to the public getInstance() method of the respective singleton classes, since I am deciding on runtime. My problem is that can I prevent others from accessing my private constructor from outside the class using reflection, which enables them to create another duplicate object. Can I restrict them to use only my getInstance() method instead?? I know this is hacking to access the private members, but I want to know whether there is any way where I can restrict this hacking???In the above code I dont want these statements to work at any case
    java.lang.reflect.Constructor[] c = cl.getDeclaredConstructors();
    c[0].setAccessible(true);
    A anotherA  = (A) c[0].newInstance(new Object[]{"Duplicate"});

  • How to create object per thread

    Hi everyone,
    This is my problem. I want to have a static method. Inside of it I want to add an element into a List, let's say I want to track something by doing this. But I also want this List to have multiple copies depending on threads, which means for every call to this static method, I want to call the "add" method on different List objects depending which thread it is from.
    Does it make sense? Do I need to have a thread pool to keep those thread references or something?
    How about I use Thread.currentThread() to determine whether this call is from a different thread so that I create another List?
    Thank you very much!
    Edited by: feiya200 on Feb 26, 2008 10:31 PM

    want to be perfect with singleton as why it is needed and how it works so see this by [email protected], Bijnor
    For those who haven't heard of design patterns before, or who are familiar with the term but not its meaning, a design pattern is a template for software development. The purpose of the template is to define a particular behavior or technique that can be used as a building block for the construction of software - to solve universal problems that commonly face developers. Think of design code as a way of passing on some nifty piece of advice, just like your mother used to give. "Never wear your socks for more than one day" might be an old family adage, passed down from generation to generation. It's common sense solutions that are passed on to others. Consider a design pattern as a useful piece of advice for designing software.
    Design patterns out of the way, let's look at the singleton. By now, you're probably wondering what a singleton is - isn't jargon terrible? A singleton is an object that cannot be instantiated. At first, that might seem counterintuitive - after all, we need an instance of an object before we can use it. Well yes a singleton can be created, but it can't be instantiated by developers - meaning that the singleton class has control over how it is created. The restriction on the singleton is that there can be only one instance of a singleton created by the Java Virtual Machine (JVM) - by prevent direct instantiation we can ensure that developers don't create a second copy.
    So why would this be useful? Often in designing a system, we want to control how an object is used, and prevent others (ourselves included) from making copies of it or creating new instances. For example, a central configuration object that stores setup information should have one and one only instance - a global copy accessible from any part of the application, including any threads that are running. Creating a new configuration object and using it would be fairly useless, as other parts of the application might be looking at the old configuration object, and changes to application settings wouldn't always be acted upon. I'm sure you can think of a other situations where a singleton would be useful - perhaps you've even used one before without giving it a name. It's a common enough design criteria (not used everyday, but you'll come across it from time to time). The singleton pattern can be applied in any language, but since we're all Java programmers here (if you're not, shame!) let's look at how to implement the pattern using Java.
    Preventing direct instantiation
    We all know how objects are instantiated right? Maybe not everyone? Let's go through a quick refresher.
    Objects are instantiated by using the new keyword. The new keyword allows you to create a new instance of an object, and to specify parameters to the class's constructor. You can specify no parameters, in which case the blank constructor (also known as the default constructor) is invoked. Constructors can have access modifiers, like public and private, which allow you to control which classes have access to a constructor. So to prevent direct instantiation, we create a private default constructor, so that other classes can't create a new instance.
    We'll start with the class definition, for a SingletonObject class. Next, we provide a default constructor that is marked as private. No actual code needs to be written, but you're free to add some initialization code if you'd like.
    public class SingletonObject
         private SingletonObject()
              // no code req'd
    So far so good. But unless we add some further code, there'll be absolutely no way to use the class. We want to prevent direct instantiation, but we still need to allow a way to get a reference to an instance of the singleton object.
    Getting an instance of the singleton
    We need to provide an accessor method, that returns an instance of the SingletonObject class but doesn't allow more than one copy to be accessed. We can manually instantiate an object, but we need to keep a reference to the singleton so that subsequent calls to the accessor method can return the singleton (rather than creating a new one). To do this, provide a public static method called getSingletonObject(), and store a copy of the singleton in a private member variable.
    public class SingletonObject
    private SingletonObject()
    // no code req'd
    public static SingletonObject getSingletonObject()
    if (ref == null)
    // it's ok, we can call this constructor
    ref = new SingletonObject();
    return ref;
    private static SingletonObject ref;
    So far, so good. When first called, the getSingletonObject() method creates a singleton instance, assigns it to a member variable, and returns the singleton. Subsequent calls will return the same singleton, and all is well with the world. You could extend the functionality of the singleton object by adding new methods, to perform the types of tasks your singleton needs. So the singleton is done, right? Well almost.....
    Preventing thread problems with your singleton
    We need to make sure that threads calling the getSingletonObject() method don't cause problems, so it's advisable to mark the method as synchronized. This prevents two threads from calling the getSingletonObject() method at the same time. If one thread entered the method just after the other, you could end up calling the SingletonObject constructor twice and returning different values. To change the method, just add the synchronized keyword as follows to the method declaration :-
    public static synchronized
         SingletonObject getSingletonObject()
    Are we finished yet?
    There, finished. A singleton object that guarantees one instance of the class, and never more than one. Right? Well.... not quite. Where there's a will, there's a way - it is still possible to evade all our defensive programming and create more than one instance of the singleton class defined above. Here's where most articles on singletons fall down, because they forget about cloning. Examine the following code snippet, which clones a singleton object.
    public class Clone
         public static void main(String args[])
         throws Exception
         // Get a singleton
         SingletonObject obj =
         SingletonObject.getSingletonObject();
         // Buahahaha. Let's clone the object
         SingletonObject clone =
              (SingletonObject) obj.clone();
    Okay, we're cheating a little here. There isn't a clone() method defined in SingletonObject, but there is in the java.lang.Object class which it is inherited from. By default, the clone() method is marked as protected, but if your SingletonObject extends another class that does support cloning, it is possible to violate the design principles of the singleton. So, to be absolutely positively 100% certain that a singleton really is a singleton, we must add a clone() method of our own, and throw a CloneNotSupportedException if anyone dares try!
    Here's the final source code for a SingletonObject, which you can use as a template for your own singletons.
    public class SingletonObject
    private SingletonObject()
    // no code req'd
    public static SingletonObject getSingletonObject()
    if (ref == null)
    // it's ok, we can call this constructor
    ref = new SingletonObject();          
    return ref;
    public Object clone()
         throws CloneNotSupportedException
    throw new CloneNotSupportedException();
    // that'll teach 'em
    private static SingletonObject ref;
    Summary
    A singleton is an class that can be instantiated once, and only once. This is a fairly unique property, but useful in a wide range of object designs. Creating an implementation of the singleton pattern is fairly straightforward - simple block off access to all constructors, provide a static method for getting an instance of the singleton, and prevent cloning.
    What is a singleton class?
    A: A class whose number of instances that can be instantiated is limited to one is called a singleton class. Thus, at any given time only one instance can exist, no more.
    Q: Can you give me an example, where it is used?
    A: The singleton design pattern is used whenever the design requires only one instance of a class. Some examples:
    �     Application classes. There should only be one application class. (Note: Please bear in mind, MFC class 'CWinApp' is not implemented as a singleton class)
    �     Logger classes. For logging purposes of an application there is usually one logger instance required.
    Q: How could a singleton class be implemented?
    A: There are several ways of creating a singleton class. The most simple approach is shown below:
    Code:
    class CMySingleton
    public:
    static CMySingleton& Instance()
    static CMySingleton singleton;
    return singleton;
    // Other non-static member functions
    private:
    CMySingleton() {}; // Private constructor
    CMySingleton(const CMySingleton&); // Prevent copy-construction
    CMySingleton& operator=(const CMySingleton&); // Prevent assignment
    Can I extend the singleton pattern to allow more than one instance?
    A: The general purpose of the singleton design pattern is to limit the number of instances of a class to only one. However, the pattern can be extended by many ways to actually control the number of instances allowed. One way is shown below...
    class CMyClass
    private:
    CMyClass() {} // Private Constructor
    static int nCount; // Current number of instances
    static int nMaxInstance; // Maximum number of instances
    public:
    ~CMyClass(); // Public Destructor
    static CMyClass* CreateInstance(); // Construct Indirectly
    //Add whatever members you want
    };

  • 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

Maybe you are looking for

  • Port number on which SAP receives data from extrernal systems

    Hi, We have an external application which sends/receives data to/from SAP. I am trying to figure out the port on which SAP server getting/sending  data. Every time on SAP server side, the port opened is sapgw01( sapgw<system number>). Can anyone tell

  • Is authurizing a computer the same as icloud?

    i got music from another laptop, and i wanted to transfer the music on to my laptop. but itunes asked i could authorize the other laptop. What does this mean? and if i do will all there songs automactically download on to my laptop?

  • ICloud for Windows won't install

    When trying to install iCloud for Windows I get the error: "The installer encountered errors before iCloud Control panel could be configured.  Your system has not been modified.  To try these operations at a later time, please run the installer again

  • Outgoing e-mail

    LOVE my iPhone, but it has an annoying problem. I just identified what is happening, but have no idea WHY its happening or how to stop it. When I sync my phone, the OUTGOING mail settings either erase or change. To fix the problem, I have to unplug t

  • Can universe be exported to xml?

    Hi, The latest version BOEXI v3.1 can export an universe to DB2 Cube views at "Metadata Exchange", do you know if there's any way to export an universe to xml?  If not, is there any roadmap to enhance?  Thanks. Regards, Gloria