Java memory allocation

• Register: the program counter, which is thread private, is a pointer to the method bytecode in the method area.

• Static field: static member defined by static.

• Constant pool: identified at compile time and saved ina.class file (final)

Symbolic references to constant values and some text modifications (fully qualified names of classes and interfaces, field names and descriptors, method and name and descriptors).

• Non-RAM storage: Permanent storage space such as hard disks.

• Heap memory: Objects and arrays created by new are managed by the Automatic Java virtual machine garbage collector and are accessed slowly.

• Stack memory: Variables of basic types and reference variables of objects (the access address of the heap memory space) are fast and can be shared, but the size and lifetime must be determined, which lacks flexibility.

Serial port (

The throughput collector uses a parallel version of the new generation garbage collector for medium – and large-data applications.

The serial collector, on the other hand, is useful for most small applications (which are needed on modern processors)

in

When an object becomes untouchable to the application that currently uses it, it can be reclaimed.

What is GC? Why GC?

GC stands for garbage collection, and memory handling is where programmers are prone to problems. Forgotten or incorrect memory collection can lead to programs or

System instability or even collapse,

Display operation method for freeing allocated memory.

Describe the Java garbage collection mechanism.

in

How do you tell if an object is alive? (or

There are two ways to determine whether an object is alive or not:

Reference counting method

The so-called reference counting method is to set a reference counter for each object, each place reference to the object, the counter is incremented by one, when the reference is invalid, the counter

Minus one. An object is not referenced when its reference counter is zero, i.e

Reachability algorithm (Chain of references)

The idea of the algorithm is: from a known as

The image is unavailable.

in

• Objects referenced in the virtual machine stack

• The object referenced by the static property of the method area class

• Objects referenced by the method area constant pool

• Objects referenced by the local method stack JNI

Although these algorithms can determine whether an object can be reclaimed, an object ratio does not necessarily get reclaimed when the above conditions are met. When an object is unreachable

“, the object will not be recycled immediately, but in a dormant phase, and will be marked twice before it can actually be recycled

In the queue, the virtual machine fires one

Advantages and principles of garbage collection. Two recycling mechanisms are considered.

A notable feature of the Java language is the introduction of garbage collection mechanism, which makes C++ programmers’ most troublesome memory management problem solved. It makes Java programmers no longer need to consider memory management when writing programs. Thanks to a garbage collection mechanism, objects in Java are no longer scoped; only references to objects are scoped. Garbage collection can effectively prevent memory leaks and efficiently use available memory. The garbage collector is usually run as a single low-level thread, cleaning and collecting objects in the heap that have died or have not been used for a long time in unexpected circumstances. The programmer cannot call the garbage collector in real time to collect an object or all objects.

Collection mechanisms include generational replication garbage collection, tagged garbage collection, and incremental garbage collection.

What is the rationale behind the garbage collector? Can the garbage collector reclaim memory right away? Is there any way to proactively notify the virtual machine for garbage collection?

for

What do system.gc () and Runtime.gc() do?

These two methods are used for hints

What is the structure of the Java heap? What is Perm Gen space in the heap?

The JVM’s heap is the run-time data area on which all instances and arrays of classes are allocated memory. It is created when the JVM starts. The heap memory occupied by objects is automatically controlled

Memory management system is garbage collector collection. Heap memory is made up of living and dead objects. Live objects are accessible to the application and are not garbage collected. Dead objects are objects that are inaccessible to the application and have not yet been collected by the garbage collector. All the way to the garbage collector
Objects occupy heap memory space until they are reclaimed.

Is there a memory leak in Java? Please describe it briefly.

A memory leak is when an object or variable that is no longer being used by a program remains in memory.

The following code can see the memory reclamation in this case:

import java.io.IOException; public class GarbageTest {

public static void main(String[] args) throws IOException {

// TODO Auto-generated method stub

try {

gcTest();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

System.out.println(“has exited gcTest!” );

System.in.read();

System.in.read();

System.out.println(“out begin gc!” );

for(int i=0; i<100; i++){

System.gc();

System.in.read();

System.in.read();

}

}

private static void gcTest() throws IOException {

System.in.read();

System.in.read();

Person p1 = new Person();

System.in.read();

System.in.read();

Person p2 = new Person();

p1.setMate(p2);

p2.setMate(p1);

System.out.println(“before exit gctest!” );

System.in.read();

System.in.read();

System.gc();

System.out.println(“exit gctest!” );

}

private static class Person{

byte[] data = new byte[20000000];

Person mate = null;

public void setMate(Person other){

mate = other;

}

}

}

Memory leaks in Java:

A memory leak occurs when a long-lived object holds a reference to a short-lived object, which cannot be reclaimed because the long-lived object holds a reference to it, even though the short-lived object is no longer needed

Determine that this object is a memory leak. If an external object instance of a class of the method returns an inner class instance of the object, the inner class object was cited for a long time, even if the external class instance objects no longer be used, but as a result of the inner class lasting external instance objects of a class, the external class object will not be garbage collected, this will cause memory leaks.

public class Stack {

private Object[] elements=new Object[10];

private int size = 0;

public void push(Object e){

ensureCapacity();

elements[size++] = e;

}

public Object pop(){

if( size == 0) throw new EmptyStackException();

return elements[–size];

}

private void ensureCapacity(){

if(elements.length == size){

Object[] oldElements = elements;

elements = new Object[2 * elements.length+1];

System.arraycopy(oldElements,0, elements, 0, size);

}

}}

The above principle should be simple if the stack is added

The stack is used sparingly, and only a few are wasted

What does it matter. Let’s look at two examples.

public class Bad{

public static Stack s=Stack();

static{

s.push(new Object());

s.pop(); // There is a memory leak on an object

s.push(new Object()); // The above object can be reclaimed, i.e. from

The more the

}}

Because it is

More than that

Because once we put new and enterprising, the previous reference nature disappears! Another case of memory leak occurs when an object is stored in

Deep copy and shallow copy.

In a nutshell, it is replication and cloning.

Person p=new Person(” Person “);

Shallow copy is a simple assignment of data members in an object, and an error is reported if there are dynamic members or Pointers. Deep copy is the relocation of dynamic members or Pointers that exist in an object.

When is the Finalize () method called? What is the purpose of finalization?

Garbage collector (

Yes, then the garbage collection may never take place, that is

So what does Finalize () do?

Its main use is to reclaim memory requested by a special channel.

If a reference to an object is set to NULL, does the garbage collector immediately free the memory occupied by the object?

No, the object will be recyclable in the next garbage collection cycle.

What is Distributed Garbage Collection (DGC)? How does it work?

DGC is called distributed garbage collection. RMI uses DGC for automatic garbage collection. Because RMI contains references to remote objects across virtual machines, garbage collection is difficult. DGC uses reference counting algorithms to provide automatic memory management for remote objects.

Briefly describe the Java memory allocation and reclamation policy and the Minor and Major GC.

• Objects are allocated in the Eden area of the heap first

• Big objects go straight to the old age

• Long-lived objects will go straight to the old age

when

Full /Major GC occurs in the old generation. Normally, the old generation GC does not trigger the Minor GC, but can be configured to trigger the Full GC

Once before

Does garbage collection occur in JVM permanent generations?

Garbage collection does not occur in the permanent generation. If the permanent generation is full or the threshold is exceeded,

Triggers a full garbage collection (

Note:

Native memory area.

What are the methods of garbage collection in Java?

tag

The idea is to mark which objects are to be recycled and then collect them uniformly. This kind of

The method is simple, but there are two main problems:

1.

Low efficiency, marking and cleaning efficiency is very low;

2.

A large number of discrete memory fragments can be generated, causing the program to allocate large memory fragments in the future


Object that fires prematurely because there is not enough contiguous memory

Replication algorithm:

In order to solve the problem of efficiency, will be available memory replication algorithm according to the capacity is divided into two equal parts, and then using only one piece, every time when a piece of memory used up, it will also live objects are copied to the second piece of memory, then one-time clear out the first block of memory, and then on the second object is copied to the first block. But this way, the cost of memory is too high, and you basically waste half of your memory every time. So the algorithm is improved, the memory area is no longer according to

If there are so many objects alive that

Mark – Finish:

The algorithm is mainly to solve the markup

Collection by generation:

Most current virtual machine garbage collection uses this approach, which divides the heap into new generation and old generation based on the lifetime of the object. In the new generation, due to the short life of objects, a large number of objects will die every time they are recycled, so the replication algorithm is adopted at this time. Subjects in the old age had a higher survival rate and no extra space to allocate guarantees.

What is a class loader, and what are class loaders?

A block of code that implements retrieving the binary stream of a class by its permission name is called a classloader.

There are four main types of loaders:

• The Bootstrap ClassLoader is used to load Java core class libraries and cannot be referenced directly by Java programs.

• Extensions Class Loader: It is used to load Java extension libraries. The Implementation of the Java Virtual machine provides an extension library directory. The class loader finds and loads Java classes in this directory.

• System Class Loader: It loads Java classes based on the Java application’s CLASSPATH. In general, Java application classes are loaded by it. Through this. GetSystemClassLoader () to get it.

• User-defined class loaders are implemented by inheriting java.lang.ClassLoader classes.

Class loader parent delegate model mechanism?

When a class receives a class loading request, it does not load the class first. Instead, it delegates to the parent class, and the parent class loads the class. If the parent class fails to load the class, the parent class sends feedback to the child class, and the child class completes the class loading.

1. Memory model and partition, need to detail what to put in each partition.

The JVM is divided into a heap and a stack, and a method section, where initialized objects are placed on the heap, references are placed on the stack, and the class information constant pool (static constants and static variables) is placed on the method section

· Method area: mainly stores class information, constant pool (static constants and static variables), compiled code (bytecode) and other data

· Heap: Initialized objects, member variables (non-static variables), and all object instances and arrays are allocated on the heap

· Stack: the structure of stack is composed of stack frames. When a method is called, a frame is pressed into the frame. Local variable table, operand stack and method output are stored on the frame

· Local method stack: mainly serves Native methods

· Program counter: Records the line number executed by the current thread

2. Partitions in the heap: Eden, Survival (from+ to), old age, their respective characteristics.

The heap is divided into Cenozoic and old generation (

3. Object creation method, object memory allocation, object access location. New an object

4. Two determination methods of GC:

Reference counting: refers to if the object is referenced somewhere

Chain of reference method:
Through a

What is SafePoint

Such as

1.

End of loop

2.

Method before returning

3.

Calling method

4.

The location where the exception was thrown

6. What are the principles and characteristics of the three GC collection methods: tag clearing, tag sorting and copy algorithm? What are your thoughts on how to optimize the collection method?

Mark first, and then clear after marking, which is not efficient and will generate fragmentation replication algorithm: divided into

What are the GC collectors? Features of CMS collector and G1 collector.

Parallel collector: The serial collector uses a separate thread for collection,

Serial collector: Multithreading is used for secondary collection

G1 is a collector based on a mark-tidy algorithm as a whole, and a copy algorithm locally (between two regions)

When does the Minor and Full GC occur

Occurs when the new generation runs out of memory

Several common memory debugging tools:

Jstack looks at the current stack, JMap looks at the memory, and Jhat dumps the heap

The paper

Major GC

1.

Objects are in the heap first

2.

Big object goes straight to the old age

3.

Long-lived objects will go straight into the old age


Occurring often in the Cenozoic era

Java class loading process?

Java class loading goes through seven processes:

1. The load

Loading is the first class loading process. During this phase, three things are done:

• Gets the binary stream of a class by its fully qualified name.

• Convert static storage structures in this binary stream to methods to run the data junction

Structure.

• Generate an in-memory Class object for the Class as a data access entry for the Class.

2. Verify

The purpose of validation is to ensure that

• Bytecode verification: it is the most complex stage in the whole verification process. Through the analysis of the verification data flow and control flow, the correctness of the program semantics is determined, mainly for the verification of the method body. For example: method type conversion is correct, jump instruction is correct and so on.

• Symbol reference validation: This action occurs later in the parsing process, mainly to ensure that the parsing action is performed correctly.

3. Prepare

The preparation phase allocates and initializes memory for static variables of the class to default values, which will be allocated in the method area. The preparation phase does not allocate memory for instance variables in the class. Instance variables are allocated along with the object when it is instantiated

public static int value=123; // During the preparation phase value the initial value is 0. It only becomes 123 during initialization.

4. The parsing

This stage mainly completes the symbolic reference to direct reference conversion action. The parse action may not necessarily be before the initialization action is complete, but may be after.

5. The initialization

Initialization is the last step of class loading. The previous class loading process is completely dominated and controlled by the virtual machine, except that the user application can participate in the loading phase through the custom class loader. During the initialization phase, you actually start executing what is defined in the class

6. Use

7. Remove

Describe how the JVM loads Class files.

The Java language is a dynamic interpreted language, and classes cannot run until they are loaded into the JVM. When the specified program is run, the JVM compiles it

the

Physically speaking, it is by

Class loading methods are classified into implicit loading and display loading.

Implicit loading is when the program is in use

The main steps of class loading:

• load. Find the corresponding class file according to the search path, and then import.

• links. Links can be broken down into 3 small steps:

• Check the correctness of the class file to be loaded.

• Prepare to allocate storage space for static variables in a class.

• Parse to convert symbolic references to direct references (this step is optional)

• Initialization. Performs initialization work on static variables and static code blocks.