1.减少锁的持有时间,将不需要锁的操作从同步代码块的移除。
- //可以优化的代码
- class AttributeStore{
- private final Map<String,String> attributes=new HashMap<String,String>();
- public synchronized boolean userLocationMatches(String username,String regex){
- String key="user."+username;
- String location=attributes.get(key);
- if(location==null)
- return false;
- else
- return Pattern.matches(regex,location);
- }
- }
- //优化之后的代码
- class AttributeStore{
- private final Map<String,String> attributes=new HashMap<String,String>();
- public boolean userLocationMatches(String username,String regex){
- String key="user."+username;
- String location;
- synchronized (this) {
- location=attributes.get(key);
- }
- if(location==null)
- return false;
- else
- return Pattern.matches(regex,location);
- }
- }
2.降低锁的粒度
- //可以锁分解的代码
- class ServerStatus{
- private Set<String> users;
- private Set<String> queries;
- public synchronized void addUser(String user){
- users.add(user);
- }
- public synchronized void removeUser(String user){
- users.remove(user);
- }
- public synchronized void addQuery(String query){
- queries.add(query);
- }
- public synchronized void removeQuery(String query){
- queries.remove(query);
- }
- }
- //优化后的代码
- class ServerStatus{
- private Set<String> users;
- private Set<String> queries;
- public void addUser(String user){
- synchronized (users) {
- users.add(user);
- }
- }
- public void removeUser(String user){
- synchronized (users) {
- users.remove(user);
- }
- }
- public void addQuery(String query){
- synchronized (queries) {
- queries.add(query);
- }
- }
- public void removeQuery(String query){
- synchronized (queries) {
- queries.remove(query);
- }
- }
- }