I am trying to find answer to my question, but not able to find it on Google or in Java docs.
in ConcurrentHashMap, suppose a thread t1 has read from segment n, and at same another thread t2 update the on the same segment n:
what is the use of concurrent read if our read by t1 became dirty because Thread t2 has updated it?
EdIted: I am expecting result of below program to be 12 but it is giving 2 or 11. that is the concern. Looks like concurrentHashMap is not safe.
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);
}
}
}