English 中文(简体)
这是使用静态方法 使单吨地图线安全 的正确而高效的方法
原标题:Is this the correct and efficient way to make a singleton map thread safe in a static method

我想在地图初始化时只创建一次锁。 这是我要使用的代码 。

public static Map<String, String> getOrderStatusInstance() {
    if (orderStatusMap == null) {
        synchronized (Utility.class) {
            orderStatusMap = new HashMap<String, String>();

            orderStatusMap.put("Key1", "Value1");
            orderStatusMap.put("Key2", "Value2");
            orderStatusMap.put("Key3", "Value3");
            orderStatusMap.put("Key4", "Value4");
        }
    }

    return orderStatusMap;
}
最佳回答

不,这是一个坏主意 - 您正在返回一个可变的、非铁面安全地图。 您也正在< em> 尝试 < / em> 来执行双重检查的锁定, 但没有正确完成它 - 并且要纠正它比使用静态初始化要困难得多 。

我会创建一个不可改变的地图(使用“http://guava-librarys.googlecode.com>>Guava ,以换取偏好),

private static final ImmutableMap<String, String> STATUS_MAP = ImmutableMap.of(
    "Key1", "Value1",
    "Key2", "Value2",
    "Key3", "Value3",
    "Key4", "Value4");

public static ImmutableMap<String, String> getOrderStatusInstance() {
    return STATUS_MAP;
}

(关于5个以上的钥匙/价值配对,请使用immobleMap.Builder 。)

您是否真的需要 需要 来做任何懒惰的吗?

问题回答

您应该对 同步 区块内的 null 进行另一次检查。

当两个线索呼唤您的方法时, 他们都会发现 < code> order StatusMap 是空的, 其中一个会进入 < code> 同步 区块, 而另一个会屏蔽。 但最终会通过同步区块, 并重新初始化地图 。

否,不正确

此处的懒惰初始化也无需 < em> / em (我认为这已被过度使用) 。

private static final Map<String, String> orderStatusMap;
static{
    orderStatusMap = Collections.synchronizedMap(new HashMap<String, String>());//making it thread safe
    //or use a ConcurrentHashMap

    orderStatusMap.put("Key1", "Value1");
    orderStatusMap.put("Key2", "Value2");
    orderStatusMap.put("Key3", "Value3");
    orderStatusMap.put("Key4", "Value4");
}

public static Map<String, String> getOrderStatusInstance() {
    return orderStatusMap;
}




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...