Two hundred questions about JAVA knowledge (181~200)

181. What are the redis elimination strategies?

• Volatile-lru: Select the least recently used data from the data set (server. db[i]. expires) for which the expiration time has been set.
• Volatile-ttl: select the data that will expire from the data set (server. db[i]. expires) that has set expiration time.
• Volatile-random: arbitrarily select data to be eliminated from the data set (server. db[i]. expires) for which the expiration time has been set.
• allkeys-lru: Select the least recently used data from the data set (server. db[i]. dict) and eliminate it.
• allkeys-random: arbitrarily select data to eliminate from the data set (server. db[i]. dict).
• no-enviction (eviction): prohibit eviction of data.

182. What are the common performance problems of redis? How to solve it?

• When the main server writes a memory snapshot, it will block the work of the main thread. When the snapshot is large, the performance impact will be very large, and the service will be intermittently suspended. Therefore, the main server is best not to write the memory snapshot.
• Redis master-slave replication performance issues. For the speed of master-slave replication and the stability of the connection, the master-slave library should preferably be in the same LAN.

183. Tell me about the main components of jvm? And its role?

• ClassLoader (ClassLoader)
• Runtime Data Area (Runtime Data Area)
• Execution Engine (Execution Engine)

The role of Native Interface components: First, the Java code will be converted into a class loader (ClassLoader) Bytecode, the Runtime Data Area (Runtime Data Area) then loads the bytecode into the memory, and the bytecode file is just a set of instruction set specifications of the JVM and cannot be directly handed over to the underlying operating system for execution, so it needs The specific command parser execution engine (Execution Engine) translates the bytecode into the underlying system instructions, which are then executed by the CPU. In this process, the Native Interface of other languages ​​needs to be called to realize the entire program. Features.

184. Tell me about the jvm runtime data area?

During the execution of the Java program, the Java virtual machine divides the memory it manages into several different data areas. These areas have their own purposes, the time of first level creation and destruction, some areas exist with the start of the virtual machine process, and some areas are created and destroyed depending on the start and end of the user thread. According to the "Java Virtual Machine Specification", the memory managed by jvm roughly includes the following runtime data areas, as shown in the figure:
Insert picture description here

1. The program counter
  occupies a small memory space and can be seen as a line number indicator of the bytecode executed by the current thread. In the virtual machine conceptual model, when the bytecode interpreter works, it selects the next bytecode instruction to be executed by changing the value of this counter. Basic functions such as branch, loop, jump, exception handling, and thread recovery are all required. Rely on this counter to complete.

Since the multi-threading of JVM is realized by the way that threads alternately switch and allocate processor execution time, at any certain moment, a processor will only execute instructions in one thread. Therefore, after thread switching in the future, it can be restored to the correct execution position. Each thread needs to have an independent program counter. The counters between the threads do not affect each other and are stored independently. We make this type of memory area "thread private" RAM.

If the thread is executing a Java method, this counter records the address of the virtual machine bytecode instruction being executed;

If the native method is being executed, this counter is empty (undefined).

This memory area is the only area that does not specify any OutOfMemoryError conditions in the Java Virtual Machine Specification.

2. The Java virtual machine stack
  thread is private, and the life cycle is the same as the thread. The virtual machine stack describes the memory model of the Java method execution. When each method is executed, a stack frame is created to store the local variable table and the operand stack. , Dynamic link, method export and other information. The process from invocation to completion of each method corresponds to the process of pushing a stack frame in the virtual machine stack to popping out of the stack.

The local variable table stores various basic types of data known at compile time (boolean, byte, char, short, int, float, long, double), object references, and returnAddress types (pointing to the address of a bytecode instruction).

The 64-bit long and double data will occupy two local variable table spaces (slots), and the remaining data types will only occupy one. The memory space required by the local variable table is allocated at compile time. When entering a method, how much local variable space the method needs to allocate in the stack frame is completely determined, and the local variable table will not be changed during the running of the method. size.

In the Java virtual machine specification, there are two exceptions for this area: If the stack depth requested by the thread is greater than the depth allowed by the virtual machine, a Stack OverflowError exception will be thrown; if the virtual machine stack can be dynamically expanded, it cannot be applied. If there is enough memory, OutOfMemoryError will be thrown.

3. Local method stack
  The role played by the local method stack and the virtual machine stack is very similar. The difference between them is that the virtual machine stack executes Java methods (bytecode) services for the virtual machine, while the local method stack is the virtual machine. Native method service used in In the virtual machine specification, the language, usage, and data structure of the method in the local method stack are not mandatory, so the specific virtual machine can freely implement it. Even some virtual machines directly combine the local method stack and virtual machine stack into one, and like the virtual machine stack, Stack OverflowError and OutOfMemoryError exceptions will also be thrown.

4. Java heap
  For most applications, the heap space is the largest piece of jvm memory. The Java heap is shared by all threads and is created when the virtual machine starts. The only purpose of this memory area is to store object instances. Almost all object instances allocate memory here. This point is described in the Java virtual machine specification: all object instances and arrays must be allocated on the heap, but with the development of the JIT compiler and the gradual maturity of escape analysis techniques, allocation on the stack, scalar replacement optimization technology will As a result of some subtle changes, all objects are allocated on the heap and it becomes less absolute.

The Java heap is the main area managed by the garbage collector, so it is often called the "GC heap". From the perspective of memory recovery, since collectors now basically use generational collection algorithms, Java heaps can also be subdivided into: new generation and old generation; more detailed ones include Eden space, From Survivor space, To Survivor space, etc. From the perspective of memory allocation, the Java heap shared by threads may be divided into multiple thread-private allocation buffers. However, no matter what the division is, it has nothing to do with the storage content. No matter which area, the storage is still the object instance. The purpose of further division is to better reclaim memory or allocate memory faster. (If there is no memory in the heap to complete the instance allocation, and the heap can no longer be expanded, an OutOfMemoryError will be thrown.)

5. The method area (also called permanent generation) is
  shared by all threads like the heap, and is mainly used to store data such as class information, constants, static variables, and code compiled by the JVM that have been loaded by the jvm.

(In HotSpot released by JDK1.7, the string constant pool has been removed from the method area.)

6. Constant pool: The
  runtime constant pool is part of the method area. In addition to the description information of the class version, fields, methods, and interfaces in the Class file, there is also a constant pool, which is used to store various literal and symbol references generated during compilation. This part of the content will be after the class is loaded It is stored in the runtime constant pool in the method area.

The Java virtual machine has strict regulations on the format of each part of the class file, and what kind of data each byte is used to store must conform to the specification before it can be recognized by the jvm. But for the runtime constant pool, the Java virtual machine specification does not make any detailed requirements.

An important feature of the runtime constant pool is dynamic. The Java language does not require constants to be generated only during compilation, that is, the content of the constant pool in the class file is not preset to enter the runtime constant pool in the method area. During runtime It is also possible to put new constants into the pool. This feature is most commonly used in the intern() method of the String class.

Since the runtime constant pool is part of the method area, it is naturally limited by the memory of the method area. When the constant pool can no longer apply for memory, an outOfMemeryError exception will be thrown.

185. Tell me about the difference between stacks?

  1. The stack memory stores local variables and the heap memory stores entities;
  2. The update speed of stack memory is faster than heap memory, because the life cycle of local variables is very short;
  3. The variables stored in the stack memory will be released once their life cycle ends, and the entities stored in the heap memory will be reclaimed from time to time by the garbage collection mechanism.

186. What are queues and stacks? What's the difference?

• Both queues and stacks are used to pre-store data.
• The queue allows first-in, first-out to retrieve elements, but there are exceptions. The Deque interface allows elements to be retrieved from both ends.
• The stack is very similar to the queue, but it runs a last-in, first-out retrieval of elements.

187. What is the parental delegation model?

Before introducing the parent delegation model, let's talk about the class loader. For any class, the uniqueness in the JVM must be established by the class loader that loads it and the class itself. Each class loader has an independent class name space. The class loader loads the class file into the JVM memory according to the specified fully qualified name, and then converts it into a class object.
Class loader classification :
1 Start the class loader (the JVM providers use native code to implement the Bootstrap class loader)

The boot class loader (BootstrapClassLoader) is a class loader implemented with native code. It is responsible for loading the core class library under /lib or the jar package specified by the -Xbootclasspath option into memory. Since the boot class loader involves the details of the local implementation of the virtual machine, developers cannot directly obtain a reference to the boot class loader, so direct operations by reference are not allowed.

The startup class loader is the lowest level loader. It is written in C++. Because the loader is a class, it also needs to be loaded through the class loader. The startup class loader can complete this function.

2 extended class loader

The extension class loader (ExtensionClassLoader) is implemented by the ExtClassLoader class. It is responsible for loading into memory the class library in <Java_Runtime_Home >/lib/ext or the location specified by the system variable -Djava.ext.dir. Developers can directly use the standard extended class loader.

3 System Class Loader
System ClassLoader (SystemClassLoader) is implemented by the AppClassLoader class. It is responsible for
loading the class library in the directory pointed to by the system class path java -classpath or -Djava.class.path variable into the memory. It is also used to load the entry function class (only the class containing the main() method). Developers can directly use the system class loader.

Parent delegation model : If a class loader receives a class loading request, it will not first load the class by itself, but will delegate the request to the parent class loader to complete it, which is the case for each layer of class loader , So that all loading requests will be transmitted to the top-level startup class loader. Only when the parent loading cannot complete the loading request (the required class is not found in its search range), the child loader will try to load the class .

188. Tell me about the execution process of class loading?

Class loading is divided into the following 5 steps:
1. Loading : Find the corresponding class file according to the search path and import it;
2. Check : check the correctness of the loaded class file;
3. Preparation : allocate memory space for static variables in the class ;
4. Analysis : The process of replacing symbol references in the constant pool with direct references by the virtual machine. Symbol reference is understood as a sign, and direct reference directly points to an address in memory;
5. Initialization : Perform initialization of static variables and static code blocks.

189. How to judge whether the object can be recycled?

There are generally two ways to judge:
Reference counter : Create a reference count for each object. When there is an object reference, the counter is +1, when the reference is released, it counts -1. When the counter is 0, it can be recycled. It has a shortcoming that it cannot solve the problem of circular references;
Reachability analysis : starting from GC Roots and searching downward, the path taken by the search is called the reference chain. When an object is not connected to the GC Roots by any reference chain, it is proved that the object can be recycled.

190. What reference types are there in java?

1 Strong references The
default declarations in Java are strong references, such as:

Object obj = new Object(); //只要obj还指向Object对象,Object对象就不会被回收
obj = null;  //手动置null

As long as the strong reference exists, the garbage collector will never reclaim the referenced object . Even when the memory is insufficient, the JVM will directly throw OutOfMemoryError instead of reclaiming it. If you want to interrupt the connection between the strong reference and the object, you can explicitly assign the strong reference to null, so that the JVM can recycle the object in a timely manner

2 Soft references
Soft references are used to describe some unnecessary but still useful objects. When the memory is sufficient, the soft reference object will not be reclaimed. Only when the memory is insufficient, the system will reclaim the soft reference object. If there is still not enough memory after the soft reference object is reclaimed, a memory overflow exception will be thrown . This feature is often used to implement caching technologies, such as web page caching, image caching, etc.

3 Weak references
The reference strength of weak references is weaker than soft references. Regardless of whether the memory is sufficient, as long as the JVM starts garbage collection, those objects associated with weak references will be collected . After JDK1.2, java.lang.ref.WeakReference is used to represent weak references.

4 Phantom reference
phantom reference is a reference to the weakest relationship, if a phantom reference object holds only, and then it does not have any references, it may be recovered at any time , after JDK1.2, with classes to represent PhantomReference By looking at the source code of this class, it is found that it has only one constructor and one get() method, and its get() method only returns a null, which means that the object will never be obtained through a virtual reference, which must To be used with ReferenceQueue reference queue. The reference queue can be used in conjunction with soft references, weak references, and virtual references. When the garbage collector is about to recycle an object, if it finds that it still has a reference, it will add this reference to the associated object before reclaiming the object. Reference to the queue. The program can determine whether the referenced object will be garbage collected by judging whether the reference has been added to the reference queue, so that some necessary measures can be taken before the object is recycled.

191. Tell me about what garbage collection algorithms does jvm have?

• Marking-clearing algorithm
• Marking-sorting algorithm
• Copying algorithm
• Generational algorithm

192. What garbage collectors does jvm have?

• Serial: The earliest single-threaded serial garbage collector.
• Serial Old: The older version of the Serial garbage collector, which is also single-threaded and can be used as an alternative to the CMS garbage collector.
• ParNew: is a multi-threaded version of Serial.
• Parallel and ParNew collectors are similarly multi-threaded, but Parallel is a throughput-first collector, which can sacrifice waiting time in exchange for system throughput.
• Parallel Old is the old generation version of Parallel. Parallel uses the copied memory reclamation algorithm, and Parallel Old uses the mark-define memory reclamation algorithm.
• CMS: A collector that aims to obtain the shortest pause time, which is very suitable for B/S systems.
• G1: A GC implementation that takes into account throughput and pause time. It is the default GC option after JDK 9.

193. Tell me more about the CMS garbage collector?

CMS is the abbreviation of Concurrent Mark-Sweep in English. It is a garbage collector that obtains the shortest recovery pause time at the expense of throughput. For applications that require server response speed, this garbage collector is very suitable. Add "-XX:+UseConcMarkSweepGC" to the parameters of starting the JVM to specify the use of the CMS garbage collector.
CMS uses a mark-sweep algorithm, so a large number of memory fragments are generated during gc. When the remaining memory cannot meet the requirements of program operation, the system will appear Concurrent Mode Failure, and the temporary CMS will use the Serial Old collector. Perform garbage removal, the performance at this time will be reduced.

194. What are the new generation garbage collectors and old generation garbage collectors? What's the difference?

• New-generation collectors: Serial, ParNew, Parallel Scavenge
• Old-generation collectors: Serial Old, Parallel Old, CMS
• Whole heap collector: G1
new-generation garbage collectors generally use replication algorithms, and the advantage of replication algorithms is efficiency High, the disadvantage is that the memory utilization is low; the old-age collector generally uses the mark-sort algorithm for garbage collection.

195. Briefly describe how the generational garbage collector works?

The generational collector has two partitions: the old generation and the young generation. The default space for the new generation takes up 1/3 of the total space, and the default space for the old generation is 2/3.
The new generation uses the replication algorithm. There are 3 partitions in the new generation: Eden, To Survivor, From Survivor, their default ratio is 8:1:1, and its execution process is as follows:
• Surviving Eden + From Survivor The object is placed in the To Survivor area;
• Eden and From Survivor partitions are cleared;
• From Survivor and To Survivor partitions are exchanged, From Survivor to To Survivor, To Survivor to From Survivor.
Objects that survive every time they move from From Survivor to To Survivor have their age +1, and when they reach 15 (the default configuration is 15), they are upgraded to the old generation. Large objects will also enter the old generation directly.
When the space occupied by the old generation reaches a certain value, the global garbage collection will be triggered. Generally, the execution algorithm of marking and sorting is used. The above cycles constitute the overall execution process of the entire generational garbage collection.

196. Tell me about the jvm tuning tool?

The JDK comes with many monitoring tools, which are located in the bin directory of the JDK. The most commonly used are jconsole and jvisualvm, two view monitoring tools.
• jconsole: used to monitor the memory, threads and classes in the JVM;
• jvisualvm: the all-round analysis tool that comes with the JDK, which can analyze: memory snapshots, thread snapshots, program deadlocks, monitoring memory changes, gc changes, etc. .

197. What are the commonly used jvm tuning parameters?

• -Xms2g: the initial push size is 2g;
• -Xmx2g: the maximum heap memory is 2g;
• -XX:NewRatio=4: set the memory ratio of the young and old generations to 1:4;
• -XX:SurvivorRatio=8: Set the ratio of Eden and Survivor of the new generation to 8:2;
• -XX:+UseParNewGC: Specify the ParNew + Serial Old garbage collector combination;
• -XX:+UseParallelOldGC: Specify the ParNew + ParNew Old garbage collector combination;
•- XX:+UseConcMarkSweepGC: Specify the CMS + Serial Old garbage collector combination;
• -XX:+PrintGC: enable printing gc information;
• -XX:+PrintGCDetails: print gc detailed information.

198. Under what circumstances will stack memory overflow occur.

The stack is private to the thread, and its life cycle is the same as that of the thread. When each method is executed, a stack frame is created to store the local variable table, operand stack, dynamic link, method export and other information. The local variable table also contains basic data types and object reference types.
If the stack depth requested by the thread is greater than the maximum depth allowed by the virtual machine, a StackOverflowError exception will be thrown, and the method recursive call produces this result.
If the Java virtual machine stack can be dynamically expanded, and the expansion action has been tried, but cannot apply for enough memory to complete the expansion, or there is not enough memory to create the corresponding virtual machine stack when a new thread is created, then Java virtual The machine will throw an OutOfMemory exception. (Too many threads started)

199. How to print thread stack information.

  1. Enter jps to get the process number.
  2. top -Hp pid Get the CPU time-consuming performance of all threads in this process
  3. jstack pid command to view the stack status of the current java process
  4. Or jstack -l> /tmp/output.txt to print the stack information to a txt file.
  5. You can use fastthread stack positioning, fastthread.io/

200. How to judge whether there is a memory leak?

Leaks can be compared to memory allocation at different points in time. Generally, it depends on the allocation of user types and what is increasing. Specifically, for example, using jmap -histo:live to take multiple snapshots and then compare the differences, or use profiling tools such as jmc, the comparison will be smoother
. What are the ways to locate the cause of Full GC?
1. First check the fullgc frequency and duration through printgcdetail
2. Check which objects are in the memory through dump, which may be the cause of fullgc, and see if it can be optimized
3. If the heap is large or the production environment, you can start jmc and fly for a while , Check the relevant data during this period to make reservations

Guess you like

Origin blog.csdn.net/cyb_123/article/details/107622031