How does equals and hashCode behave in multithreaded code?

In Java, the behavior of `equals` and `hashCode` methods can have significant implications in multithreaded environments. These methods are often overridden for objects that need to be stored in collections like `HashSet`, `HashMap`, or `Hashtable`. When multiple threads interact with shared objects, ensuring that the implementations of `equals` and `hashCode` are thread-safe is essential to prevent inconsistencies and unpredictable behavior.

For instance, if one thread modifies the fields of an object that is used as a key in a hash-based collection, it can lead to a situation where the object can no longer be retrieved by another thread. This can happen if the hash code changes due to the modifying thread affecting the internal state of the object. Therefore, it is often encouraged to make these methods immutable or synchronize access to them in multi-threaded scenarios.

Here’s an example illustrating a potential issue with `equals` and `hashCode` in a multithreaded context:


class User {
    private String username;
    
    public User(String username) {
        this.username = username;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (!(obj instanceof User)) return false;
        User user = (User) obj;
        return username.equals(user.username);
    }

    @Override
    public int hashCode() {
        return username.hashCode();
    }

    public void setUsername(String username) {
        this.username = username;
    }
}

public class Main {
    public static void main(String[] args) {
        User user = new User("JohnDoe");
        
        // Using a Thread to modify the username
        new Thread(() -> {
            user.setUsername("JaneDoe");
        }).start();
        
        // Accessing the user object from another thread
        new Thread(() -> {
            // Delay to ensure the username may have changed
            System.out.println(user.equals(new User("JohnDoe"))); // May print false
        }).start();
    }
}
    

Java equals hashCode multithreading thread safety synchronization collections HashMap HashSet