Skip to content

java.text.SimpleDateFormat 线程安全问题 #36

Closed

Description

@xuyang2

java.text.SimpleDateFormat 内部是有状态的,并非线程安全。

SimpleDateFormat javadoc

Synchronization

Date 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.

org.apache.commons.lang3.time.FastDateFormat 才是线程安全的。

FastDateFormat javadoc

FastDateFormat is a fast and thread-safe version of SimpleDateFormat.
Since FastDateFormat is thread safe, you can use a static member instance:
private static final FastDateFormat DATE_FORMATTER = FastDateFormat.getDateTimeInstance(FastDateFormat.LONG, FastDateFormat.SHORT);
This class can be used as a direct replacement to SimpleDateFormat in most formatting and parsing situations. This class is especially useful in multi-threaded server environments. SimpleDateFormat is not thread-safe in any JDK version, nor will it be as Sun have closed the bug/RFE.

Activity

  1. binarywang commented on Sep 8, 2016

    @binarywang
    Owner

    没太明白,你发这个是想指出哪部分代码已经有潜在的问题了么?

  2. xuyang2 commented on Sep 8, 2016

    @xuyang2
    Author

    这里有线程安全问题:

    /**
     * 微信API的Service
     */
    public interface WxMpService {
    
      SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
    
  3. binarywang commented on Sep 8, 2016

    @binarywang
    Owner

    我仔细考虑下了,这个地方确实是可能有问题的,因为是静态共享的,所以才可能在多线程高并发环境下,使用其parse或format方法时有线程问题

  4. binarywang commented on Sep 9, 2016

    @binarywang
    Owner

    感谢提出这个问题,我们将彻查代码,修复可能有问题的地方

  5. binarywang commented on Sep 9, 2016

    @binarywang
    Owner

    已修复,代码提交到develop分支

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions