tomcat-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Caldarale, Charles R" <>
Subject RE: replacement for useBean directive
Date Tue, 06 Jan 2009 18:46:26 GMT
> From: Jonathan Mast []
> Subject: Re: replacement for useBean directive
> do I really need synchronization at all?

Short answer: yes.

> Is synchronization really called for here, either
> around the getITEM() methods inside the beans or
> around the methods in BeanBag that return the
> bean?

Yes to both.  Your example getApple() shows use of some form of Map, most forms of which require
external synchronization.  Even if such Map objects implemented internal synchronization,
the logic that checks for the existence of the key then retrieves the corresponding value
requires that the state of the Map not change between the containsKey() and get() calls.

BTW, you're creating a ton of throw-away objects by doing String.valueOf(int) here; you may
be better off to keep appleID as a String or Integer throughout.  Also, you don't need the
containsKey() call, the get() will return null if the key isn't present.

synchronized Apple getApple(int appleID) {
    purgeIfTimeout(); //calls appleMap.clear() if we've timed out
    Apple a = (Apple)appleMap.get(String.valueOf(appleID));
    if (a != null) return a;
    a = FruitDB.getApple(appleID);
    if (a != null) appleMap.put(String.valueOf(appleID), a);
    return a;

Also, your appleMap should be declared as HashMap<String, Apple> or HashMap<Integer,
Apple> (or whatever Map type you're using) so you can get rid of the casting.

Your BeanBag class methods also need synchronization to close the window between testing a
field for null and then allocating an object for it.  Failure to do so runs the risk of two
threads both seeing the field as null, and both creating beans for the same item type.

 - Chuck

for use only by the intended recipient. If you received this in error, please contact the
sender and delete the e-mail and its attachments from all computers.

To unsubscribe, e-mail:
For additional commands, e-mail:

View raw message