Is the Java MessageFormat Class thread safe? (as opposed to SimpleDateFormat)
Asked Answered
S

3

11

I know that SimpleDateFormat and NumberFormat are NOT thread safe.
https://bugs.java.com/bugdatabase/view_bug?bug_id=4101500

But what about the other Format classes like MessageFormat?

Fortify 360 is flagging the use of "MessageFormat.format(String, Object...)" static method as a "Race Condition - Format Flaw" issue, but when I analyze the the source code of MessageFormat, I saw that in that method, it creates a new local instance of MessageFormat itself.

Is the Java MessageFormat Class thread safe?

Stative answered 15/7, 2010 at 15:24 Comment(0)
S
12

The javadoc for MessageFormat says:

Message formats are not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally.

So officially, no - it's not thread-safe.

The docs for SimpleDateFormat say much the same thing.

Now, the docs may just be being conservative, and in practice it'll work just fine in multiple threads, but it's not worth the risk.

Shingly answered 15/7, 2010 at 15:28 Comment(2)
Thanks for showing the JavaDoc, that would be enough for me. When I viewed the source code of MessageFormat, it's even clearer to me why it's not thread safe. That class makes use of NumberFormat and DateFormat, two classes that are Not thread safe.Stative
It is not! Check this documentation where it talks about "Synchronization" docs.oracle.com/en/java/javase/11/docs/api/java.base/java/text/… Following is from this link: "Message formats are not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally."Inurbane
E
9

If you are referrring to the method

public static String format(String pattern, Object... arguments)

this is thread-safe since as described in the javadoc it creates a new MessageFormat to do the formatting.

BTW, thats a funny typo in your title 'SimpleThreadFormat' :)

Equestrienne answered 15/7, 2010 at 15:48 Comment(1)
What do you think about this question ? #75875034Lightner
B
1

Per the javadoc, MessageFormat objects are not thread-safe. You can use a ThreadLocal to create a separate object for each thread that needs one.

ThreadLocal<MessageFormat> threadLocalMessageFormat =
    new ThreadLocal<MessageFormat>() {
        @Override
        protected MessageFormat initialValue() {
            return new MessageFormat(pattern);
        }
    };

You can then use threadLocalMessageFormat.get() to obtain a MessageFormat for the current thread.

Biparous answered 7/3, 2018 at 22:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.