catalogue

  • 6.0.0.1 What are the run-time data areas? What does a Java virtual machine stack do? What does the local method stack do?
  • 6.0.0.2 Memory Layout of objects? What are the ways in which objects are accessed and located? What are the advantages of pointer access versus handle access?
  • 6.0.0.3 What is the object creation process? Where does the variable creation process go on the virtual machine?
  • 6.0.0.4 In which data regions may OutOfMemoryError occur? Please describe the scenario and reason why OOM appears in this data area.
  • 6.0.0.6 What is the difference between heap and stack in Java? Write programs that run out of heap memory and stack memory separately?
  • 6.0.0.7 If an object reference is set to NULL, does the garbage collector immediately free the memory occupied by the object?
  • 6.0.0.8 What are the methods of Garbage collection in Java?
  • 6.0.1.1 How to Determine whether an object survives and? Which is better, reference-counting or reachability? How to understand that an object is not necessarily recycled?
  • 6.0.1.2 Difference between class.forname () and classLoader.loadClass ()?

Good news

  • Summary of blog notes [October 2015 to present], including Java basic and in-depth knowledge points, Android technology blog, Python learning notes, etc., including the summary of bugs encountered in daily development, of course, I also collected a lot of interview questions in my spare time, updated, maintained and corrected for a long time, and continued to improve… Open source files are in Markdown format! Also open source life blog, since 2012, accumulated a total of 500 articles [nearly 1 million words], will be published on the Internet, reprint please indicate the source, thank you!
  • Link address:Github.com/yangchong21…
  • If you feel good, you can star, thank you! Of course, also welcome to put forward suggestions, everything starts from small, quantitative change causes qualitative change! All blogs will be open source to GitHub!

6.0.0.1 What are the run-time data areas? What does a Java virtual machine stack do? What does the local method stack do?

  • What are the run-time data areas?
    • The Memory managed by the Java VIRTUAL machine consists of several runtime data memory: the method area, the virtual machine stack, the local method stack, the heap, and the program counter, where the method area and heap are data areas shared by threads, and the others are thread-isolated data areas
    • 1.1 Program counter
      • A program counter is a small piece of memory that can be thought of as an indicator of the line number executed by the current thread. The bytecode interpreter works by changing the value of this counter to select the next bytecode instruction to be executed. Branch, loop, jump, exception handling, thread recovery and other basic functions need to be completed by this counter. If the thread is executing a Java method, this counter records the address of the virtual machine bytecode instruction being executed. This counter is empty if the Native method is being executed. This memory region is the only one where the Java Virtual Machine specification does not specify any OutOfMemotyError cases
    • 1.2 Java Virtual Machine Stack
      • The virtual stack describes the memory model of Java method execution: each method execution creates a stack frame to store information about local variables, operand stacks, dynamic links, method exits, and so on. The process of each method from invocation to completion corresponds to the process of a stack frame being pushed into and out of the virtual machine stack.
      • Tech blog summary
      • Stack memory is the virtual machine stack, or the part of the virtual machine stack that is locally variable
      • The local variable table holds various basic data types known at edit time (Boolean, byte, CHAR, short, int, float, long, double), object reference (refrence) types, and returnAddress types (which refer to the address of a bytecode instruction)
      • 64-bit long and double data occupy two local variable Spaces, and the rest occupy only one.
      • The Java Virtual Machine specification specifies two exceptions for this area: a StackOverflowError is thrown if the stack depth of a thread request is greater than the depth allowed by the virtual machine. An OutOfMemoryError is raised if the virtual machine cannot allocate enough memory while expanding
    • 1.3 Local method stack
      • The role of the Native method stack and the virtual machine stack is very similar, the difference is that the virtual machine stack performs Java methods (that is, bytecode) services for the virtual machine, while the Native method stack serves the Native methods used by the virtual machine
      • The local method stack area also throws StackOverflowError and OutOfMemoryErroy exceptions
    • 1.4 Java heap
      • The heap is the largest chunk of memory managed by the Java Virtual machine. The Java heap is an area of memory that is shared by all threads and is created at virtual machine startup for the sole purpose of holding object instances, where almost all object instances are allocated memory. All object instances and arrays are allocated on the heap
      • The Java heap is the primary area managed by the garbage collector. The Java heap is subdivided into new generation and old generation
      • Anyway, the purpose of partitioning is to recycle memory better, or to allocate memory faster, right
      • The Java heap can be in a physically discrete memory space, as long as it is logically contiguous. OutOfMemoryError will be thrown if instance allocation is not completed in the heap and the heap cannot be extended
    • 1.5 method area
      • The method area is used to store information about classes that have been loaded by the virtual machine, constants, static variables, code compiled by the just-in-time compiler, and so on
      • In addition to the fact that the Java heap does not require continuous memory and can be either fixed size or extensible, you can also choose not to implement garbage collection. The main targets for this area are constant pool reclamation and type offloading
      • An OutOfMemoryErroy exception is thrown when the method area cannot meet memory allocation requirements
    • 1.6 Runtime constant pool
      • It is part of the method area. In addition to the version, field, method, and interface descriptions, the Class file contains the constant pool, which is used to store literal and symbolic references generated during editing. This is stored in the runtime constant pool when the Class is loaded into the method area
      • The Java language does not require that constants be generated only at edit time, which means that new constants can be pooled. One feature that developers use most often is the Intern () method of the String class
      • An OutOfMemoryError is raised when the constant pool can no longer allocate memory

6.0.0.2 Memory Layout of objects? What are the ways in which objects are accessed and located? What are the advantages of pointer access versus handle access?

  • Object memory layout?
    • In the HotSpot VIRTUAL machine, the layout of objects stored in memory can be divided into three areas: object headers, instance data, and aligned padding
    • The object header consists of two parts:
      • A) Store the runtime data of the object itself, such as hash code, GC band age, lock status flag, thread held lock, bias thread ID, bias timestamp
      • B) The other part refers to the type pointer, that is, the pointer of an object to its class metadata, which the virtual machine uses to determine which class the object is an instance of
  • What are the ways in which objects are accessed and located?
    • Access using a handle
      • The Java heap will be divided into a chunk of memory as a handle pool. Reference stores the handle address of the object, and the handle contains the specific address of the instance data and type data of the object
    • Use direct pointer access
      • The layout of Java heap objects must consider how to access information about type data, whereas refreence stores directly the address of the object
  • What are the advantages of pointer access versus handle access?
    • Handle access advantage: Reference stores the handle address of a stable point, and only changes the instance data pointer in the handle when the object is moved (a very common behavior in garbage collection). Reference itself does not need to be modified
    • Advantages of using direct pointer access: It is faster, saves the time cost of a pointer location, and since objects are accessed very frequently in Java, this overhead can add up to a significant execution cost
    • Tech blog summary

6.0.0.3 What is the object creation process? Where does the variable creation process go on the virtual machine?

  • What is the object creation process? For example: Dog Dog = new Dog();
    • When the virtual machine executes the new directive, it first looks for “Dog” in the constant pool to see if it can locate symbolic references to the Dog class. If so, the class has been loaded into the method area and continues execution. If not, let the Class Loader load the Class first.
    • The virtual machine then starts allocating memory for the object, and the amount of memory the object needs is determined after the class is loaded. At this point, you simply allocate space in the heap as needed. There are two ways to allocate memory. The first way is that the memory is absolutely regular, so as long as a pointer is placed between occupied memory and free memory, and each time the pointer is allocated, it only needs to move the pointer to the free memory space. When an object is collected by GC, some object memory needs to be migrated. In the second case, free memory is mixed with non-free memory, so you need to keep a list of heap memory usage, and then allocate memory as needed.
    • In the case of multiple threads, how do you ensure that if one thread allocates object memory but has not modified the memory management pointer, another thread allocates that block of memory and overwrites it? One way to do this is to have each thread preallocate a small chunk of memory in the heap (TLAB local thread allocation buffer), and each thread only allocates memory in its own memory. But the object itself is thread – shared access by its access properties.
    • After memory is allocated, the virtual machine initializes all allocated memory space to zero (excluding object headers). Instance variables are initialized to default values (0 for numeric type and False for Boolan), so instance variables can be used without an initial value. Then set the object header information, such as the object’s hash value, GC generation age, and so on. Tech blog summary
    • From the virtual machine’s point of view, a new object has been created. But from the point of view of our program, the new object is just beginning, the object constructor has not been executed. The object is not completely created until the constructor is executed and initialized according to the constructor. Constructor execution also involves calling the parent constructor, which automatically adds a default constructor if no explicit declaration is made to call the parent constructor.
    • The new operator returns a reference to the object in the heap
  • Where does the variable creation process go on the virtual machine?
    • Variables are instance variables, local variables, or static variables that place references in different places:
      • If the dog local variable, the dog variable is local to the stack frame, the reference to that object is placed in the stack frame.
      • If dog is an instance variable, the dog variable is in the heap, and the reference to the object is in the heap.
      • If dog is a static variable, the dog variable is in the method area, and the reference to the object is in the method area.

6.0.0.4 In which data regions may OutOfMemoryError occur? Please describe the scenario and reason why OOM appears in this data area.

  • In which data regions may OutOfMemoryError occur?
    • The Java heap overflow
    • The virtual machine stack and the local method stack overflow
    • Method area and runtime constant pool overflow
  • Please describe the scenario and reason why OOM appears in this data area.
    • The Java heap overflow
      • The Java heap is used to store object instances, and as long as objects are constantly created and there are reachable paths between GCRoots and objects to avoid garbage collection, overflow exceptions will occur after the maximum heap capacity is reached
      • If it is a memory leak, you can further look at the leak object’s chain of references to GC Roots through the tool. You can then find out what path the leak objects took to associate with GC Roots and cause the garbage collector to fail to reclaim them automatically. With the information of the type of the leaking object and GC Roots reference chain, the location of the leaking code can be more accurately located
      • If there is no leakage, in other words, it is an in-memory object does also have to live with, it shall check the pile of parameters of the virtual machine (-xmx and – Xms), compared with the machine physical memory to see if can also big, check whether there is a certain object lifecycle from the code is too long, the state holding time is too long, Try to reduce the memory consumption of the program’s runtime
    • The virtual machine stack and the local method stack overflow
      • For HotSpot, although the -xoss parameter (to set the local method stack size) exists, it is not actually valid and the stack size is only set by the -xss parameter. With respect to the virtual machine stack and the local method stack, two exceptions are described in the Java Virtual Machine specification:
      • StackOverflowError is raised if the stack depth requested by the thread is greater than the maximum depth allowed by the virtual machine
      • An OutOfMemoryError is thrown if the virtual machine cannot allocate enough memory while extending the stack
      • In a single thread, the virtual machine throws StackOverflowError when memory cannot be allocated, either because the stack frame is too large or because the virtual machine stack is too small
      • If the memory overflow is caused by multiple threads, there is no relation to whether the stack space is large enough. In this case, the larger the memory allocated by the stack of each thread, the more likely it is to generate memory overflow exceptions. The solution is to reduce the maximum heap and reduce the stack size in exchange for more threads without reducing the number of threads or replacing 64 virtual machines
    • Method area and runtime constant pool overflow
      • String. Intern () is a Native method that returns a String representing the String in the String constant pool if it already contains a String equal to the String. Otherwise, the String contained in this String is added to the constant pool and a reference to this String is returned
      • Since the constant pool is allocated in a permanent generation, you can indirectly limit the capacity of the constant pool by limiting the size of the method area by -xx :PermSize and -xx :MaxPermSize. Tech blog summary
      • Intern(): The JDK1.6 Intern method copies the first encountered string instance to the persistent generation and returns a reference to the string instance in the persistent generation. The string instance created by StringBuilder is on the Java heap, so it must not be a reference. The implementation of the JDK1.7 Intern () method no longer copies the instance, just records the first instance reference in the constant pool, so intern() returns the same reference as the string instance created by StringBuilder

6.0.0.6 What is the difference between heap and stack in Java? Write programs that run out of heap memory and stack memory separately?

  • What is the difference between a heap and a stack in Java?
    • Stack memory: mainly used to store basic data types and local variables; When a variable is defined in a block of code, it is allocated memory space on the stack, which is automatically freed when the variable’s scope is exceeded.
    • Heap memory: used to hold objects created at run time, such as objects and arrays created by the new keyword; It needs to be managed by the Java virtual machine’s automatic garbage collector.
  • Write programs that run out of heap memory and stack memory separately?
    • Stack overflow
    public void A() {
        A();
    }
    Copy the code
    • Heap overflow
    public void testd() {
        List<String> list = new ArrayList<>();
        int i = 0;
        while (true) {
            list.add(new String(i + "")); i++; }}Copy the code

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

  • 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.
    • This means that when a reference to an object becomes null, it is not immediately collected by the garbage collector, but is freed at the next garbage collection.

6.0.0.8 What are the methods of Garbage collection in Java?

  • What are the methods of garbage collection in Java
    • Mark-clear:
      • This is the most basic garbage collection algorithm, and as you can tell by name, the idea is to mark which objects are to be collected and then collect them all. This method is very simple, but there are two main problems: 1. Low efficiency, marking and clearing efficiency is very low; 2. 2. A large number of discrete memory fragments can be generated, causing a GC action to be triggered prematurely when the program allocates larger objects 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.
      • Therefore, the algorithm was improved. Instead of 1:1, the memory region was divided into 8:1:1 three parts. The larger memory region was Eden region, and the remaining two smaller memory regions were Survior region. If Eden is full, objects will be copied to the second memory block, and then Eden will be cleared. If there are too many surviving objects so that there are not enough survivors, these objects will be copied to the old age through the allocation guarantee mechanism. (Java heap is divided into new generation and old generation)
    • Mark-tidyTech blog summary
      • This algorithm is mainly to solve the problem of large amount of memory fragmentation caused by mark-clear. When the object survival rate is high, the efficiency of the replication algorithm is also solved. The difference is that it now moves the recyclable objects to one end when it clears objects, and then clears objects beyond the end boundary, so there is no memory fragmentation.
    • Generational collection
      • 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. In the old days, objects have a higher survival rate and no extra space to allocate guarantees, so mark-tidy or mark-clear can be used.

6.0.1.1 How to Determine whether an object survives and? Which is better, reference-counting or reachability? How to understand that an object is not necessarily recycled?

    1. Reference counting method
    • Reference counting sets a reference counter for each object, incrementing the counter every time the object is referred to somewhere, and decrement it every time the reference fails. When an object’s reference counter is zero, the object is not referenced, which is a “dead object” and will be garbage collected.
    • Reference counting method has A defect that it cannot solve the problem of circular reference. That is, when object A refers to object B, object B refers to object A, then the reference counter of object A and object B is not zero, and garbage collection cannot be completed. Therefore, mainstream virtual machines do not use this algorithm.
  • 2. Reachability algorithm (chain of references)
    • The idea is to search down from an object called GC Roots, and if an object is not connected to GC Roots by any reference chain, the object is unavailable.
    • There are several objects that can be used as GC Roots in Java:
      • Object referenced in the virtual machine stack
      • Method area the object referenced by the static property of the class
      • The object referenced by the method area constant pool
      • Objects referenced by the local method stack JNI
  • How to understand that an object is not necessarily recycled?Tech blog summary
    • 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 to GC Root, it is not immediately recycled, but rather in a dormant phase, and is marked twice before it can actually be recycled
    • If the object has no reference chain with GCRoot in the reachability analysis, then it will be marked for the first time and filtered based on whether it is necessary to execute the Finalize () method. Objects that do not override the Finalize () method or have already been called by a virtual machine are considered unnecessary.
    • If it is necessary for the object to execute finalize(), then the object will be put ina pair Queue called f-queue, and the virtual machine will trigger a Finalize() thread to execute, which is of low priority, and the virtual machine will not promise to wait until finalize() is finished. This is because if Finalize () is executed slowly or deadlocks occur, the F-queue will wait forever, causing the crash of the memory reclamation system. The GC marks the object in the f-queue a second time, at which point the object is removed from the collection to be collected.

6.0.1.2 Difference between class.forname () and classLoader.loadClass ()?

  • Is class.forname () different from classLoader.loadClass ()?
    • It asks about reflection, but at the bottom it involves virtual machine class loading knowledge.
    • By default, class.forname () performs the join and initialization actions during Class loading. Once the initialization action is performed, static variables are initialized to the values set by the programmer, and static code blocks, if any, are executed
    • Classloader.loadclass () by default only performs loading actions during class loading

The other is introduced

01. About blog summary links

  • 1. Tech blog round-up
  • 2. Open source project summary
  • 3. Life Blog Summary
  • 4. Himalayan audio summary
  • 5. Other summaries

02. About my blog

  • My personal website: www.yczbj.org, www.ycbjie.cn
  • Github:github.com/yangchong21…
  • Zhihu: www.zhihu.com/people/yang…
  • Jane: www.jianshu.com/u/b7b2c6ed9…
  • csdn:my.csdn.net/m0_37700275
  • The Himalayan listening: www.ximalaya.com/zhubo/71989…
  • Source: China my.oschina.net/zbj1618/blo…
  • Soak in the days of online: www.jcodecraeer.com/member/cont.
  • Email address: [email protected]
  • Blog: ali cloud yq.aliyun.com/users/artic… 239.headeruserinfo.3.dT4bcV
  • Segmentfault headline: segmentfault.com/u/xiangjian…
  • The Denver nuggets: juejin. Cn/user / 197877…