I have ConcurrentHashMap that I store in the servlet context, data in the map changes concurrently, I know that servlet context isn’t thread safe but ConcurrentHashMap is (for writing). Should I use synchronize construction in this case?
synchronized (context) {
ConcurrentHashMap messages =(ConcurrentHashMap)context.getAttribute("map");
String mes = messages.get("id"); // can be changed by another thread?
messages.put("id",mes +"changed by thread 1");
}
Sorry but i don’t see the problem. “messages” is a local variable in this example, every thread would have one. You are not sharing “messages”
The only problem could arise when you read from “context” so, you will only need to sync that read
but, best thing is to avoid that. How you will avoid sync on read form context? simple, you must not write on context or do that only on the initialitation process.