The principle of garbage collection mechanism in Java __java

Source: Internet
Author: User
Tags garbage collection memory usage
The principle of the garbage collection mechanism in AVA recommend an article: the memory management of High-performance Java code more than you write the code, the GC simply can not recycle, the direct system hangs off.
	GC is a program that is not intelligent, he only reclaims the rubbish he thinks of, instead of recycling what you think of rubbish. GC Garbage Collection: Grabage Collection believes that people who have studied Java know what this means.
	But how does he work? First, when the JVM manages memory, it always has new objects and old objects for managing variables. The new object is the object that developer new, but because of the short life cycle, then the memory he occupies is not immediately released, but is marked as the old object, this time the object still exists for some time.
	The JVM then determines whether he is a garbage object and reclaims it. So we can know that the garbage memory is not used up immediately released, so it will produce a memory release is not timely phenomenon, thus reducing the use of memory. And when the process is vast. This phenomenon is more pronounced, and the work of GC also consumes resources.
	As a result, memory waste is also generated.
	The object lifecycle in the JVM talking about memory recycling: The life cycle of an object is generally divided into 7 phases: the creation phase, the application phase, the invisible phase, the unreachable stage, the collection phase, the end stage, and the release phase. Create phase: First, we look at the following two paragraph code: test1:for (int i=0; I "10000;
	i++) Object Obj=new object ();
	Test2:object Obj=null; for (int i=0; I "10000;
	i++) obj=new Object (); These two pieces of code are the same function, but obviously test2 performance is better than test1 performance, memory usage is high, this is why. The reason is simple, Test1 creates an object's temporary objects each time it executes a for loop, but these temporary objects are still a long time away because the JVM's GC cannot be destroyed immediately, while Test2 saves a reference to the object in memory without creating a large number of new temporary variables.
	Thus reducing the use of memory. In addition, do not initialize multiple times on the same object.
	For example: public class a{private Hashtable table = new Hashtable ();
	Public A () {table = new Hashtable ();
	This should be removed because the table is already initialized. This makes two new Hashtable, but only one is used. The other one is not referenced. And beIgnored. Waste of memory. And as a result of the two Times new operation.
	Also affects the speed at which code is executed.
	Application phase: that the object has at least one reference in the maintenance of him. Non-visual stage: That is, beyond the scope of the variable. Here's a good idea, because the JVM is not going to recycle at the GC, but to determine if the object is being maintained by another reference.
	So, at this point, if we use an object to Obj=null or obj.dosomething () and then mark it as empty, we can help the JVM discover the garbage object in time.
	Unreachable phase: a direct or indirect reference to the object is not found in the JVM.
	The collection phase, the end stage, the release phase: This is the collector's discovery that the object is unreachable, the Finalize method has been executed, or the object space has been reused. Java destructor: There may be no one to believe that Java has destructors. Yes, there is. Because all classes in Java inherit to the object class, and Finalize is a method of the object class, this method is similar to a C + + destructor in Java. In general, you can release objects in a class by overloading the Finalize method.
	such as: public class a{public Object A;
	Public A () {a = new Object;}
	protected void Finalize () throws java.lang.throwable{a = null;//is marked empty, the object Super.finalize () is disposed, and//The Finalize method in the superclass is called recursively.
	Of course, when the method is invoked is determined by the JVM ............... In general, we need to create a Destory method to explicitly invoke the method.
	Then in finalize the method is also invoked to implement the practice of double insurance. Since the creation of an object is recursive, that is, calling the constructor of the superclass first, and then recursively calling the constructor in turn, you should avoid initializing the variable in the constructor of the class, thus avoiding unnecessary memory consumption by unnecessarily creating objects.
	Of course here also see the advantages of the interface. Array creation: Because arrays need to be given a length, the phenomenon of an array that is too large or too small is often created when the number of data is indeterminate. Creates unnecessary memory waste, so you can tell the JVM to reclaim the memory in a timely fashion by means of a soft reference.
	(soft reference, specific search information). Example: Object obj = new char[10000000000000000];
	SoftReference ref = new SoftReference (obj); Shared Static storage space: We all know that static variables are shared while the program is running, so it is sometimes possible to save memory space by declaring some variables as static variables in order to save the memory artifacts. But because the static variable life cycle is very long, not easy to be recycled by the system, so the use of static variables to be reasonable, can not be used blindly.
	So as not to backfire.
	Therefore, it is recommended that you use the following: 1, the variable contains a large volume of objects, consuming too much memory.
	2, the variable contains an object that has a longer life cycle.
	3, the variable contains data stability. 4, the object instance of the class has a shared need for the objects contained in the variable.
	(That is, whether it needs to be a global variable). Object Reuse and GC: Sometimes, such as database manipulation objects, we all need to be used between different modules, so such objects need to be reused to improve performance.
	Also effectively avoids the performance degradation caused by repeatedly creating objects. In general, object pooling is a good idea.
	As follows: Public ABSTARCT class objectpool{private Hashtable locked,unlocked;
	Private long expirationtime;
	Abstract Object Create ();
	abstract void expire (Object o);
	abstract void Validate (Object o);
	Synchronized Object getObject () {...};
	synchronized void Freeobject (Object o) {...}; So we're done with a pool of objects that we can use to access the deleted objects in a corresponding way.
	To maintain this fast memory to improve memory reuse. Of course, you can also force the system to do garbage collection by calling System.GC ().
	Of course, the cost is to consume some CPU resources.
	Do not create objects in advance: Try to create objects when needed, duplicate allocations, and construct objects that can degrade performance by doing extra work for garbage collection. JVM Memory parameter tuning: Forced memory recycling has a negative impact on the system's automatic memory recovery mechanism, which increases the processing time of the system's automatic collection, so you should try to avoid explicitly using System.GC (), and JVM settings can improve system performance. For example: JAVA-XX:NEWSIZE=128M-XX:MAXNEWSIZE=128M-XX:SURVIVORRATIO=8-XMS512M-XMX512M can view the Java Help documentation specifically.
	We mainly introduce the performance improvement in program design. Other experience with memory management in Java programming: Depending on how the JVM's memory management works, there are some tricks and ways to make the JVM more efficient in GC processing.
	, which improves memory usage and shortens GC execution time. 1, free up references to unwanted objects as soon as possible. That is, you can speed up the work of the GC by setting null without using the object's reference.
	(Of course, if it's a return value ...) 2, use the Finalize function as little as possible, a function that Java gives programmers an opportunity to release objects or resources, but it increases the GC effort.
	3, if you need to use a picture, you can use soft to apply the type, and it can read the picture into memory as much as possible without causing outofmemory.
	4, attention to the data structure of the collection data type, often the more complex data structure, the greater the GC workload, processing more complex.
	5, try to avoid creating in the default constructor (constructor), initializing a large number of objects. 6, try to avoid forcing the system to do garbage collection.
	will increase the system to do garbage collection The final time to reduce performance.
	7, try to avoid an explicit application array, and if you have to apply an array, try to estimate the size of the array as accurately as possible. 8, if you are making a remote method call. To minimize the size of the objects being passed.
	or use instantaneous values to avoid unnecessary data transfer. 9, as far as possible in the appropriate use of object pooling to improve system can reduce memory overhead, of course, the object pool can not be too large, will backfire.

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.