0

I have an HashMap as:

 Map<Integer ,ArrayList<Double>> map1 = new HasMap<Integer,ArrayList<Double>>()

This map is accessed and modified by some number of threads. I would like to make thread safe update for the granularity level of each of the component of ArrayList. It means, one value can be modified by several threads but one component can not be modified by several threads. How can I do it? Does this prevents from "undefined property" while iterating? iterating values

[EDIT]

 key      value
 1000    [0.1,0.002,0.8,0.112]

Each of the components of value is updated. While updating, first component can be updated by one thread and second by another thread at a time. I don't want to lock a pair for one thread only.

4

3 回答 3

1

I think what you want is to use a Lock. When you call lock() It will allow you to "lock" the resource from being used by other threads, then call unlock() when the update is finished on that resource so that other threads can then modify it. You can create a lock for each resource.

于 2012-07-21T07:52:09.720 回答
1

Instead of an ArrayList, use a CopyOnWriteArrayList - it's designed especially for multi-threading and performs much better than variants which uses mutexes/synchronization (like Vector):

Map<Integer ,List<Double>> map1 = new HashMap<Integer, CopyOnWriteArrayList<Double>>();

(but beware if you do much more updates than reads to the List)

According do you comments, you don't need any synchronization of the outer Map, because it's not modified concurrently.

于 2012-07-21T07:52:32.707 回答
1

I think you can try with ConcurrentHashMap for this

于 2012-07-21T07:52:37.090 回答