I am trying to browse through Spring Source Code (5.2.8.RELEASE), and found the following code.
package org.springframework.core;
public class SimpleAliasRegistry implements AliasRegistry {
/** Map from alias to canonical name. */
private final Map<String, String> aliasMap = new ConcurrentHashMap<>(16);
@Override
public void removeAlias(String alias) {
synchronized (this.aliasMap) { // what if we remove such synchronized line ?
String name = this.aliasMap.remove(alias);
if (name == null) {
throw new IllegalStateException("No alias '" + alias + "' registered");
}
}
}
}
But what I uncertain is the reason why there is a synchronized keyword in removeAlias method, is it really necessary? What if we remove the synchronized keyword? What will happen?
Here is my thought.
ConcurrentHashMap
should be thread safe when we are calling its provided method, like put
, get
and remove
. And we need to use synchronized
to lock the object only when we are performing multiple actions here, like having get first then put or remove. But we want to make the block run without interuption.
Is my thought wrong, or is there any reason why Spring removeAlias
method is designed in such way, many thanks.
Update
I also found the time when it is updated, where the developer intentionally do it in this way, when fixing the issue, SimpleAliasRegistry registerAlias not atomic
, and here is the reason he wrote out.
I've guarded registerAlias and removeAlias with synchronization, allowing the existing synchronized resolveAliases method and others to reliably see consistent state.
However, I just think synchronized in registerAlias is neccessary but still not convince why one need to do synchronized
in
removeAlias method, can someone explain to me please?
Source: https://github.com/spring-projects/spring-framework/issues/21119 [Issue]
Source: https://github.com/spring-projects/spring-framework/commit/1b1a69a144f657d46c752f1c017f64d3302891d2 [Changes for that issue]