問(wèn)題描述
我想為一些靜態(tài)方法使用日歷并使用靜態(tài)字段:
I'd like to use a Calendar for some static methods and use a static field:
private static Calendar calendar = Calendar.getInstance();
現(xiàn)在我讀到 java.util.Calendar 不是線程安全的.我怎樣才能使這個(gè)線程安全(它應(yīng)該是靜態(tài))?
Now I read java.util.Calendar isn't thread safe. How can I make this thread safe (it should be static)?
推薦答案
如果它不是線程安全的,你就不能做一些線程安全的東西.在 Calendar
的情況下,即使從它讀取數(shù)據(jù)也不是線程安全的,因?yàn)樗梢愿聝?nèi)部數(shù)據(jù)結(jié)構(gòu).
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:
- 大多數(shù)類型是不可變的
- 不可變類型是線程安全的
- 無(wú)論如何,它通常是一個(gè)更好的 API
如果您絕對(duì)必須使用 Calendar
,則可以創(chuàng)建一個(gè)鎖定對(duì)象并通過(guò)鎖定來(lái)進(jìn)行所有訪問(wèn).例如:
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
雖然很惡心.您可以只使用 一個(gè) 同步方法,該方法在每次需要時(shí)創(chuàng)建原始日歷的克隆,當(dāng)然...可以通過(guò)調(diào)用 computeFields
或 computeTime
當(dāng)然,您可以使 后續(xù) 讀取操作線程安全,但我個(gè)人不愿意嘗試它.
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.
這篇關(guān)于如何使靜態(tài)日歷線程安全的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!