緩存與單例

分析這部分代碼:涉及哪些高并發(fā)的問題

    private Cache<StringWrapper, AtomicReference<ConfigClient>> mtConfigClientCache = CacheBuilder.newBuilder()
            .expireAfterWrite(7, TimeUnit.DAYS)
            .maximumSize(2000)
            .build();
    private final Map<String, StringWrapper> key2LockKey = new ConcurrentHashMap<String, StringWrapper>();

    private LoadingCache<String, MtConfigClient> mtConfigClientLoadingCache = CacheBuilder.newBuilder()
            .expireAfterWrite(7, TimeUnit.DAYS)
            .maximumSize(2000)
            .build(new CacheLoader<String, MtConfigClient>() {
                @Override
                public ConfigClient load(String key) throws Exception {
                    return buildClient(key);
                }
            });

    private ConfigClient getMccClient(String appKey) {
        return this.getMccClientByLoader(appKey);
    }

    private ConfigClient getMccClient2(String appKey) {
        final StringWrapper appKeyLock = key2LockKey.computeIfAbsent(appKey, StringWrapper::new);
        // appKey should not be used again,we force appKey = null to remind others here
        appKey = null;
        AtomicReference<MtConfigClient> mtConfigClientAtomicReference = mtConfigClientCache.getIfPresent(appKeyLock);
        if (mtConfigClientAtomicReference == null) { // mtConfigClientAtomicReference.get() == null, we wont allow this happen
            synchronized (appKeyLock) {
                mtConfigClientAtomicReference = mtConfigClientCache.getIfPresent(appKeyLock);
                if (mtConfigClientAtomicReference == null) {
                    try {
                        MtConfigClient mtConfigClientCreating = new MtConfigClient();
                        mtConfigClientCreating.setAppkey(appKeyLock.s);
                        mtConfigClientCreating.setModel("v2");
                        mtConfigClientCreating.setId("UpdateRateLimitConfig_" + System.nanoTime());
                        mtConfigClientCreating.init();
                        mtConfigClientAtomicReference = new AtomicReference<>();
                        mtConfigClientAtomicReference.set(mtConfigClientCreating);
                        this.mtConfigClientCache.put(appKeyLock, mtConfigClientAtomicReference);
                    } catch (Exception ex) {
                        LOGGER.info("mcc客戶端初始化失敗:", ex);
                    }
                }
            }
        }
        return Optional.ofNullable(this.mtConfigClientCache.getIfPresent(appKeyLock))
                .orElseGet(() -> null)
                .get();
    }

    private MtConfigClient getMccClientByLoader(String appKey) {
        try {
            return this.mtConfigClientLoadingCache.get(appKey);
        } catch (ExecutionException e) {
            LOGGER.error("獲取mcc客戶端失敗", e);
            return null;
        }
    }

    private MtConfigClient buildMccClient(String appKey) {
        try {
            MtConfigClient mtConfigClientCreating = new MtConfigClient();
            mtConfigClientCreating.setAppkey(appKey);
            mtConfigClientCreating.setModel("v2");
            mtConfigClientCreating.setId("UpdateRateLimitConfig_" + System.nanoTime());
            mtConfigClientCreating.init();
            return mtConfigClientCreating;
        }catch (Exception ex) {
            LOGGER.error("mcc客戶端初始化失敗:", ex);
            throw ex;
        }
    }


    static class StringWrapper {
        public String s;
        public StringWrapper(String s) {
            this.s = s;
        }
    }

這已經(jīng)是修改后的代碼,原先的代碼有單例模式的典型錯誤,在將 client 放到cache之前,在做init操作,但是init操作耗時較長,約9s。這就導致其他線程拿到的是,未初始化完成的client。

這里的修改優(yōu)化一個是: 使用 LoadingCache,這是單線程加載的,有他就夠了。
如果不想用cache,第二種優(yōu)化方式是:
final StringWrapper appKeyLock = key2LockKey.computeIfAbsent(appKey, StringWrapper::new);
想要針對每個key來創(chuàng)建單例,可以把他們轉化到同一個對象,同時,使用AtomicReference<MtConfigClient> 來保證init方法一定會執(zhí)行完之后,才會執(zhí)行放到map里,對其他線程可見,因為AtomicReference的內部值引用是 volatile,有防止重排序的語意。

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容