1 Reply Latest reply on Dec 4, 2007 7:18 AM by Shoeb Khan

    How to create singletons?

    Aid Networks Newbie

      We need to create singleton classes to cache database data. Using an EJB container we are not guaranteed that truly one object is being instantiated and shared. I have heard various answers to this, including some mysterious "well, it depends on the classloader..." answers. From what I have found online, the answer appears to have something to do with declaring the class final, or using @service, but I don't know if these are definitely the solution. How can we make a singleton that is definitely really a singleton?

        • 1. Re: How to create singletons?
          Shoeb Khan Newbie

          It is an interesting question. Following might be helpful

          Before creating an instance of the singleton class, check if it exists in the system.properties. If it doesn't, create the instance and put that instance into system.properties map.

          For ex:
          if (System.properties.get("Single")==null) {
          Singleton single = new Singleton();
          System.properties.put("single", single);

          Second approach could be this:

          Don't put the class in the classpath. Write your own classloader and specify the absolute location of the class. This way app server wouldn't be able to load the class automatically.

          Hope that helps