Java 使用单例模式双重校验处理全局缓存

本文介绍了一种使用内部类实现的单例模式双重校验机制,该机制用于高效地管理和缓存WarningInfoBean对象。通过静态内部类实现单例,确保了线程安全且避免了同步带来的性能损耗。
单例模式双重校验有两种方式
1.使用synchronized 
2.使用内部类 (推荐使用)

使用以下代码需简单修改

import com.harmonywisdom.ajproduct.ajproduct.mobile.bean.WarningInfoBean;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description 缓存处理
 * @Author WangKun
 * @Date 2019/12/18 18:09
 * @Version
 */
public class SingletonCacheUtil {


    // 缓存容器
    private static List<WarningInfoBean> alertCache = new ArrayList<>();

//    private volatile static SingletonCacheUtil instance = null;
//
//    private SingletonCacheUtil() {}
//    /**
//     * @Description 单例双重检验模式
//     * @throws
//     * @Return
//     * @Date 2019-12-19 11:17:56
//     * @Author WangKun
//     **/
//    public static SingletonCacheUtil getInstance() {
//        if (instance == null) {
//            synchronized (SingletonCacheUtil.class) {
//                if (instance == null) {
//                    instance = new SingletonCacheUtil();
//                }
//            }
//        }
//        return instance;
//    }


    private SingletonCacheUtil() {
    }

    /**
     * @Description 使用内部类实现单例双重检验模式
     * @throws
     * @Return
     * @Date 2019-12-19 11:17:56
     * @Author WangKun
     **/
    private static class singleton {
        private static SingletonCacheUtil singletonStatic = new SingletonCacheUtil();
    }

    /**
     * @param
     * @throws
     * @Description 实例化
     * @Return com.harmonywisdom.ajproduct.ajproduct.task.util.SingletonCacheUtil
     * @Date 2019-12-19 11:18:09
     * @Author WangKun
     **/
    public static SingletonCacheUtil getInstance() {
        return singleton.singletonStatic;
    }

    /**
     * @param
     * @throws
     * @Description 获取缓存
     * @Return java.util.List<java.lang.Object>
     * @Date 2019-12-19 11:17:34
     * @Author WangKun
     **/
    public List<WarningInfoBean> getAlertCacheInfoList() {
        return alertCache;
    }

    /**
     * @param info
     * @throws
     * @Description 添加数据
     * @Return void
     * @Date 2019-12-19 11:20:54
     * @Author WangKun
     **/
    public void addAlertCacheInfoList(WarningInfoBean info) {
        alertCache.add(info);
    }

    /**
     * @param
     * @throws
     * @Description 清楚缓存
     * @Return void
     * @Date 2019-12-19 11:22:10
     * @Author WangKun
     **/
    public void clearCacheList() {
        alertCache.clear();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值