Quoting Warren Chen <[EMAIL PROTECTED]>:
> Hi Craig,
>
> Continue with the thread safe issue:
>
> how about Log class? I understand that log4j itself is
> thread safe (unlike DateFormat) - but I see a lot
> examples that log4j logs are used as instance varibale
>
> public final class MyAction
> {
> private Log log =
> LogFactory.getLog(this.getClass().getName());
> public ActionForward execute(.....)
> {.....}
> }
>
I tend to make my "log" variables static as well, but that doesn't change
whether it's threadsafe or not -- it just reduces the number of object
creations that happen if there's more than one instance of my class being
created.
> Is this thread safe?
>
If the commons-logging implementation classes for the wrapper are threadsafe
(and they are), and the underlying logging implementation claims to be
threadsafe (as do Log4J, JDK 1.4 logging, and the SimpleLog implementation --
don't know about the others) than this is indeed threadsafe.
> If yes, then even we use instance variable, as long as
> we access it thread-safe way (ie. sync it), it will be
> ok, right? (performance is another issue)
>
If an object is threadsafe, it should be unnecessary for you to synchronize at
all -- any required synchronzation must already be occurring inside. For
example, consider the difference between java.util.Hashtable (which advertises
itself as threadsafe) and java.util.HashMap (which explicitly states that it is
*not* threadsafe). The get() and put() calls never need to be synchronized in
the former case (even if you store the Hashtable in an instance variable of an
Action, because the class does its own synchronization internally. The
opposite is true if you create a HashMap and make it accessible from more than
one thread.
For example, note that you won't see any synchronization around calls like
log.debug() or log.trace() in the Struts code. Because the Log instance is
threadsafe, I don't need to worry about the fact that there might be two
simultaneous calls to log.debug() on different threads, processing different
requests.
In a similar vein, your servlet container guarantees that calls to
HttpSession.getAttribute() and HttpSession.setAttribute(), for example, are
thread safe ... in the sense that accessing attributes from more than one
thread will not corrupt the internal data structure that the servlet container
is using to keep track of attributes for you. You are still on the hook, of
course, to guarantee that the objects you store as attributes are thread safe,
but that's the application's issue, not the container's issue.
Does that help?
> Thanks a lot!
>
> Warren
Craig
---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]