[英]Static Synchronized Method to Access Static Field
嗨,我有一個實用工具課程。 它是一個包含所有靜態輔助方法的輔助類。 此類中有一個靜態字段。
該類永遠不會被實例化。 它僅通過靜態方法用作幫助程序。
即使這個類永遠不會被實例化,我仍然認為為了線程安全,靜態方法應該在訪問靜態字段時同步。 我對么?
public class Utils
{
private static Map<String, String> messagesMap;
public static synchronized String getMessage(String key)
{
if(messageMap == null) {
messageMap = new HashMap<String, String>();
messageMap.put("john", "hello");
messageMap.put("mary", "hi");
// actual population of this map comes from a property file.
}
return messageMap(key);
}
}
我真的建議你在聲明時初始化靜態字段(如果它是常量則將其標記為final
)並從方法中刪除同步。 就像是
private static final String message = "Hello"; // <-- needs a semi-colon.
public static String getMessage() {
return message;
}
請記住,Java String
是不可變的。
對於Map
我建議您使用static
初始化塊(並刪除同步並一致地命名變量)。 喜歡,
private static Map<String, String> messageMap = new HashMap<>();
static {
messageMap = new HashMap<String, String>();
messageMap.put("john", "hello");
messageMap.put("mary", "hi");
// actual population of this map comes from a property file.
}
public static String getMessage(String key) {
return messageMap.get(key);
}
如果您想允許從多個線程訪問和修改靜態共享狀態,那么您應該使用某種類型的同步。 使用synchronized關鍵字是一種方法。
如果您確實希望不應該實例化它,請在您的類中添加一個私有構造函數。
現在,如果數據字段僅用於參考目的而且永遠不會被更改,那么您只需將它們標記為final,而String將執行其余的操作,因為它是不可變的
否則,您需要同步方法或代碼塊,只需確保在訪問和修改時使用相同的鎖同時進行同步。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.