Home Java javaTutorial Java cache data loss: Why can't data be retrieved from cache?

Java cache data loss: Why can't data be retrieved from cache?

Apr 19, 2025 pm 02:57 PM
tomcat data lost spring container red

Java cache data loss: Why can't data be retrieved from cache?

Java 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:

  1. Static methods and singletons: scenarioBuffer class uses the static method getBAsset and the static variable assetBuffer , as well as getInstance() 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.
  2. Dependency injection is missing: Getting scenarioBuffer instance does not use Spring's dependency injection, but uses getInstance() method, which reduces the maintainability and testability of the code.
  3. Initialization method: Although it is feasible to initialize the cache using ApplicationRunner , the @PostConstruct annotation or InitializingBean 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>
Copy after login

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>
Copy after login

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Using Dicr/Yii2-Google to integrate Google API in YII2 Using Dicr/Yii2-Google to integrate Google API in YII2 Apr 18, 2025 am 11:54 AM

VprocesserazrabotkiveB-enclosed, Мнепришлостольностьсясзадачейтерациигооглапидляпапакробоглесхетсigootrive. LEAVALLYSUMBALLANCEFRIABLANCEFAUMDOPTOMATIFICATION, ČtookazaLovnetakProsto, Kakaožidal.Posenesko

How to use the Redis cache solution to efficiently realize the requirements of product ranking list? How to use the Redis cache solution to efficiently realize the requirements of product ranking list? Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

Title: How to use Composer to solve distributed locking problems Title: How to use Composer to solve distributed locking problems Apr 18, 2025 am 08:39 AM

Summary Description: Distributed locking is a key tool for ensuring data consistency when developing high concurrency applications. This article will start from a practical case and introduce in detail how to use Composer to install and use the dino-ma/distributed-lock library to solve the distributed lock problem and ensure the security and efficiency of the system.

How to build a website for wordpress host How to build a website for wordpress host Apr 20, 2025 am 11:12 AM

To build a website using WordPress hosting, you need to: select a reliable hosting provider. Buy a domain name. Set up a WordPress hosting account. Select a topic. Add pages and articles. Install the plug-in. Customize your website. Publish your website.

What should I do if the Redis cache of OAuth2Authorization object fails in Spring Boot? What should I do if the Redis cache of OAuth2Authorization object fails in Spring Boot? Apr 19, 2025 pm 08:03 PM

In SpringBoot, use Redis to cache OAuth2Authorization object. In SpringBoot application, use SpringSecurityOAuth2AuthorizationServer...

What is the reason why the browser does not respond after the WebSocket server returns 401? How to solve it? What is the reason why the browser does not respond after the WebSocket server returns 401? How to solve it? Apr 19, 2025 pm 02:21 PM

The browser's unresponsive method after the WebSocket server returns 401. When using Netty to develop a WebSocket server, you often encounter the need to verify the token. �...

Why is the return value empty when using RedisTemplate for batch query? Why is the return value empty when using RedisTemplate for batch query? Apr 19, 2025 pm 10:15 PM

Why is the return value empty when using RedisTemplate for batch query? When using RedisTemplate for batch query operations, you may encounter the returned results...

See all articles