-----------------------------
Please read the FAQ!
<http://java.apache.org/faq/>
-----------------------------
Joshua Slack wrote:
> -----------------------------
> Please read the FAQ!
> <http://java.apache.org/faq/>
> -----------------------------
>
> Thanks Jon, I believe you are right. How about this question instead: Is
> it possible to do a synchronization on a particular session object so that
> it sychronizes a block of code for a particular user only? I have tried
> something like:
>
> HttpSession session = req.getSession(true);
>
> synchronized (session) {
> ... code ...
> }
>
> And it causes every user to wait in line to use this code. Am I not
> understanding sychronization blocks perhaps?
>
> -- Joshua Slack
This would indeed lock that particular session, but you have to think about
are you locking it *from*? That session object is unique to a particular
user, because each user has their own session. It will only be accessed from
multiple threads simultaneously if the same user is making simultaneous
requests -- possible in a framed environment, but pretty unusual otherwise.
I always try to lock the minimum amount of stuff necessary to guarantee
correct operation. In your original scenario, it sounds like you might have
objects stored within the session that are being accessed by more than one
thread at a time. This can happen in the "multiple requests from the same
user" case mentioned above, but also if you are storing a reference to the
same object in more than one user's session. To lock here, you might think
about synchronizing on that particular object, which will only block other
threads that need access to the same object:
HttpSession session = req.getSession(true);
MyObject object = (MyObject) session.getValue("key");
synchronized (object) {
... code ...
}
Better yet, if possible, is to hide any necessary synchronization inside the
MyObject (or whatever) class, so that callers don't have to worry about it.
For example, the methods of a java.util.Hashtable that modify it (get, put,
remove) are synchronized, so you don't have to worry about simultaneous
accesses corrupting the structure of the hash table. However, you pay the
performance cost of locking on every call if you do it this way, even if you
know that the object is accessed in a thread safe manner.
Just an FYI note -- Apache JServ uses a Hashtable inside the session
implementation object to store user values, so it already benefits from this
built-in synchronization protection to ensure that its own data structure will
never be corrupted.
Craig McClanahan
--
--------------------------------------------------------------
Please read the FAQ! <http://java.apache.org/faq/>
To subscribe: [EMAIL PROTECTED]
To unsubscribe: [EMAIL PROTECTED]
Archives and Other: <http://java.apache.org/main/mail.html>
Problems?: [EMAIL PROTECTED]