使用FutureTask解決併發重複計算問題,提升執行效率

業務場景

現有一個消耗資源比較大的計算業務需要優化,如果是同一個計算業務,需要保證只被計算一次,後面再有此計算,則直接從緩存中讀取結果

用例圖

在這裏插入圖片描述

流程圖

在這裏插入圖片描述

類圖

在這裏插入圖片描述

具體代碼實現

接口

這裏主要涉及的兩個接口:

  • 計算接口:執行的計算邏輯
  • 緩存接口:執行的是緩存相關操作

計算接口

public interface Computer {
    Integer compute(String id);
}

緩存接口

public interface Cache {
    Integer query(String key);
    void save(String key, FutureTask<Integer> value);
}

具體業務代碼

實際計算類

public class ActualComputer implements Computer {
    @Override
    public Integer compute(String id) {
        System.out.println("用戶ID"+id+"正在計算");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return id.hashCode();
    }
}

ConcurrentHashMap實現的緩存類

public class HashMapCache implements Cache {

    private final static ConcurrentHashMap<String,Future<Integer>> cache = new ConcurrentHashMap<>();

    @Override
    public Integer query(String key) {
        try {
            Future<Integer> integerFuture = cache.get(key);
            if(integerFuture == null){
                return null;
            }
            return integerFuture.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void save(String key, FutureTask<Integer> value) {
        Future<Integer> integerFuture = cache.putIfAbsent(key, value);
        // 如果有值了 則不再計算  防止重複計算
        if(integerFuture == null){
            value.run();
        }
        // 非原子操作,最終還是會重複計算
//        cache.put(key,value);
//        value.run();
    }
}

使用裝飾器模式實現的計算裝飾類

public class DecorateComputer implements Computer{

    private Cache cache;

    private Computer computer;

    public DecorateComputer(Cache cache, Computer computer) {
        this.cache = cache;
        this.computer = computer;
    }

    @Override
    public Integer compute(String id) {
        Integer result =  cache.query(id);
        if(result == null){
            // 計算耗時的任務需要後置 防止線程重複執行計算 此時需要使用futureTask
            FutureTask<Integer> futureTask = new FutureTask<>(()->computer.compute(id));
            cache.save(id,futureTask);
            result =  cache.query(id);
        }
        System.out.println("用戶ID"+id+"計算結果:"+result);
        return result;
    }
}

入口主程序

public class Main {
    public static void main(String[] args) {
        ActualComputer actualComputer = new ActualComputer();
        HashMapCache hashMapCache = new HashMapCache();
        DecorateComputer decorateComputer = new DecorateComputer(hashMapCache, actualComputer);
        new Thread(()->decorateComputer.compute("jack")).start();
        new Thread(()->decorateComputer.compute("susan")).start();
        new Thread(()->decorateComputer.compute("jack")).start();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章