You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@struts.apache.org by Nick Coleman <ni...@leanlogistics.com> on 2003/03/10 22:31:01 UTC

[Patch] MessageFormat usage in MessageResources.java

In profiling struts-el, I noticed a big lag in the standard taglib Resources
class in that it calls MessageFormat.format rather than caching preparsed
formats.   The initialization of a MessageFormat is easily 75% of the time
spend while the call to format() is only 25%.   I entered a bug about this
last week but have seen no response.

This is why I was happy to see that the struts' MessageResources class
utilizes a hashtable to cache the formats.   However, in studying this I was
wondering about high contention among many threads for the same format.
Would the lag actually increase if many threads had to wait for the same
format?  For example, if MessageFormat.format() took 32ms and reusing a
cached format took 8ms and 10 threads tried to use the same format
simultaneously, would this be slower since the 10th thread had to wait
10*8ms = 80ms.

Therefore, I proposed a simple pooling idea inside the hashtable and thought
you may be interested if improving performance.  It looked like the
following for the standard taglib Resources class.

    public static String getMessage(String name, Object[] a)
        throws MissingResourceException {

        // Retrieve pre-parsed format pool for message
        Stack formatPool = (Stack) formats.get(name);
        if (formatPool==null) {
            formatPool = new Stack();
            formats.put(name, formatPool);
        }

        // Retrieve format from pool or create a new one if pool
        // is empty
        MessageFormat messageFormat = null;
        try {
            messageFormat = (MessageFormat) formatPool.pop();
        }
        catch(EmptyStackException emptyx) {
            messageFormat = new MessageFormat(rb.getString(name));
        }

        // Generate formatted message
        String message = messageFormat.format(a);

        // Put parsed format back in pool for re-use by
        // another thread
        formatPool.push(messageFormat);

        return message;
    }


Note, the pooling was built upon the java Hashtable and Stack classes which
are thread save.  I have attached a diff patch for the MessageResources.java
file if you are interested.

-Nick