简体   繁体   English

为什么有人需要线程安全的SimpleDateFormat对象?

[英]Why would anyone need a thread safe SimpleDateFormat object?

I was looking for the usage of ThreadLocal and landed on this popular page When and how should I use a ThreadLocal variable? 我正在寻找ThreadLocal的用法并登陆这个热门页面何时以及如何使用ThreadLocal变量?

The accepted, highest voted answer says 被接受的,最高投票的答案说

One possible (and common) use is when you have some object that is not thread-safe, but you want to avoid synchronizing access to that object (I'm looking at you, SimpleDateFormat). 一种可能的(和常见的)用法是当你有一些不是线程安全的对象,但你想避免同步对该对象的访问(我正在看你,SimpleDateFormat)。

And the core part of the code is 而代码的核心部分是

 return new SimpleDateFormat("yyyyMMdd HHmm");

which won't change or be affected by conncurrent execution, or would it? 哪个不会改变或受到并发执行的影响,或者是吗?

Can you please highlight how this could be a issue? 你能否强调这可能是一个问题? And why would we need a thread safe object here? 为什么我们需要一个线程安全对象呢?

In other occurrence, I have come across a similar usage with java.security.MessageDigest; 在其他情况下,我遇到了与java.security.MessageDigest;类似的用法java.security.MessageDigest; , which is also a puzzler to me. ,这对我来说也是一个益智游戏。 It would be great if anyone could explain the reasons behind this, with some helpful code if possible. 如果有人能够解释这背后的原因,如果有可能的话,可以使用一些有用的代码。

SimpleDateFormat扩展了具有setter方法的DateFormat,因此一个线程可以更改SimpleDateFormat实例的属性,而其他线程可以使用它并假设更早的属性,或者更糟糕的是,在执行过程中更改属性会导致内部不一致的结果。

Well, take the first line in format(Date, StringBuffer, FieldDelegate) : 好吧,取format(Date, StringBuffer, FieldDelegate)的第一行format(Date, StringBuffer, FieldDelegate)

calendar.setTime(date);

calendar there is an instance member, so that's obviously not thread-safe there. calendar有一个实例成员,所以这显然不是线程安全的。 Firstly there's a date race (since setTime is not synchronized), but even more glaringly, someone could come through and set the calendar's time to something else part-way through the function ( calendar 's value is accessed in subFormat , which format calls). 首先是一个约会竞赛(因为setTime不同步),但更加明显的是,有人可以通过函数将日历的时间设置为其他部分( calendar的值在subFormat访问, format调用) 。

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

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