Machine-translated by Google. Questions are authored in English.
Top

Discussion

Sample43 is run - what will be the output?

import java.util.*;

public class Sample43
{
    static final Map<Integer, Integer> MAP = new HashMap<>();

    public static void main(String[] args) throws InterruptedException
    {
        Runnable job = () -> { for (int i = 0; i < 1000; i++) MAP.put(i, i); };
        Thread a = new Thread(job), b = new Thread(job);
        a.start(); b.start(); a.join(); b.join();
        System.out.println(MAP.size());
    }
}

  • A.Exactly 2000, because each thread inserts its own entries
  • B.A ConcurrentModificationException from one of the threads
  • C.Possibly 1000, but the map may also be corrupted or the size wrong
  • D.Exactly 1000, because both threads write the same keys

Answer: C

Both threads write the same 1000 keys, so a correct result would be a size of 1000, but HashMap is unsynchronized and concurrent structural modification can leave the table in an inconsistent state. The size may be wrong and entries may be lost. ConcurrentModificationException guards iteration, not concurrent puts.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.