Search code examples
javamultithreadingthread-safetyrace-conditionthread-synchronization

Does thread-safe mean no race conditions?


ConcurrentHashMap is thread-safe, but race conditions can occur, because as I understand only parts of the map are locked and only for write operations meaning that if there is a read operation at the same time there will be a race condition.

But I read also like here https://en.wikipedia.org/wiki/Thread_safety

Thread safe: Implementation is guaranteed to be free of race conditions when accessed by multiple threads simultaneously.

Can I say that ConcurrentHashMap is thread-safe, but not fully synchronized? What is the right terminology here?


Solution

  • I don't know that there is a formal definition of "thread safe."

    When people say that some class is thread safe, they usually mean that concurrent use of the class methods by several threads can not cause behavior that would surprise a reasonable programmer who has read the class documentation.

    "Thread safe" for a Map would mean things like:

    • If two or more threads store different keys, all of the stores will happen.
    • If two or more threads store different values for the same key, at least one of the stores will happen.
    • If one thread stores a value for a key while another thread attempts to get the value for that key, then the reading thread will either get the old value or the new value.
    • The value for key K will never change because of multiple threads accessing and/or storing other keys.
    • Concurrent use of the same map by multiple threads will never cause the JVM to throw a VirtualMachineError, or cause it to segfault.
    • etc.

    Note that some of the above are examples of race conditions that the class itself is powerless to prevent. "Thread safe" is not a promise that your program will be free from race conditions if you use a thread safe class. It only promises that the class's own source code will not be the cause of thread-related bugs in your program.