I have the below code , addition looks thread safe to me. How about modifyelement or how can i make this thread safe ?
ConcurrentNavigableMap<String, List<String>> entries = new ConcurrentSkipListMap<>();
public void record(String key, String value) {
entries.computeIfAbsent(key, k -> Collections.synchronizedList(new ArrayList<String>())).add(value);
}
public void modifyelement(String key, String oldval, String newval) {
entries.computeIfPresent(key, (k , v ) -> {
v.set(v.indexOf(oldval), newval);
return v;
});
}
Java utilizes the monitor-concept to ensure thread-safety when needed. Simply put, critical variables are treated as a encloses space, called the monitor. When a thread calls something containing critical variables, he gets control over the monitor. If another thread wants to enter the monitor now, he has to wait until the first thread leaves the critical space.
You can mark a method as critical space by using the
synchronizedkeyword. Example:public synchronized void doSomething() {}This ensures that only one thread can use the method. Be aware that there are alternate ways to ensure thread-safety, such as manually placed locks.
Now to your concrete example, modifyelement should be synchronized, since there could be possible side effects if multiple threads call it at the same time.
I hope that this helps. :)
Regards.