i need a thread safe map, i have something like this: (i\'m very new to java)
public static class Manager
{
static
{
//something wr
The ConcurrentHashMap class from the java.util.concurrent
package is a thread-safe implementation of Map that offers far better concurrency than synchronizedMap
(and far superior scalability over Hashtable
). See http://www.ibm.com/developerworks/java/library/j-jtp07233.html.
Use ConcurrentHashMap
from java.util.concurrent
ConcurrentHashMap<K,V>
ConcurrentMap<K,V>
ConcurrentNavigableMap<K,V>
ConcurrentHashMap<K,V>
ConcurrentSkipListMap<K,V>
from java.util.Collections
Collections.synchronizedMap(Map<K,V> m)
Collections.synchronizedNavigableMap(NavigableMap<K,V> m)
Collections.synchronizedSortedMap(SortedMap<K,V> m)
Your code should look like this, ignoring imports, et al.
public class Manager
{
Map<String,Client> list = java.util.Collections.synchronizedMap(new HashMap<String, Client>());
public void AddClient(Client client)
{
// thread safe add client to the list
}
public void RemoveClient(Client client)
{
// thread safe remove client to the list
}
}
That said, beware that this is not as thread safe as you might hope. As others have mentioned, you probably want to use the Java Concurrent Collections.
You can't initialize an object member variable in a static block. Static blocks are executed once when the class is first loaded, not once for every object of that class, whereas the variable "list" is created once for each object of the class.
Also, you can't instantiate a "new Map" because Map is an interface. You need to wrap the synchronizedMap around a real Map like a HashMap or a TreeMap.
{
list = new java.util.Collections
.synchronizedMap(new HashMap<String, Client>());
}
Your map "list" needs to be static if you want to access it in a static block.