multithreading - Synchronization of Nested Data Structures between Threads in Java -
i have cache implementation this:
class x { private final map<string, concurrentmap<string, string>> structure = new hashmap...(); public string getvalue(string context, string id) { // assume example there innner map final concurrentmap<string, string> innerstructure = structure.get(context); string value = innerstructure.get(id); if(value == null) { synchronized(structure) { // can sure, inner map represent last updated // state thread? value = innerstructure.get(id); if(value == null) { value = getvaluefromsomeslowsource(id); innerstructure.put(id, value); } } } return value; } }
is implementation thread-safe? can sure last updated state thread inside synchronized block? behaviour change if use java.util.concurrent.reentrantlock instead of synchronized block, this:
... if(lock.trylock(3, seconds)) { try { value = innerstructure.get(id); if(value == null) { value = getvaluefromsomeslowsource(id); innerstructure.put(id, value); } } { lock.unlock(); } } ...
i know final instance members synchronized between threads, true objects held these members?
maybe dumb question, don't know how test sure, works on every os , every architecture.
for starters, isn't dumb question. synchronization hard right, , don't profess expert in it.
in program, @ indicated context, yes, can assume string
you're getting updated version. however, code still not safe because reading value map
outside of synchronized
block. if read occurs @ same time map
having value inserted it, you're not guaranteed sensible value. know on @ least implementations, can cause infinite loop due weirdness in implementation.
the short version should not have structure read or written multiple threads unless guard synchronization primitive synchronized
or lock, or unless structure designed lock-free concurrenthashmap
.
you indeed use reentrantlock
in case guard access structure , timed wait, if you'd have guarantee reads of structure guarded same lock. otherwise risk multiple threads seeing inconsistent or corrupted data.
Comments
Post a Comment