【Java多线程】AtomicInteger使用

AtomicInteger 提供了线程安全的方法,一般用于多线程并发计数。


在今天遇到使用AtomicInteger的源码,发现它的逻辑有点漏洞,故写了以下代码抽象出大概逻辑,来验证自己的想法。


废话少说先上代码,UILCacheSizeTest该类提供指定大小上限sizeLimit,而以下代码时上限失效了。


存在该问题的原因是AtomicInteger 的方法是线程安全的,但UILCacheSizeTest的方法并非线程安全。这样的写法会让cacheSize被多线程重入。

从而导致实际的cacheSize会偶尔超出sizeLimit。感兴趣的朋友可以运行下代码。


解决方案很简单:就是一个方法内对cacheSize的操作都放进synchronize的同步块中。


import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;


public class UILCacheSizeTest implements Runnable{
    
    private static final int MAX_COUNT = 1000;


    private final int sizeLimit;
    
    private AtomicInteger cacheSize = new AtomicInteger();
    
    public UILCacheSizeTest(int sizeLimit) {
        this.sizeLimit = sizeLimit;
    }
    
    private int randomInt(int min, int max) {
        Random random = new Random();
        int s = random.nextInt(min+1) + max-min; 
        return s;
    }
    private int randomInner() {
        return randomInt(100, 200);
    }
    
    public void run() {
        int sizeToADD = randomInner();
        int curCacheSize = cacheSize.get();
        while (curCacheSize + sizeToADD > sizeLimit) {
            curCacheSize = cacheSize.addAndGet(-100);
        }
        cacheSize.addAndGet(sizeToADD);
        int newCacheSize = cacheSize.get();
        
        if (newCacheSize > sizeLimit) {
            System.out.println("confict = " + newCacheSize);
        }
    }
    
    public static void main(String[] args) {
        ThreadPoolExecutor exe = new ThreadPoolExecutor(10, 10, 3000, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(1000));
        UILCacheSizeTest runObj = new UILCacheSizeTest(1000);
        for (int i = 0; i < MAX_COUNT; i ++) {
            exe.execute(runObj);
        }
    }
}


你可能感兴趣的:(【Java多线程】AtomicInteger使用)