Java cache data loss: Why can't data be retrieved from cache?
Apr 19, 2025 pm 02:57 PMJava cached data loss problem: Diagnosis and solutions
In Java applications, memory caching is a key strategy for improving performance. However, cached data loss is a common problem. This article will conduct a case analysis to explore the root causes of Java cached data in depth and provide effective optimization solutions.
Case background:
A project uses a class called scenarioBuffer
to cache about 160,000 asset
data into a HashMap. scenarioBuffer
class uses the @Component
annotation and provides a static method getBAsset
for data acquisition. When the application starts, scenarioBuffer
initializes the cache through ApplicationRunner
interface. However, during the run, the getBAsset
method frequently returns null values. What is even more confusing is that the server memory is in urgent need (only 100MB of available memory is left, the cache takes up 3GB, and the total memory is 8GB). After restarting the server and clearing the cache, the problem is temporarily solved.
Analysis of the root cause of the problem:
Despite allocating about 3GB of memory for Tomcat, insufficient server memory remains the main problem. When memory is insufficient, the JVM will trigger garbage collection and even force shutdown to release memory, causing cached data to be cleared.
Code flaws:
The original code has the following problems:
- Static methods and singletons:
scenarioBuffer
class uses the static methodgetBAsset
and the static variableassetBuffer
, as well asgetInstance()
method. In Spring-managed Beans, this is completely unnecessary. Spring containers themselves manage singletons of beans, static methods and variables increase code complexity and are difficult to unit test. - Dependency injection is missing: Getting
scenarioBuffer
instance does not use Spring's dependency injection, but usesgetInstance()
method, which reduces the maintainability and testability of the code. - Initialization method: Although it is feasible to initialize the cache using
ApplicationRunner
, the@PostConstruct
annotation orInitializingBean
interface is clearer and easier to understand.
Optimization solution:
It is recommended to use Spring's dependency injection and @PostConstruct
annotation optimization code:
Modified scenarioBuffer
class:
@Component public class scenarioBuffer implements IActionListener { @Autowired private IAssetService assetService; private map <string list> > assetBuffer = new HashMap(); @PostConstruct public void init() { List<asset> assetList = assetService.list(); assetBuffer.put("key", assetList); // Here you need to modify the key according to the actual situation } public List<asset> getBAsset(String groupId) { return assetBuffer.get(groupId); } }</asset></asset></string>
In the class that needs to use cache, inject scenarioBuffer
instance through @Autowired
:
@Service public class XxxService { @Autowired private ScenarioBuffer scenarioBuffer; public void xxx() { List<asset> asset = scenarioBuffer.getBAsset("xxx"); // Here you need to modify the groupId according to the actual situation // ... } }</asset>
These modifications make the code more concise, easy to maintain and test, and avoid problems caused by static methods and variables.
In addition, you need to pay attention to the server memory usage. If memory is often insufficient, consider increasing server memory or optimizing programs to reduce memory usage. Although Redis is not considered for the time being in the case, in the long run, using distributed caches such as Redis can effectively alleviate memory pressure and improve performance.
The above is the detailed content of Java cache data loss: Why can't data be retrieved from cache?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics

With the vigorous development of the Internet, Korean comics (Korean comics) have won the love of more and more readers around the world with their exquisite painting style, fascinating plots and rich and diverse themes. If you want to travel anywhere, in the exciting Korean comic world, it is crucial to find a stable, free and resource-rich online reading platform. This article will provide you with a detailed guide to watching Korean comics online for free comics, helping you easily start your Korean comic journey.

The steps for troubleshooting and repairing Redis master-slave replication failures include: 1. Check the network connection and use ping or telnet to test connectivity; 2. Check the Redis configuration file to ensure that the replicaof and repl-timeout are set correctly; 3. Check the Redis log file and find error information; 4. If it is a network problem, try to restart the network device or switch the alternate path; 5. If it is a configuration problem, modify the configuration file; 6. If it is a data synchronization problem, use the SLAVEOF command to resync the data.

The quick location and processing steps for Redis cluster node failure are as follows: 1. Confirm the fault: Use the CLUSTERNODES command to view the node status. If the fail is displayed, the node will fail. 2. Determine the cause: Check the network, hardware, and configuration. Common problems include memory limits exceeding. 3. Repair and restore: Take measures based on the reasons, such as restarting the service, replacing the hardware or modifying the configuration. 4. Notes: Ensure data consistency, select appropriate failover policies, and establish monitoring and alarm systems.

Global cryptocurrency exchange Kucoin recently completed the formation of its European leadership team, appointing two highly-watched executives. This personnel change is part of Kucoin’s accelerated layout in the EU market, especially in response to the upcoming cryptoasset management regulations (MICAR). Currently, the company is advancing the relevant licensing process through the Austrian Financial Markets Authority (FMA) and introducing senior experts from traditional finance and crypto to strengthen its management. KucoinEU is currently actively communicating with the FMA to achieve full compliance operations with the goal of providing a complete cryptocurrency service within the European Economic Area (EEA). At this stage, the company has not yet conducted business within the EU or EEA and is about to obtain the corresponding license.

Redis and RabbitMQ each have their own advantages in performance and joint application scenarios. 1.Redis performs excellently in data reading and writing, with a latency of up to microseconds, suitable for high concurrency scenarios. 2.RabbitMQ focuses on messaging, latency at milliseconds, and supports multi-queue and consumer models. 3. In joint applications, Redis can be used for data storage, RabbitMQ handles asynchronous tasks, and improves system response speed and reliability.

The operation of modifying the table structure in phpMyAdmin mainly includes the following steps: 1. Enter the "Structure" page of the target database and table; 2. Click the "Change" button of the field to edit; 3. Modify the field name, type, length, whether it is allowed to be empty; 4. Adjust the field order or add new fields; 5. Confirm data compatibility and application layer logic before saving. When modifying, special attention should be paid to the compatibility of primary keys, index fields and existing data to avoid index failure or data loss. It is recommended to back up data before operation.

Effective solutions to the problem of split brain in Redis cluster include: 1) Network configuration optimization to ensure connection stability; 2) Node monitoring and fault detection, real-time monitoring with tools; 3) Failover mechanism, setting high thresholds to avoid multiple master nodes; 4) Data consistency guarantee, using replication function to synchronize data; 5) Manual intervention and recovery, and manual processing if necessary.

Short-term crypto trading is risky, but it is one of the most favorable ways to make money. If you know how to apply the right strategy, the most important thing is to choose the right crypto assets, you can make a considerable profit, which is exactly what we are going to discuss today. Which currencies can make investors profit in the short term? How to choose? Recommended short-term profitable currencies in the currency circle How to choose short-term trading cryptocurrencies? Short-term transactions involve buying cryptocurrencies and holding them for a short period of time, ranging from minutes to days. This approach is both promising, risky and time-consuming as you need to constantly monitor the market. But that's not all; when choosing the right crypto assets, you should also pay attention to the following points:
