1. method parameter value passing 1.1 method parameter passing method parameters are divided into three types: 1, basic type; 2, string type; 3, reference type. Example:
Public void changeparam (int I, string STR, stringbuilder Sb, stringbuilder sb2) {I = 1; STR = "1"; sb. append ("1"); sb2 = new stringbuilder ("1") ;}@ testpublic void change () {int I = 0; string STR = "0 "; stringbuilder sb = new stringbuilder ("0"), sb2 = new stringbuilder ("0"); changeparam (I, STR, Sb, sb2); system. out. format ("I: %-3D STR: %-3 s SB: %-3 s sb2: %-3 s", I, STR, Sb, sb2);} result: i: 0 STR: 0 SB: 01 sb2: 0
After the change method is executed, I is still 0, STR is still 0, and Sb is changed to "01" for the following reasons:
- The parameter passing through the basic type method is in the form of a copy value, that is, the I variable in change is copied to the I of changeparam, but in fact the I of changeparam has the I value of change, however, no matter how I changes in changeparam, the I value of change will not be changed;
- Although string is a reference type, its own feature cannot be changed. To change the value of string, a new string is generated in Java, assign this value to STR, so there is no relationship between STR parameters and parameter passing, even in a method.
- There are two types of reference type parameters:
- SB reference. After Sb modifies the attribute in changeparam, Sb in change also changes because Sb references the same object in the change method and changeparam method, therefore, when they modify an object, it will naturally be reflected in all references to the object.
- Although sb2 calls the changeparam method, it also passes the reference of stringbuilder, but in changeparam, sb2 points to the new object again, therefore, the references in changeparam and change no longer point to the same object, so the changes between them do not affect each other.
1.2 problems that may occur when variable parameters are used improperly to pass values in methods in Java may cause problems. For problems that may occur when configurable parameters are used, first understand the basic concepts of methods, when calling a method in Java, the method name + parameter type under the type is used to identify which method is called. If the method name under the same class is the same, then the number of method parameters and parameters is the difference between the judgment method. The background implementation method is through the rtti mechanism during the call. You will take notes about the specific situation in the future. The variable parameter method is to receive the same type of parameters, but there is no fixed number, such as XX (integer... ARGs). An integer can be input multiple parameters and received as an array. As follows:
// After the parameter type is omitted, the variable parameter public void changeparam (string... ARGs) {system. out. println (arrays. deeptostring (ARGs); system. out. println (ARGs [0]);} @ testpublic void changeparamtest () {changeparam ("A"); changeparam ("A", "B", "C ");} result: [a] a [a, B, c]
Variable parameters may have the following problems:
/*** Variable parameters may cause problems * When the changeparam method parameter is Integer ARGs and integer... ARGs, the compiler is through * When the program calls the changparam method but only has one parameter, what I need to call at this time is an integer... the args Method * is considered to be the integer ARGs method that I call, and the method * @ Param ARGs */Public void changeparam (integer ARGs) {system. out. println ("INTEGER:" + ARGs);} public void changeparam (integer... ARGs) {system. out. println ("integer...: "+ ARGs);} // solution public void changeparam (long type, integer... ARGs) {for (integer VAL: ARGs) {system. out. println ("int:" + val) ;}@ testpublic void changeparamrun () {changeparam (1l, 1 );}
In this example, changeparam (integer ARGs) and changeparam (integer... ARGs) methods are different, but they were originally called (integer... (ARGs) method, but when only one value is passed, it will become the execution (integer ARGs) method. This is a serious problem. The execution result is inconsistent with the target method. The best solution is to set multiple parameters, which indicate differentiation. For example, (long type, integer... ARGs), the parameter type differentiation method. 2. Program initialization process
Public class helloa {public helloa () {system. out. println ("helloa") ;}{ system. out. println ("I'm a class");} static {system. out. println ("static a") ;}} public class hellob extends helloa {public hellob () {system. out. println ("hellob");} {system. out. println ("I'm B class");} static {system. out. println ("static B") ;}} public class test {public static void main (string [] ARGs) {New hellob () ;}} result: static astatic Bi'm a classhelloai' m B classhellob
The result is as follows: static areas of the parent class (static variables and static block content) "static areas of the current class (static variables and static block content) "parent class {} code block and member variable" parent class constructor "subclass {} code block and member variable" subclass constructor static region only executes initialization once, no matter how many objects are created, they are executed only once. 3. java garbage collection mechanism programmers both understand the importance of initialization and should also understand the cleaning work. A major advantage of Java is to help us handle initialization and runtime allocation of resources to programs, in addition, resources are cleared when program resources are tight to ensure healthy operation of the program. Fortunately, Java has helped us with these things. This is a "great help". We don't need to consider how to allocate memory and how to clean up memory when we get started with Java code, you only need to pay attention to the content of our own programs. Of course, to write better code in the future. It is necessary to know how to allocate and clear memory. 3.1 The effect of the Finalize method the Garbage Collector will recycle the objects generated in the heap through the new method, but some specially generated object Resources will never be cleared, such as static areas, you can use finalize to clean up. The Finalize method is to call the Finalize method before the next garbage collection. In the Finalize method, we can manually mark things that will not be cleared (for example, static variable objects will not be reclaimed by the garbage collector, and this variable can be set to null in finalize ), or set some strongly referenced objects to null so that the garbage collector can recycle these resources the next time it executes them. Code Simulation is implemented as follows:
Class handlertest {static handlertest staticbl = new handlertest (); // set the static variable Boolean checkedout = false; /*** override Finalize method * @ throws throwable */@ override protected void finalize () throws throwable {// control the cleaning condition and clear the content if (checkedout) {system. out. println ("execute cleanup");/*** the Java Garbage Collector only recycles new objects and places them in the heap. * The static area is not processed, you can use the Finalize method to process it, * and then recycle the next garbage collection */staticbl = NULL; super. finalize (); flag = false ;}@ override Public String tostring () {return "staticbl" ;}} static Boolean flag = true; @ testpublic void rungc () {While (FLAG) {handlertest handler = new handlertest (); handler. checkedout = true; handlertest handler2 = new handlertest (); system. out. println (handlertest. staticbl); system. result: staticblstaticblblstaticblstaticblstaticblstaticblblstaticbl clears staticbl, and cleans up staticbl.
In the preceding example, the staticbl variable of handlertest is not processed during normal garbage collection. The finalize () method is overwritten to make it null during garbage collection so that it can be recycled next time. However, the Finalize method is called by the garbage collector to put objects that are normally not recycled by the garbage collector and are no longer in use in finalize for cleanup, however, the garbage collector is executed when the garbage collector is executed, so the finalize execution time is uncertain, because the Java Virtual Machine is not facing the situation of memory depletion, it does not waste time executing garbage collection to restore memory.
In general, the Finalize method is not recommended.3.2 memory allocation the generation object will allocate memory for the object. The Java memory allocation method is like the queue form. According to Java programming ideas, it is like a conveyor belt, each allocation of an object, it moves one forward, and Java allocates memory much faster than C, but not exactly like a conveyor belt. When memory resources are exhausted, the Java Garbage Collector helps sort out the memory. Assume that there are a total of 10 spaces and eight are generated in sequence, but three spaces in the eight are no longer marked as garbage, if the generation continues, only two more instances can be generated. A maximum of seven valid instances (8-3 + 2) are generated. These three instances are useless, the more space you need, the more space you will waste. The garbage collector is also used to organize the conveyor belt. The purpose is to recycle useless garbage, that is, to mark the three above as garbage space, and sort the objects in the heap to make them compact, so that they can allocate more memory and improve the allocation efficiency.
Therefore, the garbage collector has a significant effect on improving the object creation speed.3.3 How does garbage collection work? The most important thing about garbage collection is to determine which objects are spam objects (no longer used objects) and which objects are in use and clear the spam objects, retain the objects that are still in use. The judgment is that the object is released and referenced. if the object is not referenced and bound, it indicates that the object is no longer likely to be used, and it is a junk object. The following is a simple description. Java's garbage collector is a very complex function and will have a chance to learn more in the future. 3.3.1 reference note technology JAVA does not use reference note technology, but you can simply understand what reference note technology is? An object may be bound by multiple references. If each reference is bound to an object, the reference counter is added with 1. If the reference of an object is out of scope or set to null, the reference value is reduced by 1, when the value is 0, it indicates that the object has no reference bound. It is equivalent to a spam object. Therefore, when the value is 0, the object is released immediately. Although the overhead of managing reference records is small, every generation of reference bound objects is executed. This overhead will continue throughout the life cycle of the program. However, there is a defect in the entire method. If there is a circular reference between objects, there may be "the object should be recycled, but the reference count is not zero", so it cannot be recycled. 3.3.2 The Idea of traversing the reference chain tracing object is as follows: any "active" object can be traced back to its reference in the stack or static storage area. Therefore, if you traverse all references from the stack and static storage area, you can find all the objects to which it is bound. For example, after you find an object bound to a reference, trace all referenced objects contained in the object. It is equivalent to a tree-like pyramid. From the previous layer of traversal, We can find all the "active" objects. Since all the objects found are active objects, and what is not found in turn is dead objects, they can be automatically recycled 3.3.3 After distinguishing live objects and dead objects, how is the garbage collector cleaned up? Different Virtual Machine versions have multiple processing methods, which are called "stop-and-Copy )"
Stop-copy:As the name suggests, this method is to pause the program first to avoid new spam and unexpected problems. By traversing the reference chain, we can find all "active" objects, all the surviving objects are copied from the current heap to another heap. When the objects are copied to the new heap, they are placed one by one, keeping them in a compact arrangement, in addition, the original reference is changed to the original object address in the new heap. Instead, all the data that has not been copied is rubbish, Which is cleared immediately.
The disadvantages of this method are as follows::
- We have to have two fully isolated stacks, and we have to move them between them. That is to say, if we need 100 space for the actual operation, we have to reserve this space, which is simply used for tamping, with low efficiency,
- Replication, when the program becomes stable, there is not much garbage produced, or even no garbage. Even so, the replication recycler will still copy all the memory to the other. If there are 100 objects, five of them are junk objects, you still have to move 95 objects to the other heap, only to clear the five spams. Performance Waste
Mark-and-sweep ):
To avoid wasting performance resources when the replication mode reduces the amount of garbage, some java virtual machines switch to another working mode when there is not much garbage, mark-and-sweep (mark-and-sweep). Generally, the Mark-sweep method is slow, but it is fast when processing a small amount of garbage. Mark-cleaning is also required for the program to be paused first. Similarly, you can traverse the reference chain to find all the surviving objects. Each time you find an object, you can set a tag for the object. When all the markup tasks are completed, you can start clearing the objects, during cleanup, all unlabeled items need to be released without any replication action. Therefore, the remaining heap space is not continuous. If the garbage collector wants to get continuous space, it has to reorganize the remaining objects.
Summary
Stop-copy andMark-cleaning:For example, if you want to clean the house, you can stop the room. If there is more garbage in the room, just move the items that are not rubbish to another room and arrange them in a regular order. Then, you have to clear all the rubbish in the original room, when there is too much garbage in the new room, move it back and forth. This is "stop-Copy", and if there is a small amount of garbage, you do not need to put something that is not rubbish into another room, because there are only a few garbage in total, move the empty garbage to another room and clean it. It is to separate the items that are not rubbish from those that are rubbish, and then clean the garbage out. This is a "mark-sweep ", of course this example is inappropriate. 3.3.4 adaptive, the generational heap memory is the largest part of the memory managed by virtual machines. During execution by the garbage collector, all objects in the heap memory need to be traversed, and it takes too much to traverse these objects, seriously affects GC efficiency. The memory generation is for this purpose. Its function is to classify these objects, which do not need to be traversed every time, and which need to be traversed frequently. Virtual machines allocate memory to the new generation, old generation, and permanent generation. The newly created object will allocate memory in the new generation. The surviving objects will be recycled multiple times and stored in the old generation, while static attributes and class information will be stored in the permanent generation, the survival time of new generation objects is short, and GC is frequently performed in new generation regions. In old generation, objects have a long life cycle, and the memory recovery frequency is low. Permanent generation usually does not perform garbage collection. Different collection methods are adopted based on the characteristics of different ages to Improve the collection efficiency. 4. Conclusion: The relationship between references and objects, and object initialization are all important points in Java programs. As mentioned above, the Java Virtual Machine (VM) determines which objects are active by traversing the reference chain, however, it is not enough to rely only on references to determine which objects need to be cleaned up and which objects do not need to be cleaned up. For example, when the memory is tight and the references are bound to objects, there are not many junk objects to be cleaned up, but the memory resources are tight. Therefore, we need to distinguish between strong references and soft references, weak references and virtual references. In this way, you can clear objects that can be cleared (such as cached object data ). The subsequent notes will be described in detail.
02-method parameter passing and initialization and garbage collection and removal