I am looking for clarification about synchronized blocks. Consider this class –
public class A{
Map map;
public getValue(String key){
return map.get(key);
}
public remove(String key){
synchronized(map){
map.remove(key);
}
}
}
A is a singleton. getValue is heavily accessed throughout the app by multiple threads. I am adding a new method, remove, that removes a key from the map. If remove is implemented as above,
- When a thread is in the synchronized block of the remove method, I assume it will acquire a lock on the map object. Does that mean other threads trying to access the map via the getValue method will be blocked? (I’d like them to.)
- When no thread is in the synchronized block of remove method, will threads accessing the getValue method function as usual i.e. not block each other? (I’d like that too).
I want the getValue threads to block only if there is a thread performing the remove operation.
The one rule of synchronized is that only one thread can be in a
synchronized(foo)block at a time, for the same foo. That’s the only rule ofsynchronized.Well, there’s some complicated stuff about memory barriers and the like, and a single thread can be in several nested
synchronized(foo)blocks for the samefooat the same time:… but the rule stated above is basically the key to understanding
synchronized.