Singleton
2 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Anonymous
Posted On:   Thursday, August 19, 2004 09:01 AM

When we use singleton pattern, at any point only one instance of the object is present.

The question is if I request this object from Service() method of a servlet & when multiuser tries to access, how is the object shared?

Is it one user then the next user? or how is that?

Can you please help me in getting clarity

Re: Singleton

Posted By:   Nilanjan_Sengupta  
Posted On:   Thursday, September 2, 2004 01:39 PM

If your object is a singleton, you will have only instance of that object. Normally you will define static methods in your singleton object. Various users of your system can have access to this single instance. The static methods will ensure that all accesses are thread safe. Whoever secures the lock, will have access to the object, the others will wait to obtain the lock and then access the method.

Re: Singleton

Posted By:   Balakris_Subramaniam  
Posted On:   Monday, August 23, 2004 07:41 AM

If you are planning to use a mutable Singleton in a multi-threaded environement (like within a JSP/J2EE application server) then you have to make sure it is thread-safe.

Explicit thread-safety constructs would have to be provided by you if the Singleton object is mutable. If the object is strictly read-only, then this step can be skipped.

There are a couple of ways you can make a (read/write) Singleton thread-safe:

  • Introduce a neutral mutex object instance in the Singleton class and synchronize access to it within the Singleton methods (i.e. protect critical sections).

  • Synchronize all the methods in the Singleton that modify the state of the object, consistently.

    When multiple threads (requests) accesses the Singleton, the above constructs ensure that the state of the object is consistent between subsequent accesses. The access sequence is determined by the request processing sequence of the server in a multi-threaded environment (mostly FIFO).

    As you can see, introducing explict thread-safety constructs are expensive. Typically, a Singleton object used for read-only access (for example to cache data, provide lookup values, storage for system variables set at startup, etc.) are the most optimal implementation of the Singleton pattern.

  • About | Sitemap | Contact