[英]Thread 1 is reading from ConcurrentHashMap on segment n and Thread 2 is updating value in same sagment.Won't it make thread 1 read dirty?
I am trying to find answer to my question, but not able to find it on Google or in Java docs. 我正在尝试找到问题的答案,但无法在Google或Java文档中找到它。
in ConcurrentHashMap, suppose a thread t1 has read from segment n, and at same another thread t2 update the on the same segment n: 在ConcurrentHashMap中,假定线程t1已从段n中读取,并且同一线程另一个t2在同一段n上更新了该线程:
what is the use of concurrent read if our read by t1 became dirty because Thread t2 has updated it? 如果t1的读取由于线程t2更新了它而变得脏了,那么并行读取有什么用?
EdIted: I am expecting result of below program to be 12 but it is giving 2 or 11. that is the concern. EdIted:我期望以下程序的结果为12,但给出的结果为2或11。 Looks like concurrentHashMap is not safe.
看起来parallelHashMap不安全。
package katalyst.samples;
import java.util.concurrent.ConcurrentHashMap;
public class SampleCode {
public static void main(String[] args) throws InterruptedException {
ThreadRun r1 = new ThreadRun();
Thread t1 = new Thread(r1);
t1.setName("Thread1");
Thread t2 = new Thread(r1);
t2.setName("Thread2");
t2.start();
t1.start();
t1.join();
t2.join();
System.out.println(r1.getCHM().get("a"));
}
}
class ThreadRun implements Runnable {
ConcurrentHashMap<String, Integer> CHM = null;
public ConcurrentHashMap<String, Integer> getCHM() {
return CHM;
}
ThreadRun() {
CHM = new ConcurrentHashMap<>();
CHM.put("a", 1);
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
int value = CHM.get("a");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (Thread.currentThread().getName().equals("Thread1")) {
// int a = CHM.get("a");
value = value + 1;
CHM.put("a", value);
} else {
// int a = CHM.get("a");
value = value + 10;
CHM.put("a", value);
}
}
}
in short, if a segment is updated and some other thread wants to read it, it will able to read, but will get last updated value(not the current/in-progress value) 简而言之,如果某个段已更新,并且某个其他线程想要读取它,则它将能够读取,但是将获得上次更新的值(而不是当前/正在进行的值)
Note: one thread always goes first because they cannot access the same key simultaneously. 注意:一个线程始终优先,因为它们不能同时访问同一密钥。 You may or may not see the object depending on when operation is performed on that key first.
您可能会或可能不会看到对象,这取决于首先对该键执行操作的时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.