Home > Java > javaTutorial > How to use HashMap to cache data in Java singleton mode

How to use HashMap to cache data in Java singleton mode

WBOY
Release: 2023-05-13 09:43:14
forward
1144 people have browsed it

1. What is the singleton pattern?

The singleton mode is an object creation mode that is used to generate a specific instance of an object. It can ensure that only one instance of a class in the system is generated. The singleton implemented in Java is within the scope of a virtual machine. Because the function of loading a class belongs to the virtual machine, a virtual machine will create an instance of the class when it loads the singleton class through its own ClassLoad. In the Java language, such behavior can bring two major benefits:

1. For frequently used objects, the time spent on creating objects can be omitted, which is very considerable for those heavyweight objects. A system overhead;

2. As the number of new operations is reduced, the frequency of use of system memory will also be reduced, which will reduce GC pressure and shorten GC pause time.

Therefore, for key components of the system and frequently used objects, using the singleton pattern can effectively improve the performance of the system. The core of the singleton pattern is to return a unique object instance through an interface. The first problem is to take back the permission to create instances, let the class itself be responsible for the creation of instances of its own class, and then let this class provide external methods for accessing instances of this class

2. Singleton Pattern combined with HashMap to implement caching

1. Test results

How to use HashMap to cache data in Java singleton mode

2. The code is as follows

JavaBean

public class People {

    private String name;

    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "People{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
Copy after login

Cache tool class

import java.util.HashMap;
import java.util.Map;

public class CacheSingletonUtil {

    private static volatile CacheSingletonUtil cacheSingletonUtil;
    private static Map<String,Object> cacheSingletonMap;

    public static final String PEOPLE_LIST_KEY = "peopleList";

    private CacheSingletonUtil(){
        cacheSingletonMap = new HashMap<String, Object>();
    }

    /*
     * 单例模式有两种类型
     * 懒汉式:在真正需要使用对象时才去创建该单例类对象
     * 饿汉式:在类加载时已经创建好该单例对象,等待被程序使用
     */

    // 懒汉式单例模式
    public static CacheSingletonUtil getInstance(){
        if (cacheSingletonUtil == null){// 线程A和线程B同时看到cacheSingletonUtil = null,如果不为null,则直接返回cacheSingletonUtil
            synchronized (CacheSingletonUtil.class) {// 线程A或线程B获得该锁进行初始化
                if (cacheSingletonUtil == null) {// 其中一个线程进入该分支,另外一个线程则不会进入该分支
                    cacheSingletonUtil = new CacheSingletonUtil();
                }
            }
        }
        return cacheSingletonUtil;
    }

    /**
     * 添加到内存
     */
    public void addCacheData(String key,Object obj){
        cacheSingletonMap.put(key,obj);
    }

    /**
     * 从内存中取出
     */
    public Object getCacheData(String key){
        return cacheSingletonMap.get(key);
    }

    /**
     * 从内存中清除
     */
    public void removeCacheData(String key){
        cacheSingletonMap.remove(key);
    }

}
Copy after login

Test class

import org.apache.commons.collections.CollectionUtils;
import java.util.ArrayList;
import java.util.List;

public class CacheSingletonTest {

    public static void main(String[] args) {
        //测试查询
        testQuery();
    }

    private static void testQuery () {
        System.out.println("第一次查询开始");
        query();
        System.out.println("第一次查询结束");

        System.out.println("=============");

        System.out.println("第二次查询开始");
        query();
        System.out.println("第二次查询结束");
    }

    /*
     * 查询数据
     */
    private static List<People> query() {
        List<People> peopleList = null;

        List<People> cacheData = (List<People>) CacheSingletonUtil.getInstance().getCacheData(CacheSingletonUtil.PEOPLE_LIST_KEY);

        if (CollectionUtils.isNotEmpty(cacheData)) {
            System.out.println("从内存中读取");
            peopleList = cacheData;
        } else {
            System.out.println("从数据库中读取");
            peopleList = getData();
            // 添加到内存中
            CacheSingletonUtil.getInstance().addCacheData(CacheSingletonUtil.PEOPLE_LIST_KEY, peopleList);
        }

        for (People people : peopleList) {
            System.out.println("name : " + people.getName() + " age : " + people.getAge());
        }

        return peopleList;
    }

    /*
     * 删除数据
     */
    private void deleteCache () {
        CacheSingletonUtil.getInstance().removeCacheData(CacheSingletonUtil.PEOPLE_LIST_KEY);
    }

    private static List<People> getData() {
        People p1 = new People();
        p1.setName("Jack");
        p1.setAge(25);

        People p2 = new People();
        p2.setName("Brown");
        p2.setAge(28);

        List<People> peopleList = new ArrayList<>();
        peopleList.add(p1);
        peopleList.add(p2);

        return peopleList;
    }
}
Copy after login

The above is the detailed content of How to use HashMap to cache data in Java singleton mode. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template