Lazily initialize a Java map in a thread safe manner

前端 未结 3 921
悲&欢浪女
悲&欢浪女 2020-12-16 13:36

I need to lazily initialize a map and its contents. I have the below code till now:

class SomeClass {
    private Map someMap = null;

         


        
3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-16 14:21

    I think TimB explained most of the options very well, but I think the quickest and most obvious answer would be to create it when the class instance is instantiated.

    class SomeClass {
        private final Map someMap = new HashMap();
    
        public String getValue(String key) {
            return someMap.get(key);  // the key might not exist even after initialization
        }
    }
    

提交回复
热议问题