Gaurav Agarwal
Gaurav Agarwal

Reputation: 611

Is ConcurrentHashMap<Integer, ArrayList<Object>> Thread safe?

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?

Upvotes: 2

Views: 635

Answers (2)

Thilo
Thilo

Reputation: 262494

Even if ArrayList was thread-safe (which it is not), you have four different all_payloads.get calls in that snippet, and even if those are individually thread-safe, the combination of them is not (the calls can be interleaved in funky ways in the presence of concurrency).

Upvotes: 2

Mureinik
Mureinik

Reputation: 311163

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

Upvotes: 1

Related Questions