Marc,
> -----Original Message-----
> From: A mailing list for discussion about Sun Microsystem's Java Servlet
> API Technology. [mailto:[EMAIL PROTECTED]]On Behalf Of Marc
> Krisjanous
> Sent: Friday, 24 November 2000 10:48
> To: [EMAIL PROTECTED]
> Subject: Singleton Instance in Multithreading (servlet) - can it work?
>
>
> Hi all,
> I believe my last email about the Singleton V.s static question requires a
> more clear explanation:
>
> I have a class that writes data to a shared resource within my web
> application. All components within the web application use this class to
> write data to the log file. The class uses the Singleton Instance design
> pattern.
>
> Question
> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> Is this good design? here are a set of steps that would happen (I have
> provided skeleton class defs below):
>
> 1. Request to servlet sent from web page.
>
> 2. The servlet calls the init method if first request. The init method
> loads the Servlets instance var with a call to the EventLogController's
> getInstance method.
>
> 3. The servlet then writes to the log file by calling the
> EventLogControllers sync writeToEventLog().
>
> 4. The servlet then creates an instance of another component.
>
> 5. The component also has an instance var that upon creation gets a handle
> on the EventLogController (same as the servlet).
>
> 6. The component then attempts to write to the log file using the same
> method call.
>
> Now... Is this approach thread safe?? Can it handle more than one post or
> get request at the same time??
No it's not thread safe unless you only write one line per call to your log
file.
The Java IO classes themselves seen to be thread safe at a low level,
for instance executions of a println from separate threads don't interfere
with each other, but anything at a higher level may. I've had two
simultaneous printStackTrace methods interleave the output to my log.
I'd recommend making your log methods synchronized.
As far as singletons go the big problem for me is that they are inflexible.
It ties your code to a particular class. What I have done is have a registry
of 'well known' objects. The registry itself is a singleton with a hashtable
of objects keyed on name and class or interface type. Users of the reigistry
can look up objects and also register new objects. For my log this allows
me to have different types of loggers depending upon the circumstances.
For instance I have a logger that prints to the console for use in
debugging.
[snip]
Hope this helps,
Rob Griffin
Quest Software
E-mail: [EMAIL PROTECTED]
Web site: http://www.quest.com
___________________________________________________________________________
To unsubscribe, send email to [EMAIL PROTECTED] and include in the body
of the message "signoff SERVLET-INTEREST".
Archives: http://archives.java.sun.com/archives/servlet-interest.html
Resources: http://java.sun.com/products/servlet/external-resources.html
LISTSERV Help: http://www.lsoft.com/manuals/user/user.html