当前位置:网站首页>Multithreading tutorial (XXIII) thread safety without lock

Multithreading tutorial (XXIII) thread safety without lock

2022-06-11 05:29:00 Have you become a great God today

Multithreading tutorial ( 23 ) Realize thread safety without lock

Title Description :

Total 10000 element ,1000 Personal withdrawal , Per person 10 block , The balance after withdrawal is just 0.

Lock method

class AccountUnsafe implements Account {
    
    private Integer balance;
    public AccountUnsafe(Integer balance) {
    
        this.balance = balance;
    }
    @Override
    public synchronized Integer getBalance() {
    
        return balance;
    }
    @Override
    public synchronized void withdraw(Integer amount) {
    
        balance -= amount;
    }
}

The result is :

0 cost: 399 ms		

Lock free solutions

class AccountSafe implements Account {
    
    private AtomicInteger balance;
    public AccountSafe(Integer balance) {
    
        this.balance = new AtomicInteger(balance);
    }
    @Override
    public Integer getBalance() {
    
        return balance.get();
    }
    @Override
    public void withdraw(Integer amount) {
    
        while (true) {
    
            int prev = balance.get();
            int next = prev - amount;
            if (balance.compareAndSet(prev, next)) {
    
                break;
            }
        }
        //  It can be simplified to the following method 
        // balance.addAndGet(-1 * amount);
    }
}

Execute test code

public static void main(String[] args) {
    
    Account.demo(new AccountSafe(10000));
}

The result of a certain execution

0 cost: 302 ms

In fact, the lock free solution is to use cas, Compare the internal variables of the thread with the variables of the main thread before assigning values , Assign values at the same time , Avoid the use of locks

However, this scheme is suitable for a small number of threads , Because there are too many threads cas Will never succeed , Reduce performance .

原网站

版权声明
本文为[Have you become a great God today]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203020539055881.html