thread safe map for java

前端 未结 7 813
忘掉有多难
忘掉有多难 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 15:08

    Your code should look like this, ignoring imports, et al.

    public class Manager
    {
        Map list = java.util.Collections.synchronizedMap(new HashMap());
    
        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.

提交回复
热议问题