JAVA Basics Cheats __java

Source: Internet
Author: User
Tags garbage collection object object

1. Java Array and memory control One, Java array initialization

The Java array is static, that is, when the array is initialized, the length of the array is immutable. Java arrays must be initialized with array objects before they are used, so the so-called initialization is to allocate the memory space for all elements of the array and to specify the initial values for each element of the element.

Two ways to initialize a Java base type array

Static initialization: The programmer explicitly specifies the initial value of each array element when initialized, and the system determines the length of the array.

Dynamic initialization: When initialized, the programmer specifies only the length of the array, and the initial value is allocated by the system's array elements.

Do not use both static and dynamic initialization, that is, do not specify both the length of the array and the initial value for each array element when the array is initialized.

The Java array is static, and once the array initialization completes, the memory space allocation of the array element ends, and the program can only change the value of the array element, not the length of the array. The Java array variable is a reference type variable, and the array variable is not the array itself, it is just an array object pointing to the heap memory. Therefore, you can change the array that an array variable refers to, which can cause an illusion of variable length of the array.

Two: Java Array memory storage

For a base type array, the value of an array element is stored directly in the corresponding array element, so the initialization of the base type array is simpler: The program allocates the memory space directly to the array and then stores the value of the element in the corresponding memory.

All local variables are stored in stack memory, variables, whether they are of a basic type or a reference type, are stored in their own method stack, but objects referenced by reference type variables (arrays, normal Java objects) are always stored in heap memory.

For many Java programmers, the easiest thing to confuse is when the reference type variable is just the variable itself in the stack memory and when it becomes a reference to the actual Java object. In fact, the rule is simple: a reference variable is essentially just a pointer, as long as the program accesses the property by referencing the variable, or invokes the method by invoking the reference variable, which is substituted by the object it references.

Three: Using an array

When an array reference variable points to a valid array object, the program can access the array object by referencing the variable. The Java language does not allow direct access to data in heap memory, so it is not possible to directly access the array objects in the heap memory, and the program accesses the array through an array reference variable.

2.Java memory recycle mechanism One, Java object in memory reference state

Memory leaks: When the program is running, the memory space will be allocated continuously, those no longer use the memory space should be recycled immediately, so that the system can use these memory again, if there is no useless memory is not recycled back, this is the memory leak.

(1) Strong reference

This is the most common reference in Java programs, where a program creates an object and assigns it to a reference variable, which is a strong reference. Java programs can access the actual object through strong references. When an object is referenced by one or more strong reference variables, it is in a state of reach and it cannot be reclaimed by the system garbage collection mechanism.

Strong references are a widely used reference type in Java programming, and Java objects referenced by strong references will never be reclaimed by garbage collection, even if the system memory is tense, and even if some Java objects will never be used later, the JVM will not reclaim the Java objects referenced by the strong references.

Because the JVM certainly does not reclaim the Java objects referenced by the strong references, strong references are the primary cause of the Java memory leak.

such as Receiptbean rb=new Receiptbean (); RB represents a strong reference way.

(2) Soft reference

Soft references need to be implemented through the SoftReference class, which can be reclaimed by the garbage collection mechanism when an object has only soft references. For objects that have only soft references, when the system has enough memory space, it is not reclaimed by the system, and the program can use the object, and the system reclaims it when the system is out of memory space.

Soft references are often used in memory-sensitive programs, and soft references are good substitutes for strong references. For soft references, when the system has sufficient memory space, soft references and strong references are not much different, when the system memory space is low, the soft reference Java objects can be recycled by the garbage collection mechanism, so as to avoid the system memory of the exception.

When a program needs to create a large number of new objects for a class, and it is possible to regain access to an old object that has already been created, a soft reference can be used to solve the problem of memory tension.

For example, there are two ways to access 1000 person objects

Method creates 1000 objects in one order, but only one person reference points to the last man object.

Method two defines an array of person with a length of 1000, each of which refers to a man object.

For method One, the weakness is obvious, and the program does not allow the person object that was previously created to be accessed again, even though the space occupied by the object has not been reclaimed. However, a reference to this object has been lost, so it is also necessary to recreate a new person object (reallocate memory), and the existing Man object (complete, correct, usable) can only wait for garbage collection.

For method Two, the advantage is that you can regain access to each person object that you created earlier, but there are weaknesses, if the system heap memory space is tight, and 1000 person objects are referenced by strong references, garbage collection mechanisms will not be able to reclaim their heap memory space, the system performance would become very poor, There is even a lack of memory that causes the program to abort.

If the soft reference is a good solution, when the heap memory space is sufficient, the garbage collection mechanism does not reclaim the person object, you can access an existing person object at any time, which is no different from the normal strong reference. However, when the heap heap memory space is insufficient, the system can also reclaim the person object referenced by the soft reference, thereby improving the performance of the program and avoiding garbage collection.

When a program uses a strong reference, the JVM garbage collection mechanism does not reclaim the Java objects referenced by the strong reference, regardless of how tight the system heap memory is, resulting in the program being aborted due to insufficient memory. However, if you change the strong reference to a soft reference, the completion can avoid this situation, which is the advantage of soft reference.

(3) Weak reference

A weak reference is somewhat like a soft reference, except that a weak reference refers to an object that has a shorter lifetime. Weak references are implemented through the WeakReference class, and weak references are similar to soft references, but weak references have lower reference levels. For objects that have weak references, the memory that the object occupies is recycled when the system garbage collection mechanism runs, regardless of the system memory.

Of course, this is not to say that when an object has only a weak reference, it is reclaimed immediately, just as those objects that have lost references must wait until the system garbage collection mechanism runs.

Summary description:

1, weak references are very uncertain, because the weak references are recycled every time the garbage collection mechanism is executed, and the garbage collection mechanism is not controlled by the programmer, so the program must be careful with the null pointer exception when it gets the Java object referenced by the weak reference. A Java object obtained through a weak reference may be null

2. Due to the uncertainty of garbage collection, the referenced object may have been released when the program wants to remove the referenced object from the weak reference. If your program needs to use the referenced object, you must re-create the object.

(4) Virtual reference

Soft references and weak references can be used alone, but virtual references cannot be used alone, and using virtual references alone does not make much sense. The primary role of a virtual reference is to track the state of the object being garbage collected, and the program can understand whether the object referenced by the virtual reference will be reclaimed by checking whether the reference queue associated with the virtual reference contains the specified virtual reference.

The reference queue is represented by the Java.lang.ref.ReferenceQueue class, which is used to hold references to the reclaimed object. When a soft reference, a weak reference, and a reference queue are used in combination, the system reclaims the referenced object and adds the reference of the reclaimed object to the associated reference queue. Unlike soft and weak references, a virtual reference adds a virtual reference to the associated queue before the object is disposed, allowing action to be taken before the object is reclaimed.

A virtual reference is implemented by the Phantomreference class, which is exactly like no reference. A virtual reference has no significant effect on the object itself, and the object does not even feel the presence of a virtual reference. If an object has only one virtual reference, it is roughly the same as without a reference. Virtual references are used primarily to track the state of the object being garbage collected, the virtual reference cannot be used alone, and the virtual reference must be used in conjunction with the queue referencequeue.

Second, Java memory leak

For C + + programs, the memory space occupied by the objects must be explicitly reclaimed by the program, and if the programmer forgets to recycle them, the memory space they occupy will generate a memory leak; for Java programs, all unreachable objects are reclaimed by the garbage collection mechanism, So programmers don't have to consider this part of the memory leak.

However, if there are Java objects in the program that are in a reachable state, but the program will never access them again, the space they occupy will not be reclaimed, and the space they occupy will result in a memory leak.

Three, memory management tips

As much as possible to master Java memory Recycling, garbage collection mechanism is to better manage the memory of the JVM, so as to improve the performance of Java programs. Based on the memory mechanism described earlier, here are some tips for Java memory management.

(1) Use the direct quantity as far as possible

When you need to use strings and Byte,short,integer,long,float,double,boolean,charater wrapper class instances, your program should not create objects in new ways, but rather directly by using direct amounts to create them.

For example, the program requires a "Hello" string, which should take the following code

String str= "Hello"

The above method creates a "Hello" string, and the JVM's string caching pool caches the string. But if the program uses

The program also creates a "hello" string in the cache pool of slow-existence strings. In addition, the string object referenced by str contains a char array, which in turn holds strings such as H,E,L,L.O.

(2) string stitching using StringBuffer and StringBuilder

If more than one string object is used in a program to perform string concatenation operations, a large number of temporary strings are generated at run time that are saved in memory, resulting in degraded program performance

(3) Early release of references to unwanted objects

Most of the time, the object referenced by the method local reference variable becomes garbage as the method ends, because the life cycle of the local variable is very short, and when the method runs, the local variable in the method ends the lifecycle. Therefore, most of the time the program does not need to explicitly set the local reference variable to NULL.

But the case in the following program needs to be explicitly set to NULL, which is better, such as:

for the info () method shown in the above program, if you need to "perform time-consuming, memory-intensive operations" or "or invoke a method of time-consuming, memory-consuming operations," the explicit setting of Obj=null in the above program is necessary. It may be that when the program "executes time-consuming, memory-intensive operations" or "or calls for time-consuming, memory-intensive operations", the objects referenced by obj may be garbage-collected.

(4) Use of static variables as little as possible

Theoretically, when a Java object object is recycled is determined by the garbage collection mechanism and is uncertain for programmers. Because the garbage collection mechanism determines whether an object is garbage, the only criterion is whether the object has a reference variable to reference it, so that the object's reference is released as soon as possible.

At worst, when an object is referenced by a static variable, the garbage collection mechanism usually does not reclaim the memory occupied by the object. Such as:

Class person {staticobject obj=newobject ();}

For the object object above, as long as the obj variable references it, it will not be reclaimed by the garbage collection mechanism

The class object corresponding to the person class will reside in memory until the program is finished, so the object object referenced by obj, once created, will also reside in memory until the program has finished running.

(5) Avoid creating Java objects in frequently invoked methods, loops, such as:

The upper loop produces 10 objects, and the system continues to allocate memory space for these objects to perform initialization operations. Their survival time is not long, and then the system needs to reclaim their memory space is that the continuous allocation of memory, recycling operations, the performance of the program has been greatly affected.

(6) Cache objects that are frequently used

If some objects need to be used frequently, consider saving them in a cache pool so that they can be used directly the next time you need them. A typical cache pool is a data connection pool in which a large number of database connections are cached, and a database connection can be directly removed each time a program needs to access the database.

In addition, if there are some commonly used basic information in the system, such as the information contained in the information of employees, material information, etc., you can also consider caching them.

There are usually two ways to use caching

1. Using HashMap for caching

2. Direct use of open source caching projects. (e.g. Oscache,ehcahe, etc.)

(7) Try not to use the Finalize method

The garbage collector calls the object's Finalize () method to perform resource cleanup before the garbage collector prepares to recycle the object after it has lost its reference. For this reason, some developers may consider using the Finalize () method to enter and clean.

In cases where the garbage collector itself has severely restricted application performance, the option to use the Finalize method for resource cleanup is no doubt an act of fuelling, which will result in a greater burden on the garbage collector, resulting in less efficient program execution

(8) Consider using SoftReference soft references

3.Java Memory Management--memory allocation One, Java memory allocation 1, Java has several storage areas.

Register

-Within the CPU, developers cannot control the allocation of registers through code, and the compiler manages

Stack

--in Windows, the stack is to the low address expansion of the data structure, is a continuous area of memory, that is, the top of the stack address and the maximum capacity of the stack is the system predetermined.

--Advantages: Automatically distributed by the system, faster.

Disadvantage: not flexible enough, but programmers are out of control.

--Storage of basic data types, objects created during development (not during run)

Heap

--a data structure that is extended to a high address and is a discrete memory region

--In the heap, there is no stack pointer, so you can't get support directly from the processor

The advantage of the heap is that there is great flexibility. such as the Java compiler does not need to know how many storage areas to allocate from the heap, nor does it have to know how long the stored data will survive in the heap.

static storage area and constant storage area

--static storage is used to hold variables of static type

--a constant type (final) type of value that is used by the Const store, typically in read-only memory

Non-RAM Storage

--a stream of objects to be sent to another machine

--persistent objects, stored on disk

2. Java Memory allocation

The underlying data types are distributed directly in the stack space;

The formal parameters of the method are allocated directly in the stack space, when the method call is completed and recycled from the stack space;

The reference data type needs to be created with new, both allocating an address space in the stack space and allocating the object's class variables in the heap space;

The reference parameters of the method are allocated an address space in the stack space, and point to the object area of the heap space, and then reclaim from the stack space when the method call is finished;

When the local variable new comes out, the space is allocated in stack space and heap space, and when the local variable life cycle is over, the stack space is immediately reclaimed and the heap space area waits for GC to recycle;

The literal parameters that are passed in when the method is called are first allocated in the stack space and released from the stack space after the method call is completed;

String constants are assigned in the DATA area, this is allocated in the heap space;

The array allocates both the array name in the stack space and the actual size of the array in the heap space.

3. The Java memory model Java virtual machines have roughly three logical portions of the memory they govern: method areas, Java stacks, and Java heaps.

The method area is statically allocated, and the compiler binds the variables to a storage location, and the bindings do not change at run time.

Constant pool, named constants, string constants, and static variables in the source code are saved in the method area.

Java stack is a logical concept, characterized by LIFO first. The space of a stack may be contiguous, or it may be discontinuous.

The most typical stack application is the invocation of a method, which creates a method frame (frame) every time the Java Virtual machine invokes the method, and the corresponding method frame is ejected (POPs). The data stored in the stack is also determined at runtime.

Java heap allocation (heap allocation) means a memory management model that allocates and reclaims storage space at run time in random order.

The data stored in the heap is often the size, quantity, and lifetime that cannot be determined at compile time. The memory of a Java object is always allocated in heap.

4. Java memory allocation Instance resolution

Chang (constant pool) refers to some data that is determined at compile time and is saved in the compiled. class file. It includes constants in classes, methods, interfaces, and so on, as well as string constants.

The Chang is loaded by the JVM during runtime and can be expanded. Inter of String

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.