简体   繁体   English

Java MessageFormat类线程是否安全? (与SimpleDateFormat相对)

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

I know that SimpleDateFormat and NumberFormat are NOT thread safe. 我知道SimpleDateFormat和NumberFormat不是线程安全的。
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4101500 http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4101500

But what about the other Format classes like MessageFormat? 但是像MessageFormat这样的其他Format类呢?

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. Fortify 360将“MessageFormat.format(String,Object ...)”静态方法的使用标记为“Race Condition - Format Flaw”问题,但是当我分析MessageFormat的源代码时,我在那个方法中看到了,它创建一个MessageFormat本身的新本地实例。

Is the Java MessageFormat Class thread safe? Java MessageFormat类线程是否安全?

The javadoc for MessageFormat says: MessageFormatjavadoc说:

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. SimpleDateFormat的文档说的大致相同。

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. 现在,文档可能只是保守,在实践中它可以在多个线程中正常工作,但它不值得冒风险。

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. 这是线程安全的,因为在javadoc中描述它创建一个新的MessageFormat来进行格式化。

BTW, thats a funny typo in your title 'SimpleThreadFormat' :) 顺便说一句,这就是你的标题'SimpleThreadFormat'中有趣的错字:)

Per the javadoc, MessageFormat objects are not thread-safe. 根据javadoc, MessageFormat对象不是线程安全的。 You can use a ThreadLocal to create a separate object for each thread that needs one. 您可以使用ThreadLocal为每个需要一个的线程创建单独的对象。

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. 然后,您可以使用threadLocalMessageFormat.get()来获取当前线程的MessageFormat

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM