Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I know that SimpleDateFormat and NumberFormat are NOT thread safe.
http://bugs.sun.com/bugdatabase/view_bug.do?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?

like image 734
thenonhacker Avatar asked Jul 15 '10 15:07

thenonhacker


People also ask

Is Java SimpleDateFormat thread-safe?

Java's SimpleDateFormat is not thread-safe, Use carefully in multi-threaded environments. SimpleDateFormat is used to format and parse dates in Java. You can create an instance of SimpleDateFormat with a date-time pattern like yyyy-MM-dd HH:mm:ss , and then use that instance to format and parse dates to/from string.

What does MessageFormat format do in Java?

MessageFormat provides a means to produce concatenated messages in a language-neutral way. Use this to construct messages displayed for end users. MessageFormat takes a set of objects, formats them, then inserts the formatted strings into the pattern at the appropriate places.

What does it mean that the library is not thread-safe and what is true about the Android library?

"Not thread safe" means its internal representation doesn't (properly) handle access from multiple threads. If only a single thread actually uses the library, thread safety isn't an issue.

What is thread-safe in Java?

A thread-safe class is a class that guarantees the internal state of the class as well as returned values from methods, are correct while invoked concurrently from multiple threads. The collection classes that are thread-safe in Java are Stack, Vector, Properties, Hashtable, etc.


2 Answers

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.

like image 179
skaffman Avatar answered Sep 23 '22 15:09

skaffman


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' :)

like image 37
Jörn Horstmann Avatar answered Sep 24 '22 15:09

Jörn Horstmann