javahashtable

Hashtable Synchronization Issue


I am trying to test the Synchronization in Java Hashtable. Below is the code. It should output 1000 always. But it is not the expected behaviour. Can someone please explain why it is behaving this way?

    Map<String, Integer> map = new Hashtable<>();
    map.put("key", 0);
    Runnable task = () -> {
        for (int i = 0; i < 10; i++) {
            map.put("key", map.get("key")+1);
        }
    };

    Thread[] threads = new Thread[100];
    for (int i = 0; i < 100; i++) {
        threads[i] = new Thread(task);
        threads[i].start();
    }

    for (int i = 0; i < 100; i++) {
        try {
            threads[i].join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    System.out.println("Hashtable value: " + map.get("key"));

output : 1000 but it is not giving 1000 always.


Solution

  • Hashtable is synchronized meaning that two threads can not update it at the same time, however there are no guarantees about the values used by those threads. In your case each thread may overwrite each others last update.