Issue
This is how I have defined a ConcurrentHashMap
:
ConcurrentHashMap<Integer, ArrayList<Object>> all_payloads = new ConcurrentHashMap<Integer, ArrayList<Object>>();
I understand that there the blocking operation works only when writing or removing from the ConcurrentHashMap
, but will this lock extend to the values which are of ArrayList
type too?
For example:
for(int i = 0; i < all_payloads.get(0).size(); i++) {
if(all_payloads.get(0).get(i).getBucketNumberCollector() == this.bucket_no) {
currentPayload = all_payloads.get(0).remove(i);
currentPayload.setCollector(collector);
all_payloads.get(1).add(currentPayload);
break;
}
}
In the above snippet, I am only using the get(Object key)
method to modify the value associated with that key - which in this case is of type ArrayList
.
Will the above snippet be thread-safe? If not then what can be done to make it so?
Solution
No, it doesn't. An ArrayList
is an ArrayList
, regardless of where you put it. The ConcurrentHashMap
's synchronization extends only to the get
operation, and from there on, if multiple threads can execute the same piece of code concurrently, you'd need an additional mechanism to protect it.
List<Object> myList = all_payloads.get(0);
synchronized (myList) {
// code that uses myList
Answered By - Mureinik
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.