JVM resolve common interview questions

Foreword

JVM summarizes some of the classic face questions, write to share out my own problem-solving ideas, we want to help, there where you do not feel right, welcome that, subsequent free updates.

Stack memory overflow will occur 1. What conditions.

Ideas: description stack is defined, and then describe why would overflow, and then explain the configuration parameters, OK, then we can give the interviewer handwriting is a stack overflow demo.

my answer:

  • Stack is a private thread, with the thread of his life cycle of the same, each method is created in the implementation of a stack frame to store local variable table, the operand stack, dynamic linking, method exit lights information. And the local variable table contains the basic data types, object reference type
  • If the stack is greater than the depth of the thread requested the maximum depth allowed by the virtual machine, StackOverflowError will throw an exception, recursive calls produce this result.
  • Not apply to enough memory to complete the expansion, or when there is not enough memory to create a new thread to create the corresponding virtual machine stack, java virtual machine that will throw an OutOfMemoryError exception. (Thread started too)
  • -Xss parameters to adjust JVM stack size

2. Detailed JVM memory model

Idea: to draw the interviewer about the JVM memory model and illustrate and describe the definition of each module, function, and problems may exist, such as a stack overflow.

my answer:

  • JVM memory structure

Program Counter: the current thread bytecode executed by the line number indicator for recording the virtual machine executing byte instruction address, private to the thread.

Java virtual stack: store basic data types, object references, export and other methods, thread private.

Native method stacks: and virtual stack similar, but it serves the Native method, thread private.

Java heap: java biggest piece of memory, all object instances, are stored in an array of local java heap, GC recovery, threads share.

Methods District: store class information has been loaded, constants, static variables, the code data and other real-time compiler. (Ie permanent band), recycling and recovery targets mainly the type of constant pool of unloading, all threads share

Why 3.JVM memory to be divided into the new generation, the old era, lasting generations. Why the new generation into Eden and Survivor.

Ideas: Talk about what JAVA stack, the new generation of division, then talk about the transformation between them, some of the configuration parameters between each other (eg: -XX: NewRatio, -XX: SurvivorRatio, etc.), and then explain why it is divided the best add a little to their own understanding.

my answer:

1) shared memory area is divided

  • = Persistent shared memory area with pile +

  • + = With persistent region other methods

  • Java heap = + years old Cenozoic

  • New Generation = Eden + S0 + S1

2) number of configuration parameters

  • By default, the new generation (Young) ratio year old (Old) value of 1: 2, by the parameters -XX: NewRatio configuration.
  • Default, Edem: from: to = 8: 1: 1 (by parameter -XX: setting SurvivorRatio)
  • Survivor object is copied in the region of 15 times (corresponding to the virtual machine parameters -XX: + MaxTenuringThreshold)

3) Why is divided into Eden and Survivor? Why should we set up two Survivor areas?

  • If there is no Survivor, Eden District, once for each Minor GC, the object will be sent to the survival of the old era. Years old and soon to be filled, the trigger memory space Major GC. Old age is much greater than the new generation, to conduct a Full GC consumed much longer than Minor GC, we need to be divided into Eden and Survivor.
  • Survivor's raison d'etre, is to reduce the object was sent to old age, thereby reducing the occurrence of Full GC, Survivor pre-screened to ensure that only undergo the target 16 times Minor GC can survive in the new generation, it will be sent to the old years.
  • Sets the maximum benefit of two Survivor areas is to solve the fragmentation, just create a new object in Eden, the experience a Minor GC, live objects in Eden will be moved to the first one survivor space S0, Eden is cleared; and so on Eden District again is full, and then trigger a Minor GC, Eden and survival of the object S0 will be copied into the second block survivor space S1 (this process is very important, because such copying algorithm guarantees from S0 and S1 in Eden two-part live objects occupy contiguous memory space, to avoid the occurrence of fragmentation)

4. JVM in a full GC process like, how objects promoted to the old year

Ideas: first describe the Java heap memory division, explain Minor GC, Major GC, full GC , describing the conversion process between them.

my answer:

  • Java heap = + years old Cenozoic
  • New Generation = Eden + S0 + S1
  • When the Eden area is full of space, Java virtual machine to trigger a Minor GC, to the new generation garbage collection, surviving objects will be transferred to Survivor areas.
  • Large objects (Java objects requires a lot of contiguous memory space, such as that a very long string) directly into old state ;
  • If the object was born in Eden, and after the first Minor GC still alive, and is housed Survivor words, the age is set to 1, every time Minor GC survived, age +1, if older than a certain limit (15), were promoted state to old age . That long-term survival into old age state of the object .
  • Old's full and can not accommodate more objects , usually it will be Full GC after Minor GC, Full GC clean up the entire heap memory - including the young generation and the old generation .
  • Major GC occurred in the GC old age , clean-tenured , often accompanied by at least one Minor GC, than Minor GC slower than 10 times .

5. Do you know what kinds of garbage collectors, their advantages and disadvantages, and highlight some of the lower cms G1, including principles, processes, strengths and weaknesses.

Idea: we must remember that the typical garbage collector, especially cms and G1, their principles and differences, garbage collection algorithm involved.

my answer:

1) Several garbage collector:

  • Serial Collector: single-threaded collector, the collection of garbage, must stop the world, using the copy algorithm.
  • ParNew Collector: multithreaded version Serial collector, also need to stop the world, replication algorithm.
  • Parallel Scavenge collector: the new generation of collectors, copying collector algorithm, concurrent multi-threading collector, the goal is to achieve a controlled throughput. If the virtual machine runs a total of 100 minutes, which refuse to spend one minute, the throughput is 99%.
  • Serial Old Collector: old's version of the Serial collector, collectors single-threaded, use tags to organize algorithm.
  • Parallel Old Collector: old's version of the Parallel Scavenge collector, the use of multi-threading, mark - sorting algorithms.
  • CMS (Concurrent Mark Sweep) Collector: a pause in order to obtain the shortest recovery time objectives collectors, mark sweep algorithm, the operation of the process: the initial mark, concurrent mark and re-mark, concurrent cleared , the end will produce a large collection of space debris .
  • G1 Collector: tags to organize algorithm, operational processes include the following: initial mark, concurrent mark, the final mark, a selectable marker . No space debris, can be accurately controlled to a halt.

2) CMS collector and the collector G1 difference:

  • CMS collector is a collector of old age, it can be used with the new generation of Serial and ParNew collector used together;
  • G1 collector's collection ranges from the old and the new generation, in combination with other collectors do not need to use;
  • CMS collector to a minimum dwell time for the collector target;
  • G1 collector predictable pause time garbage collection
  • CMS collector is to use the "mark - sweep" garbage collection algorithm, prone to memory fragmentation
  • G1 collector using the "mark - finishing" algorithm, a spatial integration, reduces memory space debris.

How much knowledge 6.JVM memory model of understanding, such as reordering, memory barriers, happen-before, main memory, working memory.

Ideas: first draw Java memory model diagram, with examples volatile, explain what is reordering, memory barriers, it is best to give the interviewer wrote the following demo description.

my answer:

1) Java Memory Model Figure:

Java memory model specifies all the variables are stored in the main memory , each thread also has its own working memory , working memory holds the thread in the thread is a copy of a copy of main memory used in variable thread variables All operations must be in a working memory for, but can not directly read and write main memory . Between different threads also can not directly access the working memory of the other variables , the variables are passed between threads require data between their working memory and main memory simultaneously.

2) command reordering.

Here, a code look

public class PossibleReordering {
static int x = 0, y = 0;
static int a = 0, b = 0;

public static void main(String[] args) throws InterruptedException {
    Thread one = new Thread(new Runnable() {
        public void run() {
            a = 1;
            x = b;
        }
    });

    Thread other = new Thread(new Runnable() {
        public void run() {
            b = 1;
            y = a;
        }
    });
    one.start();other.start();
    one.join();other.join();
    System.out.println(“(” + x + “,” + y + “)”);
}
复制代码

Operating results may be (1,0), (0,1) or (1,1), it may be (0,0). Because, in actual operation, code instructions may not be strictly in accordance with the order of execution of code statements. Most modern microprocessors are employed to execute instructions out of order (out-of-order execution, referred OoOE or the OOE) method, in a case where conditions allow, a direct current running ability to perform subsequent instructions immediately, avoiding the acquisition caused by the data required to wait for the next instruction 3. By order execution techniques, can greatly improve the efficiency of the processor. And this is the instruction rearrangement .

3) memory barrier

Memory barriers , also known as memory fence instruction is a CPU, and memory for controlling the reordering visibility problem under certain conditions.

  • LoadLoad Barrier : For a statement such Load1; LoadLoad; Load2, Load2 and before subsequent data read operations to be read is accessed, the data Load1 guaranteed to be read is read is completed.
  • StoreStore Barrier : For a statement such Store1; StoreStore; Store2, and before the subsequent write operation is performed store2 ensure Store1 write operation visible to other processors.
  • LoadStore Barrier : For a statement such Load1; LoadStore; Store2, and before the subsequent write operation is store2 brush, to ensure that the data to be read is read Load1 completed.
  • StoreLoad Barrier : For a statement such Store1; StoreLoad; Load2, before Load2 and all subsequent read operations performed to ensure Store1 writing visible to all processors. It cost are the four biggest barrier. In the implementation of most processors, this barrier is a universal barrier, both the other three memory barrier function.

4) happen-before principle

  • Threaded happen-before principle : In the same thread, the latter operation book EDITORIAL happen-before operation. Happen-before principles locks: lock happen-before operating the lock in the same lock unlock operation.
  • happen-before the volatile principles : to write a volatile variable operating any of the following happen-before this variable (of course, include a write operation).
  • Principle happen-before transfer of : if A operates happen-before operation B, B C happen-before operating the operation, the operation A C happen-before operation.
  • Happen-before principles thread started : with a thread start method happen-before other methods this thread.
  • Principles thread happen-before interrupt : interrupt thread method calls happen-before detection thread is interrupted to interrupt code sent.
  • Happen-before the end of the thread of principle: all operations are thread happen-before termination detection thread.
  • Happen-before principle object created: initialize an object completed his first call to finalize method.

7. Tell me what you know about a simple class loader can delegate it to break the parents, how to break.

Ideas: first explain what is the class loader, the interviewer can draw a map, to tell you the significance of the existence of the class loader delegation model say about the parents, the parents finally explained how to break the delegate model.

my answer:

1) What is the class loader?

Class loader is to specify the fully qualified name of the class file is loaded into the JVM memory, according to the Class object into.

  • Start class loader (Bootstrap ClassLoader): implemented by the C ++ language (for HotSpot), is responsible for the store at <JAVA_HOME> \ lib directory or -Xbootclasspath parameter specifies the path to the library is loaded into memory.
  • Other class loader: implemented by the Java language, inherited from abstract class ClassLoader. Such as:
  • Extension class loader (Extension ClassLoader): responsible for loading the <JAVA_HOME> \ All library lib \ ext directory or system variable java.ext.dirs specified path.
  • Application class loader (Application ClassLoader). Responsible for loading the user class path (classpath) on the specified library, we can directly use this class loader. Generally, if we do not have custom class loaders default is to use the loader.

2) parent delegation model

Parent delegation model work process is:

If a class loader class loader receives a request, it first does not own to try to load this class, but this request is delegated to the parent class loader is completed. Each class loader is true only when the parent loader in their search can not find the specified class (ie ClassNotFoundException), sub-loader will try to load your own.

Parent delegation model diagram:

3) Why do parents need to delegate model?

Here, first think about, if parents do not delegate, the user is not able to define its own class with the same name of a java.lang.Object , java.lang.String class of the same name , and put it ClassPath, then between classes the result of the comparison class and uniqueness can not be guaranteed , therefore, why the need for parents to delegate model? Multiple copies of the same bytecode prevent memory

4) how to break the parent delegation model?

Delegate mechanism to break the parents not only to inherit ClassLoader class, but also to rewrite and findClass loadClass method.

8. Tell me what you know of several major JVM arguments

Idea: It can be said about the stack configuration-related, related to the garbage collector, as well as additional information about related.

my answer:

1) related stack configuration

java -Xmx3550m -Xms3550m -Xmn2g -Xss128k 
-XX:MaxPermSize=16m -XX:NewRatio=4 -XX:SurvivorRatio=4 -XX:MaxTenuringThreshold=0
复制代码

-Xmx3550m: maximum heap size to 3550m.

-Xms3550m: set the initial heap size of 3550m.

-Xmn2g: Set the size of the young generation to 2g.

-Xss128k: stack size for each thread is 128k.

-XX: MaxPermSize: set the permanent generation size is 16m

-XX: NewRatio = 4: Set the young generation (including Eden and two Survivor areas) the ratio of the old generation (excluding permanent generation).

-XX: SurvivorRatio = 4: Set the size of the area ratio of Eden Survivor young generation area. Is set to 4, the ratio of the two regions with a Survivor Eden zone is 2: 4, the total area Survivor a young generation 1/6

-XX: MaxTenuringThreshold = 0: set the maximum age of garbage. If set to 0, then the younger generation of the object without Survivor areas, directly into the old generation.

2) related to the garbage collector

-XX:+UseParallelGC
-XX:ParallelGCThreads=20
-XX:+UseConcMarkSweepGC 
-XX:CMSFullGCsBeforeCompaction=5
-XX:+UseCMSCompactAtFullCollection:
复制代码

-XX: + UseParallelGC: Select the parallel garbage collector collector.

-XX: ParallelGCThreads = 20: number of threads arranged in parallel collector

-XX: + UseConcMarkSweepGC: Set old took the concurrent collection.

-XX: CMSFullGCsBeforeCompaction : Since the memory space concurrent collector does not compress, organize, it will have a "debris" after a period of operation, making operation efficiency is reduced. This value is set to run how many times GC memory space after compression, finishing.

-XX: + UseCMSCompactAtFullCollection: Open compression of the old generation. Performance may be affected, but you can remove debris

3) supplementary information relevant

-XX:+PrintGC
-XX:+PrintGCDetails
复制代码

-XX: + PrintGC output format:

[GC 118250K->113543K(130112K), 0.0094143 secs] [Full GC 121376K->10414K(130112K), 0.0650971 secs]

-XX: + PrintGCDetails output format:

[GC [DefNew: 8614K->781K(9088K), 0.0123035 secs] 118250K->113543K(130112K), 0.0124633 secs] [GC [DefNew: 8614K->8614K(9088K), 0.0000665 secs][Tenured: 112761K->10414K(121024K), 0.0433488 secs] 121376K->10414K(130112K), 0.0436268 secs

9. how to play thread stack information.

Idea: It can be said about jps, top, jstack these orders, together with a line of investigation to answer the questions.

my answer:

  • Enter jps, obtain process ID.
  • top -Hp pid get CPU time-consuming performance of all threads in this process
  • jstack pid command to view the current status of the stack java process
  • Or jstack -l> /tmp/output.txt the stack information hit a txt file.
  • You can use fastthread stack positioning, fastthread.io/

10. strong references, soft references, weak references, the difference between the virtual reference?

Idea: Let me talk about the Four Definitions of reference, can be combined with talk about the code, you can expand it comes ThreadLocalMap in use weak references.

my answer:

1) strong references

We usually new objects is a strong reference, such as Object obj = new Object (); even under low memory conditions, JVM would rather throw OutOfMemory error does not recover this object.

2) Soft references

If an object has only soft references, the memory space is sufficient, the garbage collector does not reclaim it; if the memory space is insufficient, will reclaim the memory of these objects.

SoftReference<String> softRef=new SoftReference<String>(str);     // 软引用
复制代码

Uses: soft references have important applications in practice, such as the browser's Back button. When you press Back, the Web page content is displayed when the back or re-request it removed from the cache? That depends on the specific implementation strategy.

(1) If the content of a web page to be recycled at the end of browsing, press Back to view the previous page visited, you need to be rebuilt

(2) If you browse through the pages stored in memory will cause a lot of waste of memory, and even cause memory overflow

The following code:

Browser prev = new Browser();               // 获取页面进行浏览
SoftReference sr = new SoftReference(prev); // 浏览完毕后置为软引用        
if(sr.get()!=null){ 
    rev = (Browser) sr.get();           // 还没有被回收器回收,直接获取
}else{
    prev = new Browser();               // 由于内存吃紧,所以对软引用的对象回收了
    sr = new SoftReference(prev);       // 重新构建
}
复制代码

3) Weak references

Objects that have weak references have a more short life cycle. In the process of the garbage collector thread scans memory area under its jurisdiction, once the objects found only a weak reference, regardless of the current memory space is sufficient or not, will reclaim its memory.

String str=new String("abc");    
WeakReference<String> abcWeakRef = new WeakReference<String>(str);
str=null;
等价于
str = null;
System.gc();
复制代码

4) virtual reference

If an object holds only a phantom reference, and then it does not have any references, they are likely to be garbage collected at any time. Phantom reference primarily used to track objects recovered garbage collector activity.

11. to be updated

Reference and thanks

Guess you like

Origin juejin.im/post/5d35ca5b518825449c64bc31