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
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 + '}'; } }
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); } }
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; } }
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!

hashmap的扩容机制是:重新计算容量,用一个新的数组替换原来的数组。重新计算原数组的所有数据并插入一个新数组,然后指向新数组;如果数组在容量扩展前已达到最大值,则直接将阈值设置为最大整数返回。

如何使用HashMap类的put()方法将键值对插入到HashMap中HashMap是Java集合框架中的一个非常重要的类,它提供了一种存储键值对的方式。在实际开发中,我们经常需要向HashMap中插入键值对,通过使用HashMap类的put()方法可以很轻松地实现这一目标。HashMap的put()方法的签名如下:Vput(Kkey,Vvalue)

Java文档解读:HashMap类的containsKey()方法用法详解,需要具体代码示例引言:HashMap是Java中常用的一种数据结构,它提供了高效的存储和查找功能。其中的containsKey()方法用于判断HashMap中是否包含指定的键。本文将详细解读HashMap类的containsKey()方法的使用方式,并提供具体的代码示例。一、cont

1、说明Map基本上可以使用HashMap,但是HashMap有一个问题,那就是迭代HashMap的顺序不是HashMap放置的顺序,就是无序。HashMap的这个缺点往往会带来麻烦,因为有些场景我们期待一个有序的Map,这就是LinkedHashMap。2、区别实例publicstaticvoidmain(String[]args){Mapmap=newLinkedHashMap();map.put("apple","苹果");map.put("

一、单例模式是什么?单例模式是一种对象创建模式,它用于产生一个对象的具体实例,它可以确保系统中一个类只产生一个实例。Java里面实现的单例是一个虚拟机的范围,因为装载类的功能是虚拟机的,所以一个虚拟机在通过自己的ClassLoad装载实现单例类的时候就会创建一个类的实例。在Java语言中,这样的行为能带来两大好处:1.对于频繁使用的对象,可以省略创建对象所花费的时间,这对于那些重量级对象而言,是非常可观的一笔系统开销;2.由于new操作的次数减少,因而对系统内存的使用频率也会降低,这将减轻GC压

javaHashMap插入重复Key值要在HashMap中插入重复的值,首先需要弄清楚HashMap里面是怎么存放元素的。put方法Map里面存放的每一个元素都是key-value这样的键值对,而且都是通过put方法进行添加的,而且相同的key在Map中只会有一个与之关联的value存在。put方法在Map中的定义如下。Vput(Kkey,Vvalue);put()方法实现:首先hash(key)得到key的hashcode(),hashmap根据获得的hashcode找到要插入的位置所在的链,

JavaMap是Java标准库中常用的数据结构,它以键值对的形式存储数据。Map的性能对于应用程序的运行效率至关重要,如果Map的性能不佳,可能会导致应用程序运行缓慢,甚至崩溃。1.选择合适的Map实现Java提供了多种Map实现,包括HashMap、TreeMap和LinkedHashMap。每种Map实现都有其各自的优缺点,在选择Map实现时,需要根据应用程序的具体需求来选择合适的实现。HashMap:HashMap是最常用的Map实现,它使用哈希表来存储数据,具有较快的插入、删除和查找速度

Java使用HashMap类的putAll()函数将一个Map添加到另一个Map中Map是Java中常用的数据结构,用来表示键值对的集合。在Java的集合框架中,HashMap是一个常用的实现类。它提供了putAll()函数,用于将一个Map添加到另一个Map中,方便实现数据的合并和拷贝。本文将介绍putAll()函数的使用方法,并提供相应的代码示例。首先,


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Dreamweaver Mac version
Visual web development tools