SimpleDateFormat的线程安全问题 [英] Thread safety issue with SimpleDateFormat

查看:130
本文介绍了SimpleDateFormat的线程安全问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从程序员测试中得到以下代码

I got the following piece of code from a programmers test

private String formatDate(Date date)
{
  String result = "";
  //….
  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
  result = sdf.format(date);
  //…
  return result;
}

包含多个线程一次使用该方法的附加信息。这有什么问题吗?

with the additional information that several threads are using the method at once. Are there any problems with this?

我的答案是不,它应该没问题(假设//部分没有其他内容)。

My answer is that no, it should be fine (assuming that nothing else is going on in the //... parts).

我的动机是没有使用全局或类数据结构。日期作为参数从每个胎面传递,并且在方法内部仅使用局部变量和本地对象。因此,每个线程将获取并使用它自己的SimpleDateFormat类的对象实例。

My motivation is that no global or class data structures are used. The date is passed from each tread as a parameter and inside the method only local variables and local objects are being used. Thus, each thread will get and use it's own object instance of the SimpleDateFormat class.

但是,这不是测试中的正确答案。 正确的答案是类SimpleDateFormat不是线程安全的,因此需要同步对该对象的访问。

However, this was not the "correct" answer in the test. The "correct" answer is that the class SimpleDateFormat isn't thread safe and that the access to that object therefore needs to be synchronized.

所以,我还是解决方案对吗?

So, am I or the solution correct?

推荐答案

你的答案是对的。 SimpleDateFormat不是线程安全的,但是每个方法调用都会创建一个自己的实例,所以这没关系。如果SimpleDateFormat是一个实例变量,那么这将不是线程安全的(如你所提到的)。

Your answer is correct. SimpleDateFormat isn't thread-safe that's true but each method call will create an own instance so this is ok. If the SimpleDateFormat were an instance variable this wouldn't be thread-safe (as you mentioned).

这篇关于SimpleDateFormat的线程安全问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆