EnumMap is a specialized Map implementation in Java designed specifically for use with enum keys. It provides high performance and is optimized for enum types. However, when it comes to multithreaded environments, EnumMap behaves like most other collections in Java, which means it is not thread-safe for concurrent read and write operations.
To ensure safe use of EnumMap in multithreaded code, proper synchronization mechanisms must be implemented to prevent data inconsistency or unexpected behavior. Common approaches include using synchronized blocks or utilizing higher-level concurrency utilities like java.util.concurrent.ConcurrentHashMap if suitable.
Here's a simple example demonstrating the use of EnumMap in a multithreaded scenario:
import java.util.EnumMap;
enum Color {
RED, GREEN, BLUE;
}
public class EnumMapExample {
private final EnumMap colorMap = new EnumMap<>(Color.class);
public EnumMapExample() {
colorMap.put(Color.RED, 1);
colorMap.put(Color.GREEN, 2);
colorMap.put(Color.BLUE, 3);
}
public synchronized void updateColorValue(Color color, int value) {
colorMap.put(color, value);
}
public synchronized Integer getColorValue(Color color) {
return colorMap.get(color);
}
public static void main(String[] args) {
EnumMapExample example = new EnumMapExample();
// Create threads to update and read values
Thread writerThread = new Thread(() -> {
example.updateColorValue(Color.RED, 10);
});
Thread readerThread = new Thread(() -> {
System.out.println("Value of RED: " + example.getColorValue(Color.RED));
});
writerThread.start();
readerThread.start();
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?