Edit with example
this will copy the input map, safely provide an immutable copy of the map when request, and safely return an element of the map when needed:
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class CopyMap {
//just an example Long and String are both immutable
//replace Long for Book (Book has to implement hashcode and equals.
// replace String for Booklog
private final Map<Long, String> map;
public CopyMap(Map<Long,String> map) {
this.map = new ConcurrentHashMap<>(map);
}
// get a non editable copy of the whole map
// threadsafe because this.map is concurrentHashMap
// no synchronization needed
public Map<Long,String> getMap() {
return Collections.unmodifiableMap(this.map);
}
//get only one of the elements
//thread safe because implementation is ConcurrentHashMap
//no synchronization needed
public String get(Long key) {
return map.get(key);
}
//just to try it, with -ea enabled
public static void main(String... args) {
final Map<Long,String> map1 = new ConcurrentHashMap<>();
map1.put(1l,"1");
map1.put(2l,"2");
map1.put(3l,"3");
final CopyMap copyMap = new CopyMap(map1);
assert(copyMap.getMap().equals(map1));
assert(copyMap.getMap()!=map1);
assert(copyMap.get(1l).equals("1"));
assert(copyMap.get(2l).equals("2"));
assert(copyMap.get(3l).equals("3"));
}
}
Original for historical purposes:
A few things,
Firstly, it is better if you define your variables/fields/constants all as interfaces as opposed to specific concrete classes. So, you should define you map as:
//conventions usually prefer private final, as opposed to final private
private final Map<Book,BookLog> booklogMap;
Then, and Secondly, you can indeed use the Collections.unmodifiableMap()
So an example would be:
//package and imports here
public class MyClass {
private final Map<Book,BookLog> booklogMap;
public MyClass(Map<Book, BookLog> booklogMap) {
this.booklogMap = Collections.unmodifiableMap(booklogMap);
}
}
Thirdly, for you to have true immutability, you need to make the whole hierarchy of objects immutable. So your classes Book
and BookLog
need to be immutable as well.
Otherwise, you need to deep copy all the Book(s), and BookLog(s) one by one in the constructor.