i need a thread safe map, i have something like this: (i'm very new to java)
public static class Manager { static { //something wrong here, doesn't compile list = new java.util.Collections .synchronizedMap(new Map<String, Client>()); } static Map<String,Client> list; public static void AddClient(Client client) { // thread safe add client to the list } public static void RemoveClient(Client client) { // thread safe remove client to the list } }
Java HashMap is not thread-safe and hence it should not be used in multithreaded applications.
TreeMap and TreeSet are not thread-safe collections, so care must be taken to ensure when used in multi-threaded programs. Both TreeMap and TreeSet are safe when read, even concurrently, by multiple threads.
You can make HashMap thread safe by wrapping it with Collections. synchronizedMap() . What's the difference? @naXa ConcurrentHashMap allows concurrent access and a synchronized one doesn't.
HashMap performance is relatively high because it is non-synchronized in nature and any number of threads can perform simultaneously. But ConcurrentHashMap performance is low sometimes because sometimes Threads are required to wait on ConcurrentHashMap.
java.util.concurrent.ConcurrentHashMap
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With