简体   繁体   English

哈希图中的线程问题

[英]Threading issue in hashmap

I am using two threads to put values in the same hashmap. 我正在使用两个线程将值放在同一哈希图中。 Thread 1 will read the values what it was stored and thread 2 will read only the values what it was stored in the map. 线程1将读取存储的值,线程2将仅读取映射存储的值。

In that i am getting NullPointerException . 在这种情况下,我得到了NullPointerException Is that due to threading issue?? 那是由于线程问题吗?

HashMap map = new HashMap();

    Thread1:

           map.put(1,1);
           map.put(2,2);
           map.get(1).toString(); // here null pointer i am getting.. Is it possible due to threading issue..

    Thread 2:
       map.put(4,4);
       map.put(5,5)

There are 2 solutions 有2个解决方案

1) Use java.util.ConcurrentHashMap, which is designed to operate in a threaded enviornment. 1)使用java.util.ConcurrentHashMap,它设计为在线程环境中运行。

2) Synchronize the hashmap. 2)同步哈希图。 Java allows you to synchronize on objects, so you can ensure that only one thread touches the object at at time. Java允许您在对象上进行同步,因此可以确保一次只有一个线程接触该对象。

ex. 例如

synchronized(map) {
    map.put("important", "stuff");
}

Method #2 is NOT the preferred solution for multithreading (CuncurrentHashMap is), but is your only option if you cannot change the type of the variable (like on a large project). 方法2不是多线程的首选解决方案(CuncurrentHashMap是),但是如果您不能更改变量的类型(例如在大型项目中),则方法2是您的唯一选择。

@Dylan is correct, short answer is you should never use HashMaps in a concurrent environment. @Dylan是正确的,简短的答案是您永远不要在并发环境中使用HashMaps。 Luckily, java.util.concurrent.ConcurrentHashMap to the rescue. 幸运的是,java.util.concurrent.ConcurrentHashMap得以解救。

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

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