简体   繁体   English

从多个线程设置和更新并发哈希映射

[英]Set and Update concurrenthashmap from multiple thread

I am implementing a Client Lookup Map where i am using ConcurrentHashamp. 我正在使用ConcurrentHashamp实施客户端查找图。

    private ConcurrentHashMap<String,SignupDTO> map = new <String,SignupDTO> ConcurrentHashMap();*
    public  SignupDTO get(String opcode) 
    {
      return this.map.get(opcode);
    }
    public  void set(String opcode,SignupDTO dto) 
    {
      this.map.put(opcode, dto);
    }

Here get and set function called from multiple thread to update and get client information. 这里从多个线程调用get和set函数来更新和获取客户端信息。 I have another function update() which is called from a specific thread after certain time and update the map with updated client information. 我还有另一个函数update(),该函数在特定时间后从特定线程调用,并使用更新的客户端信息更新地图。

public  void update() 
    {
        Connection connection = null;
        Statement stmt = null;
        ResultSet rs = null;

        try 
        {
            connection = DatabaseManager.getInstance().getConnection();
            stmt = connection.createStatement();    
            String sql= "select * from client";
            rs = stmt.executeQuery(sql);
            while (rs.next()) 
            {
                SignupDTO row = new SignupDTO();
                ......
                            ..........
                this.map.put(key, row);         
            }

        } 
    }

get and set operation on map will be thread safe or not? 在地图上进行get和set操作是否是线程安全的? please help me. 请帮我。

As @nosid pointed out, your update method will not be thread safe (= it can update only half of map, then someone can read mixture of old/new values, and the your update method will finish updating the other half). 正如@nosid指出的那样,您的update方法将不是线程安全的(=它只能更新map的一半,然后有人可以读取旧值/新值的混合,并且您的update方法将完成另一半的更新)。

I recommend you put your query result into a Map (not nesseserly concurrent one) and the update with putAll method from your ConcurrentHashMap, which is thread-safe (or at least official documentation caims so). 我建议您将查询结果放入一个Map(而不是并发的)中,并从ConcurrentHashMap中使用putAll方法进行更新,这是线程安全的(或者至少是官方文档如此)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM