JavaEE Interview Collection

JavaEE Interview Collection

1. SpringCloud Microservice

1.1. Registration Center (Eureka, Zookeeper, Nacos)

The registry has two cores, which are divided into provider (service provider) and consumer (service consumer), also known as Web and Service. The provider and consumer are registered to the client of the registry, and the module name is used when calling The client obtains the ip and port number to call. Eureka guarantees availability, Zookeeper guarantees consistency, please search CAP theory for details

1.1.1. Eureke

Eureka is currently the most popular registry component in China. Although it has been discontinued, its popularity remains unchanged. It is still officially recommended by SpringCloud. Support clusters, the implementation method is to register each other.

1.1.1.1. Eureka-module call

Eureka uses crp remote call (crp is the distributed connection method of zookeeper, which is used to call it in China), and the underlying protocol is HTTP.

1.1.1.2. Heartbeat and self-protection mechanism

After the application is started, the nodes will send heartbeats to Eureka Server. The default period is 30 seconds. If Eureka Server does not receive a heartbeat from a node in multiple heartbeat cycles, Eureka Server will send this from the service registry. Service node removal (default 90 seconds)

During operation, Eureka Server will count whether the heartbeat failure rate is less than 85% within 15 minutes. If it is less than 85%, Eureka Server will protect these instances so that these instances will not expire, but during the protection period if The service happens to be abnormally offline by the service provider. At this time, the service consumer will get an invalid service instance, and the call will fail. For this problem, the service consumer must have some fault tolerance mechanisms, such as retry , Circuit breaker, etc.

1.1.2. Zookeeper

It is a distributed service framework and a sub-project of Apache Hadoop. It is mainly used to solve some data management problems often encountered in distributed applications, such as: unified naming service, state synchronization service, cluster management, distributed Application configuration item management, etc.

Dubbo (Ali, similar to SpringCloud) recommends using Zookeeper as the service registry

1.1.3. Nacos ** (recommended to learn or understand)**

Nacos is a registration center launched by Ali, and integrates the functions of the configuration center Config and the message bus Bus. It has great potential and is worth learning by yourself. Web pages are provided, which greatly simplifies the learning cost.

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-L2zas5Az-1600746909872)(file:///C:\Users\ADMINI~1\AppData\Local\Temp \ksohtml7636\wps1.jpg)]

1.2. Load Balancing-Ribbon

Load balancing is an algorithm used to solve all the requests that a machine (a process) cannot solve. For example, nginx can use load balancing to distribute traffic, ribbon provides load balancing for clients, load balancing in dubbo service calls, etc. Load balancing is used in many places.

There are several implementation strategies for load balancing, the common ones are:

  1. RoundRobin-(default)

  2. Random

  3. Consistent Hash (ConsistentHash)

  4. Hash

  5. Weighted

1.3. Declarative Service Invocation-Feign

  1. Feign can hide the request of Rest and pretend to be a Controller similar to SpringMVC. You don't need to splice URLs, splicing parameters and so on by yourself. Feign will do everything.

  2. Feign uses Ribbon at the bottom, so load balancing is supported by default.

  3. OpenFeign is that springcloud supports SpringMVC annotations, such as @RequestMapping, etc. on the basis of Feign. OpenFeign's @FeignClient can parse the interface under SpringMVC's @RequestMapping annotation, and generate implementation classes through dynamic proxy, implement load balancing in the class and call other services.

1.4. Service gateway (Zuul, Zuul2, GetWay)

Service gateway = route forwarding + filter

1. Routing and forwarding: receive all external requests and forward them to the back-end microservices

2. Filter: A series of cross-cutting functions can be completed in the service gateway, such as permission verification, current limiting and monitoring, etc.

1.4.1. Zuul

1. Routing-all requests access consumer through zuul

2. Fault tolerance-the client cannot call the consumer through zuul, use zuul to downgrade the consumer

3. Current limit-use the token bucket algorithm to implement Zuul's current limit on the consumer

1.4.2. Zuul2

Zuul2 and Zuul are both service gateways developed by Netflix, but due to the company's decision-making issues, the core personnel who developed Zuul changed and the development was delayed, so it is currently in the new version testing stage.

1.4.2. GetWay ** (recommended to learn or understand) **

GetWay is a service gateway component officially launched by SpringCloud. Due to the postponement of Zuul2, SpringCloud officially decided to develop its own service gateway component. So far, GetWay turned out to be very popular in foreign countries, but Zuul is basically used in China. GetWay and Zuul2 are implemented, asynchronous non-blocking model.

1.5. Service degradation (Hystrix, Sentinel)

1.5.1. Hystrix

1. Downgrade

​ When the service provider cannot call the service consumer, use Hystrix to downgrade the service consumer and return the bottom data

2. Fuse

​ When the failure rate, thread pool and semaphore reach the threshold, the downgrade is automatically triggered. The downgrade triggered by the fuse will test whether the service is restored after a specified time. (The next request after 5 seconds by default will test whether the service is restored)

1.5.2. Sentinel ** (recommended to learn or understand)**

Sentinel is a new generation of circuit breaker degraded components launched by Ali. It does not require a lot of configuration when used like Hystrix.

Sentinel is a separate component, which can be independent, direct page-oriented, fine-grained unified configuration, and provides a set of Web pages to implement operations such as flow control, rate, degradation, and fuse.

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-9DZM8JcX-1600746909878)(file:///C:\Users\ADMINI~1\AppData\Local\Temp \ksohtml7636\wps2.jpg)]

1.6. Configuration Center Config and Message Bus Bus

Config Configuration Center: Used to centrally manage configuration files

Bus message bus: used to update the configuration file without restarting

work process:

  1. First send the configuration file to the remote GitHub

  2. Configure the GitHub address on the Config client

  3. Use postman to send a post request and notify the Config client to pull the configuration file

  4. After the configuration file is downloaded, send a message to the MQ queue

  5. Bus listens to the MQ queue, after receiving the message

  6. Bus sends MQ messages to notify the corresponding modules

  7. After the module receives the message, go to the Config client to get the configuration file and update it

2. Multithreading

Multithreading is very common in projects. For example, to efficiently read a large txt file, first split the txt file, and then use multithreading to read each shard, and then combine them together, which is the most efficient.

2.1. Multi-threaded implementation

  1. Inherit the Thread class:

Just override the run method. The disadvantage is that Java is single inheritance and multiple implementations. In this case, the class cannot inherit other classes, and it is generally not recommended.

  1. Implement the Runnable interface:

To solve the single inheritance problem of the Thread class, multi-threading can be realized. The disadvantage is that there is no return value, and the result cannot be received but void.

  1. Implement the Callable interface:

Java5 provides the Future interface to represent the return value of the call() method in the Callable interface, and provides an implementation class FutureTask for the Future interface.

  1. Obtained from the thread pool:

Use Executors to create threads and call threads, which can have return values. When using multiple threads on a large scale, it is recommended to use thread pools, and threads need to be closed after use.

2.2. Thread state

New status:

After creating a thread object using the new keyword and the Thread class or its subclasses, the thread object is in a newly created state. It remains in this state until the program starts() the thread.

Ready state:

When the thread object calls the start() method, the thread enters the ready state. Threads in the ready state are in the ready queue and wait for the scheduling of the thread scheduler in the JVM.

Operating status:

If the thread in the ready state acquires CPU resources, it can execute run(), and the thread is now in the running state. The thread in the running state is the most complicated, and it can become blocked, ready, and dead.

Blocked state:

If a thread executes sleep (sleep), suspend (suspend) and other methods, after losing the occupied resources, the thread enters the blocking state from the running state. The ready state can be re-entered after the sleep time is up or the device resources are obtained.

Death status:

When a thread in the running state completes its task or other termination conditions occur, the thread switches to the termination state.

3. Synchronization lock

3.1. The difference between Synchronized and Lock (ReentrantLock)

Synchronized is a modifier in java. It can modify classes, methods, and code blocks. It does not need to manually release the lock. If an exception occurs, the lock will be automatically released without causing a deadlock. The operation is simple.

Lock can only lock the code block and needs to manually release the lock. If the unLock method is not called to release the lock, it will cause a deadlock, and it provides some operation methods to easily obtain lock information.

4. MySQL database

4.1. The difference between InnoDB and MyISAM

InnoDB:

  1. Suitable for addition, deletion and modification

  2. Must have a primary key

  3. Support affairs

  4. Clustered index

  5. The minimum lock granularity is row-level lock

  6. Changed to the default storage engine after MySQL-5.5

MyISAM:

  1. Suitable for query

  2. Nonclustered index

  3. Slow recovery after system crash

  4. The minimum lock granularity is table-level lock

4.2. SQL statement execution order

from-on-join-where-group by-having-select-distinct-order by-limit

Table lookup-filtering-connection-filtering-grouping-filtering-specified column-deduplication-sorting-paging

4.3. B+ tree structure—with link to learning website

https://www.cs.usfca.edu/~galles/visualization/Algorithms.html

Binary tree:

Binary tree is the most basic tree structure. According to the first value, the small one is placed on the left and the large one is placed on the right.

Red-black tree:

The red-black tree is carried out on the basis of the binary tree, and the dynamic balance adjustment will not cause the chain to be too long.

B tree:

The B-tree is based on the red-black tree, which can be scaled horizontally on the nodes, and each node can be mounted with key-value data, which can reduce the number of IO queries

B+ tree:

B+ tree is an exclusive data structure developed by MySQL. Based on the B tree, it is cut off. The key-value data on the B tree only retains the key, and only has the key-value in the following node. Data, key is the primary key, value is determined based on whether the storage structure is InnoDB or MyISAM, and value is a disk address or data

5. JVM and GC

5.1. JVM memory model

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-XNK7Kuig-1600746909881)(file:///C:\Users\ADMINI~1\AppData\Local\Temp \ksohtml7636\wps3.png)]

JVM:https://www.bilibili.com/video/BV11J411N7Tg?from=search&seid=11648229642537222949

5.1.1. Program counter (thread private)

Record the sequence of program commands and the bytecode line number executed by the current thread. Each thread has an independent program counter. This type of memory is also called "thread-private" memory.

5.1.2. JAVA virtual machine stack (thread private) (stack)

Stored are declared variables and objects. When each method is executed, a stack frame is also created, storing local variables, operands, dynamic links, and method return addresses. Each method from invocation to completion of execution corresponds to the pushing and popping of a stack frame in the virtual machine stack. Generally speaking, the stack generally refers to the local variable part in the virtual machine stack.

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-HSbh8nsT-1600746909885)(file:///C:\Users\ADMINI~1\AppData\Local\Temp \ksohtml7636\wps4.png)]

Current stack frame: Represents the currently executing method, storing the variables, objects, operation commands and other related data and operation behaviors of the current method.

5.1.2.1. Local variable table

Store various basic data types, object reference types, and returnAddress types (pointing to the address of a bytecode instruction: function return address) that can be known at compile time.
Long and double occupy two local variable control Slots.
The memory space required by the local variable table is determined at compile time. When entering a method, the local variable control that the method needs to allocate in the stack frame is completely determined, and the size cannot be changed dynamically.

5.1.2.2. Operand stack

LIFO last in, first out, the maximum depth is determined by the compilation period. The stack frame has just been created, the operand stack is empty. When performing method operations, the operand stack is used to store the constants or variables copied by the JVM from the local variable table, provide extraction, and push the results to the stack, and also used to store the calls required by the method Parameters and results returned by the receiving method.
The operand stack can store a value of any data type defined in the jvm.
At any time, the operand stack has a fixed stack depth. Except for long and double, the basic types occupy two depths, and the others occupy one depth.

5.1.2.3. Dynamic link

Each stack frame contains a reference to the method to which the stack frame belongs in the runtime constant pool. This reference is held to support dynamic connection during method invocation. There are a large number of symbol references in the constant pool of the Class file, and the method call instruction in the bytecode takes the symbol reference pointing to the method in the constant pool as the parameter. Some of these symbol references will be converted into direct references (such as final, static domains, etc.) during the class loading stage or the first time they are used, which is called static resolution, and the other part will be converted into direct references during each run. The part is called dynamic connection.

5.1.2.4. Method export

When a method is executed, there are two ways to exit the method: the execution engine encounters a bytecode instruction returned by any method or encounters an exception, and the exception is not handled in the method body. No matter which exit method is used, after the method exits, it needs to return to the place where the method was called before the program can continue. When the method returns, it may need to save some information in the stack frame to help restore the execution state of its upper method. Generally speaking, when the method exits normally, the value of the caller's PC counter can be used as the return address. This counter value is likely to be stored in the stack frame. When the method exits abnormally, the return address is determined by the exception handler. , This part of information is generally not saved in the stack frame.
The process of method exit is actually equivalent to popping the current stack frame, so the operations that may be performed when exiting are: restore the local variable table and operand stack of the upper method, and if there is a return value, push it into the caller's stack frame In the operand stack, adjust the value of the PC counter to point to an instruction after the method call instruction.

5.1.3. Local method stack (understand)

Mainly use computer hardware calls, such as printers, keyboards, mice and other hardware devices, which have been abandoned. The system executes hardware commands instead of direct operations.

5.1.4. Heap (thread sharing)

A memory area shared by all threads, created when the virtual machine starts, and used to store object instances. The pair can be implemented as extensible (controlled by -Xmx and -Xms), which is also the main direction of GC recovery.

Heap memory is generally divided into young generation, old generation, and permanent generation. After JDK1.8, metaspace is used instead of permanent generation, because Oracle officially replaced another JVM developed according to the JVM convention.

5.1.5. Method area (thread sharing)

A memory area shared by all method threads.
Used to store class information, constants, static variables, etc. that have been loaded by the virtual machine.
The memory recovery target in this area is mainly for the recovery of the constant pool and the unloading of the heap type.

5.2. GC Garbage Collector

GC :https://www.bilibili.com/video/BV154411r7GP?p=7

5.2.1. Reference counting method

A counter is used to record the usage of each object. Objects with 0 usage times are reclaimed during GC, and the data is stored in the old generation when the usage times reaches 15.

Features: The counter needs to be maintained, and the use of the counter will also consume a certain amount of resources. JVM generally does not use this method.

5.2.2. Copy Algorithm

Open up two spaces in the memory, first store the data on one side, and copy the surviving data to the other side of the memory during GC and add the object age+1. If it reaches 15, the object will be stored in the old age. After the object is copied Then empty the memory.

Features: Double the memory space required.

This algorithm is used in the young generation, because the replication algorithm is suitable for the young generation with low survival rate

5.2.3. Mark removal

Divided into two steps

The first step is to mark: start scanning from the root collection and mark the surviving objects

The second step is to clean up: Scan the entire memory space, reclaim unmarked objects

Features: The two scans are time-consuming and cause memory fragmentation and no additional space is needed. However, the algorithm will suspend the entire application, otherwise there will be two scans, and the called object will be misjudged

5.2.4. Marker compression

Divided into two steps

The first step is to mark: same as mark clear, mark first and then clear

The second step of compression: scan again, and slide the surviving objects to a section

Features: There is no memory fragmentation, and the cost of moving objects is required.

Disadvantages of memory fragmentation: it will occupy the entire memory irregularly. For example, when an array needs to be created, because the array requires continuous use of space, it will be very troublesome if there is memory fragmentation.

Optimization: In order to reduce the cost of moving, you can design the compression operation when the GC is a certain number of times.

5.2.5. Optimal Algorithm

Mark clear *

Divided into two steps

The first step is to mark: start scanning from the root collection and mark the surviving objects

The second step is to clean up: Scan the entire memory space, reclaim unmarked objects

Features: The two scans are time-consuming and cause memory fragmentation and no additional space is needed. However, the algorithm will suspend the entire application, otherwise there will be two scans, and the called object will be misjudged

5.2.4. Marker compression

Divided into two steps

The first step is to mark: same as mark clear, mark first and then clear

The second step of compression: scan again, and slide the surviving objects to a section

Features: There is no memory fragmentation, and the cost of moving objects is required.

Disadvantages of memory fragmentation: it will occupy the entire memory irregularly. For example, when an array needs to be created, because the array requires continuous use of space, it will be very troublesome if there is memory fragmentation.

Optimization: In order to reduce the cost of moving, you can design the compression operation when the GC is a certain number of times.

5.2.5. Optimal Algorithm

There is no optimal algorithm, only the most suitable algorithm. The optimal algorithm is selected according to factors such as memory efficiency, memory neatness, and memory utilization.

Guess you like

Origin blog.csdn.net/zhang_yuanbai/article/details/108728459