問題描述
我想為一些靜態方法使用日歷并使用靜態字段:
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
雖然很惡心.您可以只使用 一個 同步方法,該方法在每次需要時創建原始日歷的克隆,當然...可以通過調用 computeFields
或 computeTime
當然,您可以使 后續 讀取操作線程安全,但我個人不愿意嘗試它.
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.
這篇關于如何使靜態日歷線程安全的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!