如何使一个静态日历线程安全 [英] How to make a static Calendar thread safe

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

问题描述

我想对某些静态方法使用日历,并使用静态字段:

 私人静态日历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);
}
}

//同上其他方法

这是非常讨厌的。您可以只使用一种同步方法,在每次需要时创建原始日历的克隆,当然...可能通过调用 computeFields computeTime ,您可以使后续读取操作线程安全,当然,但我个人不喜欢尝试。 / p>

I'd like to use a Calendar for some static methods and use a static field:

private static Calendar calendar = Calendar.getInstance();

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 Calendar, even reading data from it isn't thread-safe, as it can update internal data structures.

If at all possible, I'd suggest using Joda Time instead:

  • Most of the types are immutable
  • The immutable types are thread-safe
  • It's a generally much better API anyway

If you absolutely have to use a 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

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 computeFields or computeTime you could make subsequent read-operations thread-safe, of course, but personally I'd be loathe to try it.

这篇关于如何使一个静态日历线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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