• Approaching autumn recruitment, preparing for summer internship, I wish you every day progress hundred million little!Day07
  • This post is a summary of jVM-related interview questions, which will be updated daily
  • Note: JVM is boring, directly brush the topic before, it is best to string a time JVM course, here recommend spread wisdom podcast JVM tutorial: dark horse programmer TUTORIAL notes complete directory


1. Can you name five references in Java? What reference types are available in Java?

1) strong reference

  • As long as theGC RootCan find the object, it will not be garbage collected; Only when theGC Root Don’t refer toThis object is recycledStrong referenceObject.
  • In other words, as long as a strong reference exists, the JVM garbage collector will never reclaim the referenced object, even if it runs out of memory and the JVM throws itOutOfMemoryError.

For example, if you create an object named Student and assign it to stu via the =(assignment operator), then stu strongly references Student.

// As long as stu refers to Student, it is a strong reference and will never be reclaimed by the JVM
Student stu = new Student();
// If you set stu to null, you can break the GC Root reference chain and the STU will be reclaimed by the JVM
stu = null;
Copy the code

(2) soft references

  • If only a soft reference refers to an object, garbage collection will be triggered again to reclaim the soft reference object after the garbage collection. That is, soft reference objects are not reclaimed by the JVM when there is enough memory, but they are reclaimed when there is not enough memory, so soft reference objects are often used to describe objects that are not necessary but still useful.
// do not refer to byte[] directly through list
/ / the list -- -- -- -- -- > SoftReference -- -- -- -- -- > byte [] add a layer of soft references:
List<SoftReference<byte[]>> list = new ArrayList<>();
Copy the code

(3) a weak reference

  • A weak reference is a reference one level lower than a soft reference. If only a weak reference refers to an object, the object referenced by the weak reference will be reclaimed during garbage collection regardless of whether there is sufficient memory.
List<WeakReference<byte[]>> list = new ArrayList<>();
Copy the code

(4) virtual reference

  • Virtual references must be used with reference queues, mainly ByteBuffer. When reference objects are reclaimed, virtual references are enqueued and vreferent-related methods are called (Unsafe.freeMemory()Free direct memory.

⑤ Finalizer references

  • All classes inherit fromObjectClass,ObjectHave a classfinalize()Methods. When an object is no longer referenced by another object, the finalizer reference object is placed in the reference queue (the referenced object has not been reclaimed yet), the finalizer reference object is found based on the finalizer reference object, and the object’sfinalize()Methods. Once called, the object can be garbage collected.

Reference queue

The soft reference itself is not cleaned up when the object to which the soft reference or weak reference points is recycled. If you want to clean up references, you need to use the reference queue:

ReferenceQueue, when a reference (soft reference, weak reference) is associated with a ReferenceQueue, when the object referenced by this reference is to be garbage collected, it will be added to the associated ReferenceQueue. Therefore, one of the phenomena to determine whether a reference object has been collected is: Whether a reference to this object is added to its associated reference queue.

ReferenceQueue<byte[]> queue = new ReferenceQueue<>();
SoftReference<byte[]> ref = new SoftReference<>(new byte[_4MB], queue);
Copy the code

After all, a reference queue is a recycling mechanism for references. When the object wrapped by a soft or weak reference is null or recycled, the reference is no longer valuable, and the reference queue is a recycling mechanism for clearing the part of the reference.

  • Soft and weak references can work with or without the reference queue: after objects referenced by weak and virtual references are reclaimed, they are placed in the reference queue so that soft and weak reference objects can be reclaimed together.
  • Virtual and finalizer references must work with reference queues: virtual and finalizer references are associated with a reference queue when used.

How does the JVM determine that an object can be reclaimed? Two algorithms to determine whether an object can be recycled?

① Reference counting (Java does not use this method)

  • If an object is referenced by another variable, let the object’s reference count+ 1If the object is referenced2Then its reference count is2And so on.
  • If a variable no longer refers to the object, the object’s reference is counted- 1When the object’s reference count becomes0, it indicates that the object is not referenced by other variables, and the object can be collected as garbage.

Disadvantages of reference counting method: In circular reference, the reference count of both objects is 1, so neither object can be released and reclaimed. You end up with a memory leak!

(2) Accessibility analysis algorithm

The reachability analysis algorithm is the algorithm in the JVM that determines whether an object is garbage or not: the algorithm first determines the GC Root (the Root object, that is, the object that must not be garbage collected).

Before garbage collection, the JVM scans all objects in the heap to determine whether each object can be referenced directly or indirectly by GC Root. If it can be referenced directly or indirectly by the Root object, it cannot be garbage collected, and if it can not be collected:

  • The garbage collector in the JVM explores all viable objects through reachability analysis.

  • Scan objects in the heap to see if they can be found along the chain of references starting with GC Root; if not, they can be reclaimed, otherwise they can be reclaimed.

  • Objects that can be used as GC Root:

    • The object referenced in the virtual machine stack (the local variable table in the stack frame).
    • The object referenced by the class static property in the method area.
    • The object referenced by the constant in the method area.
    • Local method stackNativeThe object referenced by the method.

What are the JVM garbage collection algorithms?

① Mark-clear algorithm

  • Tag removal algorithm: As the name implies, in the process of virtual machine garbage collection, the tag algorithm is first used to determine the recyclable objects, and then the garbage collector clears the corresponding contents according to the tag to make corresponding space in the heap memory.

    • In this case, the memory space is not zeroed out, but the start and end address of the memory is recorded. The next time the memory is allocated, the memory will be overwritten directly.
  • There are two main disadvantages:

    • One is efficiency. The efficiency of both marking and cleaning is not high.
    • The other is the space problem. After the mark is cleared, a large number of discontinuous memory fragments will be generated. Too much space fragment may cause that when the program needs to allocate large objects in the future, it cannot find enough contiguous memory and has to trigger another garbage collection action in advance.

② Mark-collation algorithm

  • Mark-collation algorithm: will not beGC RootThe referenced object is reclaimed, cleaning up the memory space it occupies. Then the remaining object memory space can effectively avoid problems caused by memory fragmentation, but it takes a certain amount of time to sort out and move objects, so the efficiency is low.

③ Replication algorithm

  • Replication algorithm: Divide memory into two areas of equal size,FROMandTO(TO is empty). The first will beGC RootThe object referenced fromFROMIn theTOIn, recollect cannot beGC RootObject referenced. Then exchangeFROMTO.

This also avoids the memory fragmentation problem, but can take up twice as much memory. The process is as follows:

  • When an object needs to be reclaimed, theGC RootDirectly referenced objects (objects that do not need to be reclaimed) fromFROMIn theTOIn:

  • Then clear the objects that need to be reclaimed FROM:

  • Finally swap FROM and TO :(FROM TO TO, TO FROM)

④ Generational collection algorithm

  • Generation collection algorithm: This algorithm divides the Java heap into the new generation and the old generation. By default, the new generation takes up 1/3 of the total space, and the old generation takes up 2/3 of the total space. The most appropriate collection algorithm is adopted according to the characteristics of different ages.

    • In the new generation, a large number of objects are found dead and only a few survive in garbage collection, so the replication algorithm is selected, and only a small amount of the replication cost of the surviving objects can be collected.

      • There are three divisions in the New generation: Eden,ToSurvival area,FromSurvivability, their default ratio is8:1:1.
    • In the old days, because the object had a high survival rate and there was no extra space to allocate it, it had to be recycled using mark-clean or mark-tidy algorithms.

The following is a step-by-step introduction to the process of generational collection algorithm:

  • Objects that have been used for a long time are placed in the old age (recycling once for a long time takes a long time), and objects that can be discarded when used up are placed in the new generation (recycling is frequent and relatively fast) :

  • The newly created objects were placed in the Eden of the new generation:

  • When Eden runs out of memory, a garbage collection is made, called a Minor GC (Young GC) :

The Minor GC copies Eden and surviving FROM objects that still need TO survive into surviving FROM, increases their lifetime by 1, and then swaps FROM and TO.

  • Eden does not require a living object to clear it:

  • Swap FROM and TO:

  • Similarly, continue to add objects to Eden, if full, proceed a second timeMinor GC:

Same process, still need to live object life +1 :(in the picture below, the object with life of 1 in the FROM is newly copied FROM the garden of Eden, not the object with life of 1 in the original survival zone FROM, here is only a static picture is not easy to display, can only be described in words)

The object is created again, and if The Eden of The new generation is full again, The Minor GC (which triggers Stop The World, stopping other user threads and letting only The garbage collection thread work) is triggered again, which not only collects The garbage from The Eden, but also collects The garbage from The survivable zone and copies The active object TO The survivable zone TO. Recycling swaps the two surviving zones and increases the life of objects in the surviving zone by 1!

  • If the object in the surviving zoneThe service life exceeds a threshold. Procedure(maximum15.4 bit), will bePut into old ageIn:

  • If memory is full in the new generation and the old generation, it will trigger firstMinor GcAnd then triggerFull GC, the scanningNew generation and old ageAll objects that are no longer used and recycled:

Process summary of generational collection algorithm:

  • Newly created objects are first assigned to the Eden region.
  • Cenozoic space is insufficient when triggeredMinor GC, Eden andFROMObjects that need to survive in the survival zone will be copiedTOIn the survival zone, the life of the surviving object+ 1And exchangeFROMTO.
  • Young GCWill lead toStop The World: Suspends another user’s thread and waits for the garbage collection to complete before resuming execution.
  • The service life of an object exceeds the threshold15Will be promoted to the old age.
  • If the memory of both the new generation and the old generation is full, it will trigger firstMinor GCAnd then triggerFull GC, the scanningNew generation and old ageAll objects that are no longer used and recycled.

What are the JVM garbage collection mechanisms?

When the GC is triggered, the details are as follows, only the common Young (Minor) and Full GC are mentioned here.

① Young GC (Minor GC)

  • Triggered when there is not enough space to allocate in the Cenozoic Eden zoneYoung GC.
  • Young GCIt was just a one-time thingCopy the garbage collection algorithmEden and the surviving zone FROMYou still need live objectsFirst,Copied to theSurvival area TOAnd let itAdd 1 lifeAgain,Swap FROM and TO. There is no need for living objects in Eden to be removed.

(2) Full GC

  • If memory is full in the new generation and the old generation, it will trigger firstYoung GCAnd then triggerFull GC, the scanningNew generation and old ageAll objects that are no longer used and recycled.
  • System.gc()Default is also triggerFull GC.
  • Full FCuseMark – Clean uporMark – TidyAlgorithm to do the recycling.

Why is Full GC so slow?

  • This is because Full GC collects new generation, old age, metadata/permanent generation (method area).
  • The metadata reclamation algorithm is inefficient, and the Class reclamation conditions of vm specifications are harsh.
  • The new generationReplication algorithmIt’s faster. Used in the old daysMark – Clean uporMark – TidyThe memory size of the old generation is larger than that of the new generation.
  • In some garbage collectors, a Young GC is triggered before a Full GC is collected

What garbage collectors does the JVM have?

Related concepts:

  • Parallel collection: Multiple garbage collection threads work in parallel while the user thread is still waiting.
  • Concurrent collection: When the user thread and garbage collection thread work simultaneously (not necessarily in parallel, but alternately). The user program continues to run, while the garbage collector runs on another CPU.
  • throughput: indicates that the CPU is usedThe time to run user codeWith the CPUTotal elapsed timeThe ratio of the (Throughput = run user code time/(Run user code time + garbage collection time“(” That’s right. For example, if the virtual machine runs for 100 minutes and the garbage collector takes 1 minute, the throughput is99%.

Garbage collector classification:

  • Serial: single-threaded garbage collection.
  • Throughput first: Multithreaded garbage collection, minimizing STW (stop the world, stop all other workers) time per unit of time.
  • Response time priority: Multi-threaded garbage collection to make a single STW as short as possible (try not to affect other threads running).

7 types of garbage collectors:

As shown in figure: (reference since the image: thinkwon.blog.csdn.net/article/det…).

Let’s take a look at the following two recyclers.

  • CMS collector: old-age parallel collector

    • Collectors with the goal of obtaining the shortest collection pause time have the characteristics of high concurrency and low pause, and pursue the shortest GC collection pause time.
    • The CMS collector is implemented based on a mark-sweep algorithm and generates memory fragmentation.
  • G1 collector: Java heap parallel collector

    • The G1 collector is a new collector provided with JDK1.7 and is implemented based on the mark-collation algorithm, which means that there is no memory fragmentation.
    • In addition, the G1 collector differs from its predecessors in that it collects the entire Java heap (including the new generation and the old generation), while the other six collectors collect only the new generation or the old generation.

CMS and G1 are response-first garbage collectors: keep STW times as short as possible (with minimal impact on other threads).

Note: STW, which stands for Stop The World, suspends other user threads and only lets The garbage collector thread work.


Can you tell me what GC Root is?

In the Java language, objects that can be used as GC Roots include the following four types:

  • The object referenced in the virtual machine stack (the local variable table in the stack frame).
  • The object referenced by the class static property in the method area.
  • The object referenced by the constant in the method area.
  • Objects referenced by Native methods in the Native method stack.

7. A ++ + ++ A

The case code is as follows:

/** * a++ */
public class Demo3_2 {
    public static void main(String[] args) {
        int a = 10;
        int b = a++ + ++a + a--;
        System.out.println(a);/ / 11
        System.out.println(b);/ / 34}}Copy the code

How do you get the results for A and B above?

Analysis:

  • iincInstructions operate directly on local variable buckets (slots).
  • iloadInstructions are used to read variables
  • a++++aThe difference is execution firstiloadLet’s do it firstiinc.a++First,iloadagainiinc.++aOn the contrary.

For those not clear about virtual machine instructions, take a look at this article: JVM_07 Class loading and Bytecode Technology (Bytecode instructions)

Insert a = 10 into the operand stack:

② istore 1, eject 10 from operand stack into slot 1 of local variable table:

A++ = iinc + 1; a++ = iinc + 1

  • iload 1The variablea=10, read into the operand stack:

  • performiincCommand, perform +1 operation on a on the local variable table, where A is 11:

Iinc = iloAD; iInc = iloAD;

  • performiincCommand, perform +1 operation on a on the local variable table, where a is 12:

  • iload 1Place local variables in the scalea=12, read into the operand stack:

⑤ Add (a++ + ++a) in the operand stack to get the result 22.

(a++ + ++a) +a —

  • a--To perform firstiloadCommand, in executioninc 1,-1The following command reads 12 from the local table into the operand stack:

  • Next to executeinc 1,-1Command, perform -1 operation in the local variation table, then the value in the local variation table is reduced from 12 to 11:

  • In the operand stack, the second addition is performed, yielding 34:

Finally, pop the data in the operand stack into the local variable table, and assign the value of slot 2 B =34:

So the program results: A is 11, b is 34.


8. Why HotSpot is divided into new generation and old generation?

HotSpot divides the memory into chunks based on the lifetime of the object, typically dividing the Java heap into new generation and old generation, so that it can use the most appropriate collection algorithm for each generation.

  • In the new generation, a large number of objects are found dead and only a few survive in garbage collection, so the replication algorithm is selected, and only a small amount of the replication cost of the surviving objects can be collected.
  • In the old days, because the object has a high survival rate and there is no extra space to allocate it, it has to use the “mark-clean” or “mark-tidy” algorithm for recycling.

The Cenozoic era is divided into one Eden zone and two Survivor zones, usually called From Survivor zone and To Survivor zone.


What are the main components of the JVM?

Figure :(picture from blog.csdn.net/weixin_4359…)

It is mainly composed of four parts:

  • Runtime data area: this is what we call the MEMORY of the JVM.
  • Execution engine: performclassInstructions in a bytecode file.
  • Class loading system: Class name according to the given fully qualified name (e.g.java.lang.Object) to load.classFiles to the methods section in the runtime data section.
  • Native interface: Interacts with local method libraries and is an interface that other programming languages interact with.

10. Does Java have memory leaks? Please briefly describe

Answer: There are memory leaks in Java.

Although there is a GC garbage collection mechanism in Java, objects that are no longer in use are collected in a timely manner. But there are still memory leaks!

Java cause of memory leaks is clear: long life cycle of object reference object holds a short life cycle is very possible memory leaks, although a short life cycle objects no longer needed, but because of long life cycle object holds its reference that can’t be recycled, which is memory leaks in Java takes place.


Reference article:

  • JVM_04 Garbage collection mechanism
  • JVM_07 Class Loading and bytecode Technology (Bytecode instructions)

Summary of the interview question is also quite time-consuming, the article will be updated from time to time, sometimes more than a day to update a few, if you help to review and consolidate the knowledge point, please also support three, the follow-up will be a hundred million points of update!


In order to help more young white from zero to advanced Java engineers, from CSDN official side to get a set of “Java Engineer learning growth knowledge Map”, size870mm x 560mm, can be folded into a book size, interested friends can have a look, of course, anyway, the blogger’s articles are always free ~