我知道SimpleDateFormat和NumberFormat不是线程安全的。
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4101500

但是像MessageFormat这样的其他格式类呢?

Fortify360正在标记使用"MessageFormat。格式(字符串,对象。..)"静态方法作为"竞争条件-格式缺陷"问题,但是当我分析MessageFormat的源代码时,我看到在该方法中,它创建了MessageFormat本身的新本地实例。

Java MessageFormat类线程安全吗?

有帮助吗?

解决方案

javadoc for MessageFormat说:

消息格式不同步。 建议创建单独的 每个线程的格式化实例。如果 多个线程访问格式 同时,它必须同步 外部。

如此正式,不 - 它不是线程安全的。

SimpleDateFormat的docs表示相同的事情。

现在,Docs May 只是保守,在实践中,它可以在多个线程中工作,但它不值得风险。

其他提示

如果要引用方法

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

这是线程安全,因为它在javadoc中描述,它创建了一个新的MessageFormat来执行格式。

btw,这是一个有趣的错字在你的标题'simpleethreadformat':)

根据javadoc, MessageFormat 对象不是线程安全的。您可以使用一个 ThreadLocal 为每个需要一个的线程创建一个单独的对象。

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

然后,您可以使用 threadLocalMessageFormat.get() 获得一个 MessageFormat 为当前线程。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top