Memory leaks and garbage collection mechanisms in Java

Source: Internet
Author: User

3 garbage collection mechanism

3.1 What is garbage?

garbage, in-memory garbage, which is void in memory but not automatically freed. In the Java language, a class object that is not referenced by a reference handle is most likely to become garbage. , there are a lot of garbage generation, there are 3 main types:

(1) When the scope of the object's reference handle is exceeded, the object referenced by the reference handle becomes garbage.

Cases:

Person p1 = new Person ();

...

The scope of the reference handle P1 is from definition to "}", and after executing all the code in the curly brace, the resulting person object becomes garbage because the handle to the object P1 has exceeded its scope, P1 is invalid, and the person object is no longer referenced by any handle.

(2) when the scope of the object's reference handle is not exceeded, the object referenced by the reference handle becomes garbage when the value of the reference handle is assigned to NULL.

Cases:

Person p1 = new Person ();

... ..

p1 = null;

....

After the execution of the "p1=null;" , the person object is no longer referenced by any handle, and becomes garbage, even though the handle P1 is still valid if it has not gone beyond its scope, but it has been assigned null and no longer points to any object. The P1 can then point to other person objects, because it has not yet exceeded its scope.

(3) When an anonymous object is created, it becomes garbage when the anonymous object is exhausted.

Cases:

New Person (); //Because it is an anonymous object, no reference handle points to it, which is garbage

New person (). print ();

When the print () method of an anonymous object is run, the object becomes garbage

......

Therefore, you should use as few anonymous objects as possible in your program.

3.2 Garbage Collection

During a Java program run, a garbage collector (garbage Collector, referred to as GC) is periodically called to check for objects that are no longer in use and to free up memory space they occupy. The garbage collector's recycling is irregular and may not start or start many times in the course of the program's operation. As a result, the garbage collector will automatically reclaim garbage as soon as the program code generates garbage, and it is likely that the garbage collector will not start at the end of the program. Therefore, the garbage collector does not completely avoid the problem of memory leaks.

on the other hand, garbage collection brings additional burden and space-time overhead to system resources. The less likely it is to be activated, the less likely it will be to bring the burden. Therefore, the garbage recycling strategy is also very important.

3.3 Recycling strategy for garbage collector

the memory garbage collection mechanism in different vendors and versions of Java virtual machines is not exactly the same, usually the newer version of the memory recycling mechanism is faster. While different Java virtual machines adopt different recycling strategies, there are two common types: copy-recycling strategy and self-reflection recycling strategy.

Replication Recycling Strategy: Pause the running program and then copy all objects that are being used from the heap memory A in which they reside to another heap of memory B, freeing up all the space in heap memory A, and the memory space occupied by those objects that are no longer in use will be freed. This method requires at least twice times the amount of memory needed to maintain the required memory space, which is suitable for more garbage cases. This recycling strategy is inefficient when the program produces only a small amount of garbage or no garbage.

Introspection Recycling strategy: First detect all objects in use and label them, such as using one to label the object being used, mark the object that is no longer in use with zero, and then release all memory spaces labeled 0. Because labeling increases the overhead of the system, this approach is still slow, especially in the case of more garbage, which is inefficient. This method is suitable for cases where there is less waste.

These two approaches are complementary, so in some Java virtual machines two ways are organically combined.

4 System.GC ()

since Java's garbage collector is not controlled by the programmer, and recycling is not regularly followed, the garbage collector is aroused, and sometimes even when the program terminates, the collector does not have the opportunity to start. Therefore, this garbage collection mechanism is not a very reliable mechanism. Because garbage can not be reclaimed in a timely manner, the memory space they occupy cannot be released, which can affect the performance of the program, and if a program generates large amounts of garbage without recycling, the recycling process becomes difficult. To solve this problem, Java provides a System.GC () method that forces the garbage collector to recycle garbage to reduce the probability of memory leaks occurring.

Example: Anonymous objects can produce garbage, if you are concerned that these garbage can not be collected in a timely manner, after using these anonymous objects, add a statement: System.GC (), forcing the garbage collector to recycle garbage.

Class TESTJC

{

Public Void Finalize ()

 {

System.out.println ("Free the Occupied memory ...");

 }

Public static void Main (String args[])

 {

new TESTJC ();

new TESTJC ();

new TESTJC ();

System.GC ();

System.out.println ("End of Program.");

 }

}

The running result of the program is:

End of program.

Free the occupied memory ...

Free the occupied memory ...

Free the occupied memory ...

System.GC () has a feature of calling the Finalize () method before the object is disposed of as garbage from memory, and releasing an object to call a Finalize () method . From the running results of the program can be seen: After the garbage collector starts, and does not necessarily start recycling garbage immediately, it is likely to wait a while to execute. This is because the garbage collection thread has a lower priority during the run of the program, and if there are threads that are higher priority than this thread, run these high priority threads first, and wait until those threads have finished executing before they are garbage collected . So the System.GC () method is just a "recommendation", it is recommended that Java virtual machines perform garbage collection, freeing up memory space, but when it is possible to recycle it can not be predicted.

If we put the "System.GC ();" Statement behind the second anonymous object statement, and then compile and execute it, we will find the result:

End of program.

Free the occupied memory ...

Free the occupied memory ...

this is because after the garbage collector is started, it can only detect garbage that the program runs before the garbage collector is forced to start, the Java Virtual Machine tries its best to reclaim garbage from discarded objects, and for garbage generated after starting the garbage collector, the probability of this thread being detected is very small. If they are not detected, they cannot be recycled.

Therefore, the garbage collector mechanism in Java and the System.GC () method do not completely avoid the problem of memory leaks, only minimizing the likelihood and extent of memory leaks.

5. Things to be aware of in Java programming

in order to improve the efficiency of garbage recovery, in practical applications, the following methods can be used to avoid memory leaks in Java to some extent.

(1) minimize the use of anonymous objects, use internal classes with caution

When an anonymous object is used, it becomes garbage, and in an inner class, a reference to an external class object is implied, and the reference cannot be automatically eliminated.

(2) in a program using the System.GC () method, use the Finalize () method sparingly

Because the System.GC () method calls the Finalize () method when reclaiming the memory space occupied by each object, any operation in this method increases the cost of garbage collection.

(3) use System.GC () method carefully to reduce the number of threads

You can explicitly call the System.GC () method in your program, but this method does not guarantee that all garbage is cleared. In addition, garbage collection is also a thread that consumes the resources of the system, and initiating garbage collection can also cause intermittent pauses. The more threads, the more likely the garbage collection thread hangs and restores, and the longer it takes, the more overhead the system will be .

Memory leaks and garbage collection mechanisms in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.