23

I'm working on an application, that has uses a HashMap to share state. I need to prove via unit tests that it will have problems in a multi-threaded environment.

I tried to check the state of the application in a single thread environment and in a multi-threaded environment via checking the size and elements of the HashMap in both of them. But seems this doesn't help, the state is always the same.

Are there any other ways to prove it or prove that an application that performs operations on the map works well with concurrent requests?

thokuest
  • 5,800
  • 24
  • 36
Alexander Bezrodniy
  • 8,474
  • 7
  • 22
  • 24
  • 5
    This is essentially impossible: you can't force race conditions on demand. – Louis Wasserman Aug 30 '13 at 22:15
  • IBM has/had a tool called ConTest that would weave your bytecode in such a way to make race conditions more common. I bet it would find problems with `HashMap` in a jiffy. I can't find it now, though; it could be they got rid of it, or rolled it into a (possibly proprietary) bundle of software. – yshavit Aug 30 '13 at 22:15
  • For high reliability, I've had better luck with actual code proofs as opposed to testing. Case in point, I worked on a system that required 6 weeks worth of running the exact same test repeatedly overnight to reveal one race condition. – Kyle Dewey Aug 31 '13 at 01:40
  • Just because it "works well" doesn't make it thread safe. You can use tools to help find thread safety bugs but you can not prove some thing is thread safe by experimentation. You have to understand the code and what it is doing. Some once "proved" that PI was a fraction by measuring 10 circles and concluding a fraction worked well in those cases. ;) – Peter Lawrey Aug 31 '13 at 06:49
  • You could slam the code with a few nested for-loop parallel streams. If you have enough loops, technically the test is still flaky, but the probability would greatly increase of reproducing errors. I used this to prove some thread safety issues with some of our code using unit tests. – cody.tv.weber Jan 06 '20 at 21:34

12 Answers12

35

This is quite easy to prove.

Shortly

A hash map is based on an array, where each item represents a bucket. As more keys are added, the buckets grow and at a certain threshold the array is recreated with a bigger size so that its buckets are spread more evenly (performance considerations). During the array recreation, the array becomes empty, which results in empty result for the caller, until the recreation completes.

Details and Proof

It means that sometimes HashMap#put() will internally call HashMap#resize() to make the underlying array bigger.

HashMap#resize() assigns the table field a new empty array with a bigger capacity and populates it with the old items. While this population happens, the underlying array doesn't contain all of the old items and calling HashMap#get() with an existing key may return null.

The following code demonstrates that. You are very likely to get the exception that will mean the HashMap is not thread safe. I chose the target key as 65 535 - this way it will be the last element in the array, thus being the last element during re-population which increases the possibility of getting null on HashMap#get() (to see why, see HashMap#put() implementation).

final Map<Integer, String> map = new HashMap<>();

final Integer targetKey = 0b1111_1111_1111_1111; // 65 535
final String targetValue = "v";
map.put(targetKey, targetValue);

new Thread(() -> {
    IntStream.range(0, targetKey).forEach(key -> map.put(key, "someValue"));
}).start();


while (true) {
    if (!targetValue.equals(map.get(targetKey))) {
        throw new RuntimeException("HashMap is not thread safe.");
    }
}

One thread adds new keys to the map. The other thread constantly checks the targetKey is present.

If count those exceptions, I get around 200 000.

Artem Novikov
  • 4,087
  • 1
  • 27
  • 33
  • Can you please throw some light on how this is prevented using ConcurrentHashMap? For ConcurrentHashMap, does resizing take place for 1 out of 16 parts at a time or for whole map at once? – Sumit Desai Oct 25 '19 at 13:12
  • @SumitDesai I recommend reading https://dzone.com/articles/how-concurrenthashmap-works-internally-in-java. Specifically to answer your question, individual Segments are resized whilst being locked, so yes, resizing works only on a part of the map at time. The specific number of Segments used depends on the initial capacity (if set). – Woodz Dec 17 '19 at 03:52
  • 1
    "HashMap#resize() assigns the table field a new empty array with a bigger capacity"... Shouldn't we first create a new empty array, populate it by rehashing all the keys present in the original array and then assign that array = newArray ? Basically, while new array is being populated, original array can serve read request. In that case we won't require thread safety for W/R scenarion ? – user2488286 Jan 05 '20 at 10:23
  • 1
    It's enough to simply do `map.get(targetKey)` in the while loop. Also, this is so effective that even replacing the `while` loop with a IntStream(0, 10) triggers the NPE. This works EXTREMELY well, nice work Arterm Novikov. – robert Sep 05 '20 at 23:26
  • I had the same question as user2488286 above. Did you get an answer for that? Why not have the original array serve the requests until the 2nd array is ready? – Austin Jul 19 '21 at 10:17
  • Excuse me, but what do you mean by "If count those exceptions, I get around 200 000"? you mean when run this code, you will get around 200000 lines of exceptions? – Lake_Lagunita Aug 27 '21 at 06:35
8

It is hard to simulate Race but looking at the OpenJDK source for put() method of HashMap:

public V put(K key, V value) {
    if (key == null)
        return putForNullKey(value);

    //Operation 1       
    int hash = hash(key.hashCode());
    int i = indexFor(hash, table.length);
    for (Entry<K,V> e = table[i]; e != null; e = e.next) {
        Object k;
        if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
            V oldValue = e.value;
            e.value = value;
            e.recordAccess(this);
            return oldValue;
        }
    } 

    //Operation 2
    modCount++;

    //Operation 3
    addEntry(hash, key, value, i);
    return null;
}

As you can see put() involves 3 operations which are not synchronized. And compound operations are non thread safe. So theoretically it is proven that HashMap is not thread safe.

Guy
  • 46,488
  • 10
  • 44
  • 88
Narendra Pathai
  • 41,187
  • 18
  • 82
  • 120
6

I need to prove via unit tests that it will have problems in multithread environment.

This is going to be tremendously hard to do. Race conditions are very hard to demonstrate. You could certainly write a program which does puts and gets into a HashMap in a large number of threads but logging, volatile fields, other locks, and other timing details of your application may make it extremely hard to force your particular code to fail.


Here's a stupid little HashMap failure test case. It fails because it times out when the threads go into an infinite loop because of memory corruption of HashMap. However, it may not fail for you depending on number of cores and other architecture details.

@Test(timeout = 10000)
public void runTest() throws Exception {
    final Map<Integer, String> map = new HashMap<Integer, String>();
    ExecutorService pool = Executors.newFixedThreadPool(10);
    for (int i = 0; i < 10; i++) {
        pool.submit(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10000; i++) {
                    map.put(i, "wow");
                }
            }
        });
    }
    pool.shutdown();
    pool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
}
Gray
  • 115,027
  • 24
  • 293
  • 354
6

Its an old thread. But just pasting my sample code which is able to demonstrate the problems with hashmap.

Take a look at the below code, we try to insert 30000 Items into the hashmap using 10 threads (3000 items per thread).

So after all the threads are completed, you should ideally see that the size of hashmap should be 30000. But the actual output would be either an exception while rebuilding the tree or the final count is less than 30000.

class TempValue {
    int value = 3;

    @Override
    public int hashCode() {
        return 1; // All objects of this class will have same hashcode.
    }
}

public class TestClass {
    public static void main(String args[]) {
        Map<TempValue, TempValue> myMap = new HashMap<>();
        List<Thread> listOfThreads = new ArrayList<>();

        // Create 10 Threads
        for (int i = 0; i < 10; i++) {
            Thread thread = new Thread(() -> {

                // Let Each thread insert 3000 Items
                for (int j = 0; j < 3000; j++) {
                    TempValue key = new TempValue();
                    myMap.put(key, key);
                }

            });
            thread.start();
            listOfThreads.add(thread);
        }

        for (Thread thread : listOfThreads) {
            thread.join();
        }
        System.out.println("Count should be 30000, actual is : " + myMap.size());
    }
}

Output 1 :

Count should be 30000, actual is : 29486

Output 2 : (Exception)

java.util.HashMap$Node cannot be cast to java.util.HashMap$TreeNodejava.lang.ClassCastException: java.util.HashMap$Node cannot be cast to java.util.HashMap$TreeNode
    at java.util.HashMap$TreeNode.moveRootToFront(HashMap.java:1819)
    at java.util.HashMap$TreeNode.treeify(HashMap.java:1936)
    at java.util.HashMap.treeifyBin(HashMap.java:771)
    at java.util.HashMap.putVal(HashMap.java:643)
    at java.util.HashMap.put(HashMap.java:611)
    at TestClass.lambda$0(TestClass.java:340)
    at java.lang.Thread.run(Thread.java:745)

However if you modify the line Map<TempValue, TempValue> myMap = new HashMap<>(); to a ConcurrentHashMap the output is always 30000.

Another Observation : In the above example the hashcode for all objects of TempValue class was the same(** i.e., 1**). So you might be wondering, this issue with HashMap might occur only in case there is a collision (due to hashcode). I tried another example.

Modify the TempValue class to

class TempValue {
    int value = 3;
}

Now re-execute the same code.
Out of every 5 runs, I see 2-3 runs still give a different output than 30000.
So even if you usually don't have much collisions, you might still end up with an issue. (Maybe due to rebuilding of HashMap, etc.)

Overall these examples show the issue with HashMap which ConcurrentHashMap handles.

Kishore Bandi
  • 5,537
  • 2
  • 31
  • 52
  • This does demonstrate that the put operation is a compound operation which is not thread safe, if you put it in synchronized block it works every time. – somshivam Feb 28 '17 at 04:28
5

Is reading the API docs enough? There is a statement in there:

Note that this implementation is not synchronized. If multiple threads access a hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with a key that an instance already contains is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the map. If no such object exists, the map should be "wrapped" using the Collections.synchronizedMap method. This is best done at creation time, to prevent accidental unsynchronized access to the map:

The problem with thread safety is that it's hard to prove through a test. It could be fine most of the times. Your best bet would be to just run a bunch of threads that are getting/putting and you'll probably get some concurrency errors.

I suggest using a ConcurrentHashMap and trust that the Java team saying that HashMap is not synchronized is enough.

Jeff Storey
  • 56,312
  • 72
  • 233
  • 406
5

Are there any other ways to prove it?

How about reading the documentation (and paying attention to the emphasized "must"):

If multiple threads access a hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally

If you are going to attempt to write a unit test that demonstrates incorrect behavior, I recommend the following:

  • Create a bunch of keys that all have the same hashcode (say 30 or 40)
  • Add values to the map for each key
  • Spawn a separate thread for the key, which has an infinite loop that (1) asserts that the key is present int the map, (2) removes the mapping for that key, and (3) adds the mapping back.

If you're lucky, the assertion will fail at some point, because the linked list behind the hash bucket will be corrupted. If you're unlucky, it will appear that HashMap is indeed threadsafe despite the documentation.

parsifal
  • 174
  • 3
  • I've read it, the question not about what to use (sure, I'll use thread-safe implementation of Map), but about how to check that HashMap can have bugs in multithread env. – Alexander Bezrodniy Aug 30 '13 at 22:06
  • @AlexanderBezrodniy - see edit for a possible demonstration. As other people have said, it's extremely difficult to demonstrate race conditions. Better is to read and understand the source, or rely on the documentation. – parsifal Aug 30 '13 at 22:10
1

It may be possible, but will never be a perfect test. Race conditions are just too unpredictable. That being said, I wrote a similar type of test to help fix a threading issue with a proprietary data structure, and in my case, it was much easier to prove that something was wrong (before the fix) than to prove that nothing would go wrong (after the fix). You could probably construct a multi-threaded test that will eventually fail with sufficient time and the right parameters.

This post may be helpful in identifying areas to focus on in your test and has some other suggestions for optional replacements.

Community
  • 1
  • 1
DSway
  • 752
  • 14
  • 33
1

You can create multiple threads each adding an element to a hashmap and iterating over it. i.e. In the run method we have to use "put" and then iterate using iterator.

For the case of HashMap we get ConcurrentModificationException while for ConcurrentHashMap we dont get.

0

Most probable race condition at java.util.HashMap implementation

Most of hashMaps failing if we are trying to read values while resizing or rehashing step executing. Resizing and rehashing operation executed under certain conditions most commonly if exceed bucket threshold. This code proves that if I call resizing externally or If I put more element than threshold and tend to call resizing operation internally causes to some null read which shows that HashMap is not thread safe. There should be more race condition but it is enough to prove it is not Thread Safe.

Practically proof of race condition

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.IntStream;

public class HashMapThreadSafetyTest {
    public static void main(String[] args) {
        try {
            (new HashMapThreadSafetyTest()).testIt();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void threadOperation(int number, Map<Integer, String> map) {
        map.put(number, "hashMapTest");
        while (map.get(number) != null);
        //If code passes to this line that means we did some null read operation which should not be
        System.out.println("Null Value Number: " + number);
    }
    private void callHashMapResizeExternally(Map<Integer, String> map)
            throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Method method = map.getClass().getDeclaredMethod("resize");
        method.setAccessible(true);
        System.out.println("calling resize");
        method.invoke(map);
    }

    private void testIt()
            throws InterruptedException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        final Map<Integer, String> map = new HashMap<>();
        IntStream.range(0, 12).forEach(i -> new Thread(() -> threadOperation(i, map)).start());
        Thread.sleep(60000);
        // First loop should not show any null value number untill calling resize method of hashmap externally.
        callHashMapResizeExternally(map);
        // First loop should fail from now on and should print some Null Value Numbers to the out.
        System.out.println("Loop count is 12 since hashmap initially created for 2^4 bucket and threshold of resizing"
                + "0.75*2^4 = 12 In first loop it should not fail since we do not resizing hashmap. "
                + "\n\nAfter 60 second: after calling external resizing operation with reflection should forcefully fail"
                + "thread safety");

        Thread.sleep(2000);
        final Map<Integer, String> map2 = new HashMap<>();
        IntStream.range(100, 113).forEach(i -> new Thread(() -> threadOperation(i, map2)).start());
        // Second loop should fail from now on and should print some Null Value Numbers to the out. Because it is
        // iterating more than 12 that causes hash map resizing and rehashing
        System.out.println("It should fail directly since it is exceeding hashmap initial threshold and it will resize"
                + "when loop iterate 13rd time");
    }
}

Example output

No null value should be printed untill thread sleep line passed
calling resize
Loop count is 12 since hashmap initially created for 2^4 bucket and threshold of resizing0.75*2^4 = 12 In first loop it should not fail since we do not resizing hashmap. 

After 60 second: after calling external resizing operation with reflection should forcefully failthread safety
Null Value Number: 11
Null Value Number: 5
Null Value Number: 6
Null Value Number: 8
Null Value Number: 0
Null Value Number: 7
Null Value Number: 2
It should fail directly since it is exceeding hashmap initial threshold and it will resizewhen loop iterate 13th time
Null Value Number: 111
Null Value Number: 100
Null Value Number: 107
Null Value Number: 110
Null Value Number: 104
Null Value Number: 106
Null Value Number: 109
Null Value Number: 105

M S
  • 2,455
  • 1
  • 9
  • 11
0

Very Simple Solution to prove this

Here is the code, which proves the Hashmap implementation is not thread safe. In this example, we are only adding the elements to map, not removing it from any method.

We can see that it prints the keys which are not in map, even though we have put the same key in map before doing get operation.

package threads;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class HashMapWorkingDemoInConcurrentEnvironment {

    private Map<Long, String> cache = new HashMap<>();

    public String put(Long key, String value) {
        return cache.put(key, value);
    }

    public String get(Long key) {
        return cache.get(key);
    }

    public static void main(String[] args) {

        HashMapWorkingDemoInConcurrentEnvironment cache = new HashMapWorkingDemoInConcurrentEnvironment();

        class Producer implements Callable<String> {

            private Random rand = new Random();

            public String call() throws Exception {
                while (true) {
                    long key = rand.nextInt(1000);
                    cache.put(key, Long.toString(key));
                    if (cache.get(key) == null) {
                        System.out.println("Key " + key + " has not been put in the map");
                    }
                }
            }
        }

        ExecutorService executorService = Executors.newFixedThreadPool(4);

        System.out.println("Adding value...");

        try  {
            for (int i = 0; i < 4; i++) {
                executorService.submit(new Producer());
            }
        } finally {
            executorService.shutdown();
        }
    }
}

Sample Output for a execution run

Adding value...
Key 611 has not been put in the map
Key 978 has not been put in the map
Key 35 has not been put in the map
Key 202 has not been put in the map
Key 714 has not been put in the map
Key 328 has not been put in the map
Key 606 has not been put in the map
Key 149 has not been put in the map
Key 763 has not been put in the map

Its strange to see the values printed, that's why hashmap is not thread safe implementation working in concurrent environment.

Rohit Narang
  • 55
  • 1
  • 12
0

There is a great tool open sourced by the OpenJDK team called JCStress which is used in the JDK for concurrency testing.

https://github.com/openjdk/jcstress

In one of its sample: https://github.com/openjdk/jcstress/blob/master/tests-custom/src/main/java/org/openjdk/jcstress/tests/collections/HashMapFailureTest.java

@JCStressTest
@Outcome(id = "0, 0, 1, 2", expect = Expect.ACCEPTABLE, desc = "No exceptions, entire map is okay.")
@Outcome(expect = Expect.ACCEPTABLE_INTERESTING, desc = "Something went wrong")
@State
public class HashMapFailureTest {

    private final Map<Integer, Integer> map = new HashMap<>();

    @Actor
    public void actor1(IIII_Result r) {
        try {
            map.put(1, 1);
            r.r1 = 0;
        } catch (Exception e) {
            r.r1 = 1;
        }
    }

    @Actor
    public void actor2(IIII_Result r) {
        try {
            map.put(2, 2);
            r.r2 = 0;
        } catch (Exception e) {
            r.r2 = 1;
        }
    }

    @Arbiter
    public void arbiter(IIII_Result r) {
        Integer v1 = map.get(1);
        Integer v2 = map.get(2);
        r.r3 = (v1 != null) ? v1 : -1;
        r.r4 = (v2 != null) ? v2 : -1;
    }

}

The methods marked with actor are run concurrently on different threads.

The result for this on my machine is:

Results across all configurations:

       RESULT     SAMPLES     FREQ       EXPECT  DESCRIPTION
  0, 0, -1, 2   3,854,896    5.25%  Interesting  Something went wrong
  0, 0, 1, -1   4,251,564    5.79%  Interesting  Something went wrong
  0, 0, 1, 2  65,363,492   88.97%   Acceptable  No exceptions, entire map is okay.

This shows that 88% of the times expected values were observed but in around 12% of the times, incorrect results were seen.

You can try out this tool and the samples and write your own tests to verify that concurrency of some code is broken.

shubhamgarg1
  • 1,619
  • 1
  • 15
  • 20
0

As a yet another reply to this topic, I would recommend example from https://www.baeldung.com/java-concurrent-map, that looks as below. Theory is very straigthforwad - for N times we run 10 threads, that each of them increments the value in a common map 10 times. If the map was thread safe, the value should be 100 every time. Example proves, it's not.

@Test
public void givenHashMap_whenSumParallel_thenError() throws Exception {
    Map<String, Integer> map = new HashMap<>();
    List<Integer> sumList = parallelSum100(map, 100);

    assertNotEquals(1, sumList
      .stream()
      .distinct()
      .count());
    long wrongResultCount = sumList
      .stream()
      .filter(num -> num != 100)
      .count();
    
    assertTrue(wrongResultCount > 0);
}

private List<Integer> parallelSum100(Map<String, Integer> map, 
  int executionTimes) throws InterruptedException {
    List<Integer> sumList = new ArrayList<>(1000);
    for (int i = 0; i < executionTimes; i++) {
        map.put("test", 0);
        ExecutorService executorService = 
          Executors.newFixedThreadPool(4);
        for (int j = 0; j < 10; j++) {
            executorService.execute(() -> {
                for (int k = 0; k < 10; k++)
                    map.computeIfPresent(
                      "test", 
                      (key, value) -> value + 1
                    );
            });
        }
        executorService.shutdown();
        executorService.awaitTermination(5, TimeUnit.SECONDS);
        sumList.add(map.get("test"));
    }
    return sumList;
}
Sokeks
  • 47
  • 8