thread safe map for java

前端 未结 7 814
忘掉有多难
忘掉有多难 2020-12-09 14:44

i need a thread safe map, i have something like this: (i\'m very new to java)

 public static class Manager
        {
        static 
        {
//something wr         


        
相关标签:
7条回答
  • 2020-12-09 14:55

    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.

    0 讨论(0)
  • 2020-12-09 15:03

    Use ConcurrentHashMap

    0 讨论(0)
  • 2020-12-09 15:04

    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)
    
    0 讨论(0)
  • 2020-12-09 15:08

    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.

    0 讨论(0)
  • 2020-12-09 15:10

    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>());
            }
    
    0 讨论(0)
  • 2020-12-09 15:11

    Your map "list" needs to be static if you want to access it in a static block.

    0 讨论(0)
提交回复
热议问题