background

  • One of Java’s strengths is its garbage collection mechanism. In most cases, the JVM’s GC(garbage collector) can help us return unreachable objects (that is, unreferenced objects).
  • Of course, in some cases, we still need to free the memory ourselvesObject referenceNull, theContainers, arraysEmpty), otherwise it will cause a memory leak, which is easily caused when the memory leak is severeOutOfMemoryError, LTD.A memory leak that can’t be ignored.
  • Also, since GC stops all threads, including the UI thread, frequent GC will inevitably lead to a picture stacken (one frame every 16ms in Android), so frequent GC should be avoided. One reason why GC happens so frequently is thatNever heard of memory jitter, click the link for details.
  • So understanding Java’s memory mechanism can help you avoid memory leaks when writing code.

Step into memory model

Java Memory hierarchy

Program counter

The program counter is a thread-private memory area, which is the only memory area in the Java Virtual machine that does not limit OutofMemoryErrors. Need it because Java multi-thread mechanism is through the switch in turn allocation processor execution time to realize, so will involve the thread pause and restart, but if you are in a thread execute Java method, the counter went to record the current executing virtual machine bytecode, once was suspended, Recovery simply continues at the end of the program counter record.

However, if a Native method is executed in the thread, the program counter will not be logged, so the program counter will be empty.

Vm Stack

The Java virtual machine stack is also thread-private. When a thread is started, a virtual machine stack is created for it.

A “stack frame” is created each time a Java method is called in the thread. Each “stack frame” holds information about the local variation table (the section that ordinary Java programmers like to use to represent stacks), operand stacks, dynamic links, and method exits needed to execute the method.

A stack benefit, or StackOverflowError, can occur if too many “stack frames” are added to a thread’s stack, i.e. too many methods are called in a short period of time.

In this memory area, OutOfMemoryError is thrown if the virtual machine needs to expand memory, but has not allocated enough memory.

Local method stack

It’s similar to the virtual stack, but it serves Native methods.

The Java Heap Heap

The Java heap memory is the largest chunk of memory managed by the Java Virtual machine. It is shared by all threads, is used to hold object instances and arrays, and is where most of the GC for the Java Virtual machine occurs. This area is therefore also called the “GC heap “.

The memory of the Java heap can be divided into the “new generation” and “old generation” according To the garbage collection algorithm. Furthermore, the “new generation” can be divided into “Eden”, “From Survivor” and “To Survivor”.

From a memory perspective, Java heap memory is divided into areas of memory shared by threads and areas of memory that are private to each thread.

In the Java heap region, an OutOfMemoryError is thrown if there is no memory allocated for the instance to be created and the heap cannot be extended.

Recovery algorithm

After Java8, Heap segments really consist of Young Generiation and Old Generiation. Object in which the tag copy algorithm determines whether an object should be cleaned up. The GC that occurs in the Heap Segment is called a Major GC and only affects the Heap Segment area.

GC variation – replication algorithm in Young Generiation

The GC that occurs in this region is called a Minor GC.

  • When an object is created, it is first addededenArea. whenedenWhen the extent is full, a GC is triggered and the surviving objects are copied tosurvivorArea.
  • Should not be emptySurvivorA full range also triggers a GC.
  • Memory jitter can also occur when a large number of objects are created and released in a short period of time, triggering CG.
  • As the picture shows,survivorThere are two regions, one of which is always left empty.
  • Now let’s assume twoSurvivorS0, S1, and the first GC,edenSurviving objects in the extents are copied to S0. When GC occurs again, S0 andedenObjects that are still alive in S1 are copied to empty S1, where S0 is empty; When the next GC occurs, S1 andedenObjects that survive in S0 will be copied to S0, where S1 is empty; Again GC… That’s how it goes. When the number of times an object has been copied back and forth reaches the threshold (the default is 15 times), you can pass-XX:MaxTenuringThresholdThe command to adjust the threshold), the object will be copied toOld GeneriationZone, the object will become relatively secure becauseOld SegmentThe GC frequency of the region is relatively low.

GC changes in Old Segment

The GC sent from this region becomes the Full GC.

  • When the region is full, a GC is triggered, in which some of the older objects are cleaned up.
  • If the region is still full after multiple GC fires, it is thrownOutOfMemoryError.
  • There are two cases in which a new object is copied directly into the scope:
    • When creating a single object the memory required is greater than 1/2survivorArea memory. Some very long objects;
    • When a new object is referenced by an object in the range, or references an object in the range.

Methods area

Java’s method area is common to threads as is Java’s heap memory. It mainly stores information about classes loaded by virtual machines, constants, static variables, and code generated by just-in-time compilation.

Some places incorporate method areas into the Java heap together. Let’s call it the permanent generation. This is true for hot-spot virtual machines, but it is not true in general.

Java methods can also throw OutofMemoryErrors if they are not allocated enough memory. That is, loading too many classes into the method area can result in a method area memory benefit.

Reachability of objects

When the GC checks whether an object can be collected, it is determined by whether the object can reach the GC Roots object at the top of the reference. GC Roots objects are generally referred to in the variable table of the virtual machine stack, objects referred to by static attributes of the class, constant objects, and objects passed by JNI to the underlying layer. That is, an object that does not trace to any of these types of objects is considered unreachable and will be collected during GC.

New reference type

After JDK 1.2, Java extended four reference type definitions:

Strong application type

References to objects that we normally create with the new keyword must not be reclaimed as long as strong references exist, even if OutOfMemoryError is thrown. When do strong references cease to exist? When a method completes, the variable table in the stack frame is cleaned up, and the temporary strong reference used in the method creation is cleaned up, after which the object it originally referred to is made unreachable.

Soft reference type

Objects that are useful but not required, created with SoftReference, will be reclaimed in a GC before an overflow is determined, and the Java heap throws an OutOfMemoryError if there is not enough reclaimed memory. That is, until an overflow occurs, these objects are treated like strong references and will not be reclaimed as long as the reference exists.

Weak reference type

Used to describe some unnecessary objects, that is, objects created through WeakReference. Weakly referenced objects have a lifetime of only one GC.

Virtual reference type

The existence of an object is not affected by the existence of a virtual reference, and its only use is to monitor whether an object is being reclaimed.

– Run-time constant pool in the method area

The runtime constant pool mainly holds compile-time constants from a class, which can also be added dynamically.

Such as:

"abc".intern();
Copy the code

This method first checks to see if the string exists in the runtime constant pool, retrieves it if it does, and generates one if it does not and stores it in the constant pool.

For example, when a String is generated static during runtime, it is added to the constant pool. For strings, a constant plus a constant produces a constant, but a constant plus a variable produces a variable.

About the Dalvik vm

Dalvik VIRTUAL machine is a virtual machine customized by Google according to the JVM virtual machine specification, which is more suitable for the environment requirements of mobile devices. Different from standard VMS:

  • The Dalvik compilation produces.dexFile, this format is smaller in size. The JVM does.classFile.
  • The Dalvik VIRTUAL machine is register-based, whereas the JVM specification is stack-based, so there is an advantage in speed. For example, in the standard Java virtual machine mentioned above, the virtual machine stack provides services for running threads. In Dalvik VIRTUAL machine, registers are used to store running instructions, and registers also provide program counters. Registers are part of the processor.
  • The Dalvik virtual machine allows you to create multiple instances in memory to isolate different applications. This way, when an application crashes in its own process, it does not affect other processes.

About the ART VM

ART virtual machine is enabled by default after Android 5.0, at which point Dalvik has been abandoned by Google. It differs from the Dalvik virtual machine:

  • ART virtual machine will directly convert bytecode into machine code for storage through dex2OAT tool during application installation, which is called AHEAD-of-time (AOT). Dalvik converts bytecode to machine code IN a traditional Just-in-time (JIT) mode every TIME an application is launched. Obviously, it’s going to be a lot slower. Of course, the ART virtual machine also takes up more memory.
  • The ART virtual machine performs GC in parallel mode.
    • In traditional GC mode, when a virtual machine triggers a GC, it suspends all threads, checks all objects, marks eligible objects for collection, reclaims them, and finally resumes the thread. In this case, GC is faster, but memory jitter causes it to stall. At the same time, traditional GC algorithms lead to fragmentation, where many blocks of memory are discontinuous after a collection, making addressing difficult and slowing down programs.
    • The ART virtual garbage collection algorithm allows for concurrent object markup and some object cleanup during GC. At the same time, ART introduces the mobile garbage collector technology, which enables fragmented memory to be aligned, thus saving memory space slightly.

conclusion

  • Heap SegmentTo be divided into two parts:Young GeneriationandOld Generiation.
  • Young GenertiationIs divided into twoEdenAnd two of themSurvivorZone in which the object is adoptedMark copy algorithmTo determine whether an object should be cleaned up or moved toOld GeneriationIn the. This memory region has a high frequency of GC.
  • The frequency of GC in Old Generiation is relatively low. When a large object is created, or an object associated with the region is created, it will be moved directly to the region.

See here children’s shoes quickly reward yourself with a spicy stick!

To see more articles from CoorChice, add a follow!