Home  >  Article  >  Java  >  Java and the Mystery of Disappearing Memory!

Java and the Mystery of Disappearing Memory!

Susan Sarandon
Susan SarandonOriginal
2024-11-04 10:56:02695browse

In the magical land of Java Land there lived a little robot named JVM-bot. The JVM-bot had a very important job: keep track of memory! The thing is, memory in Java Land was like a big cookie jar and everyone wanted a piece of it! Therefore, JVM-bot had to make sure that there was enough for everyone.

Magic indicators: totalMemory, freeMemory and maxMemory!

JVM-bot had three special indicators - tools to monitor all memory:

Java и Тайна Исчезающей Памяти!

totalMemory - This indicator showed the JVM-bot how many cookies (or memory) it already holds. This method shows the current amount of memory allocated by the JVM, which is useful for understanding the current load. Essentially, totalMemory is the memory “budget” that we already have in our pocket to use.
freeMemory - This one told him how many cookies were left in his jar (in the memory he already had). This method shows the amount of memory that can still be used within totalMemory. For example, if totalMemory is 500 MB and freeMemory is 200 MB, this means that 300 MB are already taken. This method helps us understand how much free memory there is right now, and when we should think about optimizing.
maxMemory - And this is the largest indicator of all! It showed the maximum number of cookies that JVM-bot could ever have. If it was full, you cannot add more cookies! For example, if you have the maximum set to 1024 MB, this is the upper limit, and once it is reached, the JVM will start using virtual cookies (memory), which will noticeably reduce performance.
Here is a code example showing how JVM-bot could use these indicators:

public class MemoryExample {
    public static void main(String[] args) {
        Runtime runtime = Runtime.getRuntime();

        // Получаем текущую память
        long totalMemory = runtime.totalMemory(); // Общее количество памяти
        long freeMemory = runtime.freeMemory();   // Свободная память
        long maxMemory = runtime.maxMemory();     // Максимально доступная память

        System.out.println("Общая память: " + totalMemory + " байт");
        System.out.println("Свободная память: " + freeMemory + " байт");
        System.out.println("Максимальная память: " + maxMemory + " байт");
    }
}

JVM-bot liked to think of itself as a cookie (memory) guardian, using its indicators to keep an eye on the precious crumbs left behind.

Entry: Mischievous Algorithm Gremlins!

One sunny day, JVM-bot was just minding its own business, monitoring its indicators, when suddenly... BAM! A bunch of nimble little Algorithm Gremlins have appeared! These gremlins loved cookies as much as the JVM-bot, and they were hungry!

They started devouring the JVM-bot cookies, taking a bite here and there. JVM-bot's freeMemory indicator began to fall rapidly when the gremlins ate the cookies!

Java и Тайна Исчезающей Памяти!

"Oh no!" JVM-bot exclaimed, rubbing his robotic head. "If these gremlins eat too many cookies, there won't be enough left for the rest of Java Land!"

Measuring Gremlin Appetites

JVM-bot has a brilliant idea! He uses his memory meters to see how many cookies the gremlins eat.

The JVM-bot first looked into freeMemory to check how many cookies it had left before the gremlins started feasting on it.

long initialFreeMemory = runtime.freeMemory();
System.out.println("Свободная память перед едой гремлинов: " + initialFreeMemory + " байт");

Then he said, "Okay, Gremlins, let's see what you can do!" and let them run free, biting off cookies.

After the gremlins had eaten, JVM-bot checked freeMemory again:

long remainingFreeMemory = runtime.freeMemory();
System.out.println("Свободная память после еды гремлинов: " + remainingFreeMemory + " байт");

Finally, JVM-bot did the calculations to figure out how many cookies were missing. It was a memory that the gremlins swallowed!

long consumedMemory = initialFreeMemory - remainingFreeMemory;
System.out.println("Съеденная память: " + consumedMemory + " байт");

Super Memory Indicator JVM-bot!

To keep track of everything, JVM-bot built itself a Memory Indicator! It looked like a cookie jar with colored sections:

Green for cookies that have already been eaten (Memory Used).
Blue for the cookies that are still safe in the jar (Free Memory).
Gray for cookies that may never bake (Maximum Memory).
This way the JVM-bot could keep an eye on everything and tell when it was time to bake more cookies!

Big Red Button "GC" - JVM-bot's Secret Weapon!

Java и Тайна Исчезающей Памяти!
And finally, JVM-bot had a big red button that said GC (short for Garbage Collection, of course!). This was his emergency cookie peeling tool. If things were getting out of hand and the gremlins were leaving crumbs everywhere, the JVM-bot would press that button and whoop! - all the crumbs disappeared, leaving the JVM-bot with clean, fresh memory again.

Example code to call the garbage collector:

public class MemoryExample {
    public static void main(String[] args) {
        Runtime runtime = Runtime.getRuntime();

        // Получаем текущую память
        long totalMemory = runtime.totalMemory(); // Общее количество памяти
        long freeMemory = runtime.freeMemory();   // Свободная память
        long maxMemory = runtime.maxMemory();     // Максимально доступная память

        System.out.println("Общая память: " + totalMemory + " байт");
        System.out.println("Свободная память: " + freeMemory + " байт");
        System.out.println("Максимальная память: " + maxMemory + " байт");
    }
}

Tips from JVM-bot: How to Keep Memory Gremlins Under Control!

To keep memory safe, JVM-bot has a few tricks:

  • Press the GC button before measuring to avoid any extra crumbs. Clearing debris before taking measurements helps obtain more accurate results. This, of course, is not always necessary, but it is useful for measurement accuracy.

  • Don't measure too often! JVM-bot measures only when it is really necessary (avoid measuring in a loop), otherwise its indicators may wear out. Accessing memory too frequently through Runtime can create small delays. Instead, take single measurements at the beginning and end of the algorithm.

  • Use friendly units like megabytes (MB) so everyone can understand.

How to measure memory consumption of an algorithm?

Java и Тайна Исчезающей Памяти!
To measure how much memory a specific piece of code, such as an algorithm, takes in memory, we need a little trick:

We measure the initial memory before executing the code.
We execute our algorithm.
We measure memory after execution.
We find the difference between the measurements.
The code example below will demonstrate how this can be done:

public class MemoryExample {
    public static void main(String[] args) {
        Runtime runtime = Runtime.getRuntime();

        // Получаем текущую память
        long totalMemory = runtime.totalMemory(); // Общее количество памяти
        long freeMemory = runtime.freeMemory();   // Свободная память
        long maxMemory = runtime.maxMemory();     // Максимально доступная память

        System.out.println("Общая память: " + totalMemory + " байт");
        System.out.println("Свободная память: " + freeMemory + " байт");
        System.out.println("Максимальная память: " + maxMemory + " байт");
    }
}

So JVM-bot became the hero of Java Land, protecting the cookie (or memory) for everyone, no matter how many gremlins tried to eat it. Remember: with JVM-bot and its memory indicators, there will always be enough cookies for everyone in Java Land! ?

The above is the detailed content of Java and the Mystery of Disappearing Memory!. For more information, please follow other related articles on the PHP Chinese website!

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