Discussions

EJB programming & troubleshooting: Singleton class

  1. Singleton class (3 messages)

    How often should i use singleton class in distributed design. WHat are its advts and dis-advts ??

    Pranav

    Threaded Messages (3)

  2. Singleton class[ Go to top ]

    The answer is, it depends :-)

    What is your singleton going to do with the singleton?

    Distributed systems should, IMHO, should avoid singletons that:

    ** Hold State
    ** Act as a "security guard" to protect certain resources

    A singleton is guaranteed only to be unique in a given VM. For example, if a developer designed a distributed system that was deployed to a cluster of app servers, and in that system designed a singleton that would act as a "controller" to coordinate access to a shared file on a common drive, there is going to be problems. This is a **bad** design. The singleton could potentially exist N times across the cluster, where N is the number of app servers in the cluster. This means that theoretically two or more clients could be simultaneously accessing the resource, and the singleton pattern fails. Why would there be multiple instances? Because each app server is running in its on VM, and when the singleton class is instantiated, only the VM of that app server is going to be inspected; the other app server VMs will not.

    HTH

    Jason Weiss
    Internet Applications Division
    Sybase, Inc.
  3. Singleton class[ Go to top ]

    Hi,
    so whats the solution to overcome this dis advantage.
  4. Singleton class[ Go to top ]

    Understanding the issues is the solution, since there really isn't any way to overcome the issues I pointed out per se.

    It is more about being educated on the fact that singletons _may_ not be singletons at all, and that fact may be the cause of the problem you've been dubugging for 3 days now.

    When you talk about distributed computing and application servers, singletons simply aren't the best pattern to play around with IMHO.

    In those situations where you feel there is _no_ other approach, take a long, hard look at your environment, and understand what the immplications are. Do you know how the class loaders work in your application server? What kind of creational pattern are you using in the application? What if you your factory was designed to only create one instance, but your app server actually had two factories running from different class loaders?