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

Updating the Tomcat version in the Debian system generally includes the following process: Before performing the update operation, be sure to do a complete backup of the existing Tomcat environment. This covers the /opt/tomcat folder and its related configuration documents, such as server.xml, context.xml, and web.xml. The backup task can be completed through the following command: sudocp-r/opt/tomcat/opt/tomcat_backup Get the new version Tomcat Go to ApacheTomcat's official website to download the latest version. According to your Debian system

C drive can expand capacity in five ways: 1. Use Windows disk management tools to expand the volume, but there must be unallocated space; 2. Use third-party software such as EaseUS or AOMEI to adjust the partition size; 3. Use Diskpart command line tools to expand the C drive, suitable for users who are familiar with the command line; 4. Repartition and format the hard disk, but it will cause data loss and data needs to be backed up; 5. Use external storage devices as C drive expansion, transfer folders through symbolic links or modification of the registry.

To develop a complete Python Web application, follow these steps: 1. Choose the appropriate framework, such as Django or Flask. 2. Integrate databases and use ORMs such as SQLAlchemy. 3. Design the front-end and use Vue or React. 4. Perform the test, use pytest or unittest. 5. Deploy applications, use Docker and platforms such as Heroku or AWS. Through these steps, powerful and efficient web applications can be built.

[Common Directory Description] Directory/bin stores binary executable files (ls, cat, mkdir, etc.), and common commands are generally here. /etc stores system management and configuration files/home stores all user files. The root directory of the user's home directory is the basis of the user's home directory. For example, the home directory of the user user is /home/user. You can use ~user to represent /usr to store system applications. The more important directory /usr/local Local system administrator software installation directory (install system-level applications). This is the largest directory, and almost all the applications and files to be used are in this directory. /usr/x11r6?Directory for storing x?window/usr/bin?Many

Create a SQLite database in Python using the sqlite3 module. The steps are as follows: 1. Connect to the database, 2. Create a cursor object, 3. Create a table, 4. Submit a transaction, 5. Close the connection. This is not only simple and easy to do, but also includes optimizations and considerations such as using indexes and batch operations to improve performance.

The garbled problem in Java Chinese is mainly caused by inconsistent character encoding. The repair method includes ensuring the consistency of the system encoding and correctly handling encoding conversion. 1.Use UTF-8 encoding uniformly from files to databases and programs. 2. Clearly specify the encoding when reading the file, such as using BufferedReader and InputStreamReader. 3. Set the database character set, such as MySQL using the ALTERDATABASE statement. 4. Set Content-Type to text/html;charset=UTF-8 in HTTP requests and responses. 5. Pay attention to encoding consistency, conversion and debugging skills to ensure the correct processing of data.

For good reason, Blockdag focuses on buyer interests. Blockdag has raised an astonishing $265 million in 28 batches of its pre-sales As 2025 approaches, investors are steadily accumulating high-potential crypto projects. Whether it’s low-cost pre-sale coins that offer a lot of upside, or a blue chip network that prepares for critical upgrades, this moment provides a unique entry point. From fast scalability to flexible modular blockchain architecture, these four outstanding names have attracted attention throughout the market. Analysts and early adopters are watching closely, calling them the best crypto coins to buy short-term gains and long-term value now. 1. BlockDag (BDAG): 7 days left

Java middleware is a software that connects operating systems and application software, providing general services to help developers focus on business logic. Typical applications include: 1. Web server (such as Tomcat and Jetty), which handles HTTP requests; 2. Message queue (such as Kafka and RabbitMQ), which handles asynchronous communication; 3. Transaction management (such as SpringTransaction), which ensures data consistency; 4. ORM framework (such as Hibernate and MyBatis), which simplifies database operations.
