如何使一个静态日历线程安全 [英] How to make a static Calendar thread safe
问题描述
我想对某些静态方法使用日历,并使用静态字段:
私人静态日历calendar = Calendar.getInstance();
现在我读了java.util.Calendar不是线程安全的。如何使此线程安全(应为静态)?
使事情线程安全,如果不是。在 Calendar
的情况下,甚至从其读取数据不是线程安全的,因为它可以更新内部数据结构。
如果可能的话,建议您使用 Joda Time 代替:
- 大多数类型都是不可变的
$ b 如果你绝对有使用
日历
,您可以创建一个锁定对象,并通过锁定所有的访问。例如: private static final Calendar calendar = Calendar.getInstance();
private static final Object calendarLock = new Object();
public static int getYear()
{
synchronized(calendarLock)
{
return calendar.get(Calendar.YEAR);
}
}
//同上其他方法
这是非常讨厌的。您可以只使用一种同步方法,在每次需要时创建原始日历的克隆,当然...可能通过调用 I'd like to use a Calendar for some static methods and use a static field: Now I read java.util.Calendar isn't thread safe. How can I make this thread safe (it should be static)? You can't make something thread-safe if it isn't. In the case of If at all possible, I'd suggest using Joda Time instead: If you absolutely have to use a It's pretty nasty though. You could have just one synchronized method which created a clone of the original calendar each time it was needed, of course... it's possible that by calling 这篇关于如何使一个静态日历线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! computeFields
或 computeTime
,您可以使后续读取操作线程安全,当然,但我个人不喜欢尝试。 / p> private static Calendar calendar = Calendar.getInstance();
Calendar
, even reading data from it isn't thread-safe, as it can update internal data structures.
Calendar
, you could create a locking object and put all the access through a lock. For example:private static final Calendar calendar = Calendar.getInstance();
private static final Object calendarLock = new Object();
public static int getYear()
{
synchronized(calendarLock)
{
return calendar.get(Calendar.YEAR);
}
}
// Ditto for other methods
computeFields
or computeTime
you could make subsequent read-operations thread-safe, of course, but personally I'd be loathe to try it.