I need to initialize a single instance of LinkedHashMap while starting my SpringBoot application .I tried to initialize the same in the following way
@Getter
private Map<Long, String> myMap;
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
synchronized (this) {
if (null == myMap) {
myMap = new LinkedHashMap<>();
}
}
}
My static code analysis tool spotbugs reported the following
EI: May expose internal representation by returning reference to mutable object
I cannot return the copy of LinkedHashMap since it needs to be shared among all the threads. So I decided to supress warning . Is this approach correct or is there any other efficient way?
IMHO you can suppress the warning.
Alternatively, you can do the following:
Instead of providing
getterto this instance, you can provide public methods likegetoraddwhich will use thisMap. It means, threads will not have direct access to your hashmap, but only through the method. In this way, you need not to suppress the warning.