I have a variable:
ConcurrentHashMap<String, List<AnObjectType>> mapOfList;
The List as I understand is not thread safe. But I don’t want to use Synchronized keyword as I actually want concurrent read access and synchronized write to the list and not blocking read and writes.
So I would normally declare Volatile on the variable like so:
volatile List<AnObjectType> varName;
(Although in this case I think this referers to Volatile reference on the list, but what I want is for both the list reference and the content of the list to be volatile.)
But how do I do that within a ConcurrentHashMap construct given that I don’t declare the list as a variable anywhere but within a method?
i.e. List is created within method:
if (!mapOfList.containsKey("ListA")) {
List<AnObjectType> listA=new ArrayList<AnObjectType>();
mapOfList.put("ListA", listA);
}
and the list is accessed in another method within the same class:
List<AnObjectType> listA=mapOfList.get("ListA");
if (listA!=null) {
// Do something concurrent with listA.
}
Sub Question: Would something like this work at all?
ConcurrentHashMap<String,List<AtomicReference<AnObjectType>>>>
Elaboration on the list’s operations:
The list will be accessed via multiple threads reading almost constantly. Write access to the list will be triggered on certain conditions. So what I want is a concurrent access to the List’s content with seldom write operations on the list’s content that should be reflected by all reads after the write operation.
Use
ConcurrentMap#putIfAbsentfor creating theList, and access all lists in a lazy getter:The
CopyOnWriteArrayListshould give you the synchronized performance you need.