Note that there are some explanatory texts on larger screens.

plurals
  1. POUpdating (and Iterating) a Map in Java
    primarykey
    data
    text
    <p>I have seen this code in the book Java 7 recipes to update and iterate a Map concurrently: </p> <pre><code>ConcurrentMap&lt;Integer,String&gt; concurrentMap = new ConcurrentHashMap&lt;Integer, String&gt;(); for (int i =0;i &lt; 1000;i++) { startUpdateThread(i, concurrentMap); } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } for (Map.Entry&lt;Integer, String&gt; entry : concurrentMap.entrySet()) { System.out.println("Key :"+entry.getKey()+" Value:"+entry.getValue()); } </code></pre> <p>And the method to update the map as follows: </p> <pre><code>private void startUpdateThread(int i, final ConcurrentMap&lt;Integer, String&gt; concurrentMap) { Thread thread = new Thread(new Runnable() { public void run() { while (!Thread.interrupted()) { int randomInt = random.nextInt(20); concurrentMap.put(randomInt, UUID.randomUUID().toString()); } } }); thread.setName("Update Thread "+i); updateThreads.add(thread); thread.start(); } </code></pre> <p>I have tried with just a HashMap instead of ConcurrentHasMap and the results are the same (monitored with Java VisualVM). Does anyone know why? </p> <p>Thanks, Agustin</p> <p>UPDATE: A few interesting questions: </p> <ol> <li>If the HashMap has a constant capacity, what of the following operations can be performed safely? <ul> <li>Two threads updating values in the HashMap. </li> <li>Two threads updating values in the HashMap while a third one is reading the HashMap. </li> </ul></li> <li>If I want speed in updating a Map, does it make sense to have more than 4 threads in a computer with only 4 processors? </li> </ol>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload