如何使静态日历线程安全

2023-02-10Java开发问题
6

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

问题描述

我想为一些静态方法使用日历并使用静态字段:

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

private static Calendar calendar = Calendar.getInstance();

现在我读到 java.util.Calendar 不是线程安全的.我怎样才能使这个线程安全(它应该是静态)?

Now I read java.util.Calendar isn't thread safe. How can I make this thread safe (it should be static)?

推荐答案

如果它不是线程安全的,你就不能做一些线程安全的东西.在 Calendar 的情况下,即使从它读取数据也不是线程安全的,因为它可以更新内部数据结构.

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.

如果可能的话,我建议改用 Joda Time:

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

  • 大多数类型是不可变的
  • 不可变类型是线程安全的
  • 无论如何,它通常是一个更好的 API

如果您绝对必须使用 Calendar,则可以创建一个锁定对象并通过锁定来进行所有访问.例如:

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

虽然很恶心.您可以只使用 一个 同步方法,该方法在每次需要时创建原始日历的克隆,当然...可以通过调用 computeFieldscomputeTime 当然,您可以使 后续 读取操作线程安全,但我个人不愿意尝试它.

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.

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

The End

相关推荐

如何使用 JAVA 向 COM PORT 发送数据?
How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)...
2024-08-25 Java开发问题
21

如何使报表页面方向更改为“rtl"?
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)...
2024-08-25 Java开发问题
19

在 Eclipse 项目中使用西里尔文 .properties 文件
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)...
2024-08-25 Java开发问题
18

有没有办法在 Java 中检测 RTL 语言?
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)...
2024-08-25 Java开发问题
11

如何在 Java 中从 DB 加载资源包消息?
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)...
2024-08-25 Java开发问题
13

如何更改 Java 中的默认语言环境设置以使其保持一致?
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)...
2024-08-25 Java开发问题
13