有三种方式可以降低锁的竞争程度,减少锁的持有时间,降低锁的请求频率,使用带有协调机制的独占锁
(1) 缩小锁的范围
public class AttributeStore{ private final Map<String,String> attribute = new HashMap<>(); public synchronized boolean userLocationMatched(String name,String regex){ String key = "users"+name String location = attributes.get(key); if(location == null){ return false; }else{ return Pattern.matches(regex,location); } } } public class BAttributesStore{ ... public boolean userLocationMatches(String name,String regex){ String key = "users"+name; String location; synchronized(this){ location = attrinutes.get(key); } if(location == null){ return false; }else{ return Pattern.matches(regex,location); } } } 减小锁粒度 ```java public class ServerStatus{ public final Set<String> users; public final Set<String> queries; ... public synchronized void addUser(String u){ users.add(u); } public synchronized void addQuery(String q){ queries.add(q); } } public class ServerStatus{ public final Set<String> users; public final Set<String> queryies; ... public void addUser(String u){ synchronized(users){ users.add(u); } } public void addQuery(String q){ synchronized(queries){ queries.add(q); } } }