简体   繁体   English

通过两个线程并发修改HashMap

[英]Concurrent modification of HashMap by two threads

If two threads try to put (key, value) in same map passed in constructor of thread. 如果两个线程试图将(键,值)放在线程的构造函数中传递的同一映射中。 What kind of threading issues i might encounter? 我可能会遇到什么样的线程问题?

public class App {
    public static void main(String[] args) throws JMSException {
        Map<String, String> map = new HashMap<String, String>();
        map.put("5", "fnc");

        Thread t1 = new App().new T(map);
        Thread t2 = new App().new T(map);
        t1.start();
        t2.start();
    }

    class T extends Thread {

        private Map<String, String> map;

        public T(Map<String, String> map) {
            this.map = map;
        }

        public void run() {
            // put 100s of keys in map here
            map.put("1", "abc");
            // put other keys
        }
    }
}

map will not be thread safe. 地图将不是线程安全的。 that means few scenario shall happen 这意味着几乎不会发生任何情况

1) thread 1 trying to retrieve a entry from a key and thread 2 trying to modify the entry on that moment. 1)线程1试图从键中检索条目,线程2试图在那一刻修改条目。 2) vice versa. 2)反之亦然。

you can use ConcurrentHashMap to serve this purposes which handle concurrency. 您可以使用ConcurrentHashMap来达到处理并发的目的。

One example: while thread 1 is putting a value, thread 2 decides to increase hash table capacity. 一个示例:线程1放置值时,线程2决定增加哈希表容量。 In this case thread 1 may put its value to the old hash table and thread 2 may overwrite this hash table with a new one. 在这种情况下,线程1可以将其值放在旧的哈希表中,线程2可以用新的哈希表覆盖此哈希表。 Thread 1 put is lost. 线程1 put丢失。

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

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