高并发下减少锁竞争
Posted 夏日的微笑
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了高并发下减少锁竞争相关的知识,希望对你有一定的参考价值。
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);
- }
- }
- }
以上是关于高并发下减少锁竞争的主要内容,如果未能解决你的问题,请参考以下文章