SimpleDateFormat的线程安全问题

今天用代码测试工具时,发现我的代码中存在这么一个问题,还不能忽略.

报错代码:

public static final SimpleDateFormat FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

工具的提示为:

Not all classes in the standard Java library were written to be thread-safe. Using them in a multi-threaded manner is highly likely to cause data problems or exceptions at runtime.

This rule raises an issue when an instance of Calendar, DateFormat, javax.xml.xpath.XPath, or javax.xml.validation.SchemaFactory is marked static.

Noncompliant Code Example

public class MyClass {
  static private SimpleDateFormat format = new SimpleDateFormat("HH-mm-ss");  // Noncompliant
  static private Calendar calendar = Calendar.getInstance();  // Noncompliant

Compliant Solution

public class MyClass {
  private SimpleDateFormat format = new SimpleDateFormat("HH-mm-ss");
  private Calendar calendar = Calendar.getInstance();

原因是SimpleDateFormat类是线程不安全的。这一点其实在JDK中也有提醒:

       JDK原始文档如下:
  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.

由于本次程序并发程度较高,且时间格式化的使用频率也高,所以不能像以往一样无视这种可能性了。于是可选择的解决方式有:

  • 用的时候new,用一次new一次  - - !
  • synchronized
  • ThreadLocal
  • 放弃SimpleDateFormat

最终我选择了放弃SimpleDateFormat,使用Apache里的FastDateFormat:

public static final FastDateFormat FORMAT=FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss");

搞定,不再报错了。

 

参考好文:http://www.cnblogs.com/peida/archive/2013/05/31/3070790.html

 

  • 20190605更新

java1.8提供了新的时间处理包java.time。可使用java.time.format.DateTimeFormatter格式化时间,如:

	/**
	 * 时间戳数字格式化成指定格式.
	 * 
	 * @param milliTimestamp 时间戳
	 * @param pattern        时间格式
	 * @return
	 */
	public static String format(long milliTimestamp, String pattern) {
		return DateTimeFormatter.ofPattern(pattern)
				.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(milliTimestamp), ZoneId.systemDefault()));
	}

 

转载于:https://my.oschina.net/woooooody/blog/1477120

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值