I would like to create lock only once when map is initialized. Here is the code i am using.
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;
}
No, that’s a bad idea – you’re returning a mutable, non-thread-safe map. You’re also trying to implement double-checked locking, but not doing it properly – and it’s harder to get it right than it is to use static initialization.
I would create an immutable map (using Guava, for preference), ideally as part of class initialization:
(For more than 5 key/value pairs, use
ImmutableMap.Builder.)Do you really need it to be any lazier than that?