2021/3/24 iQiyi (Unexpectedly cool scripture for telephone interview) How to deal with when the Redis cache data is full? Java exception architecture spring interceptor SQL injection

1Talk about your understanding of Sleep and wait?

1 Different classes: wait inherits object and sleep inherits Thread
2 handles locks differently: sleep does not release the lock, wait will release the lock
3 different scope of use: sleep can sleep anywhere, wait must In the synchronous code block

2 The life cycle of threads?

new,runnable,blocked,waiting,timed waiting,terminated

3 four ways of thread creation?

1 Inherit Thread 2 Implement Runnable 3 Implement Callable 4 Thread pool to create the way ThreadPoolExecutor

4 Seven parameters of thread pool


```java
public ThreadPoolExecutor(int corePoolSize,  //核心线程池大小,线程池中会维护一个最小的线程数量,即使这些线程处理空闲状态,他们也不会被销毁。
                          int maximumPoolSize, //一个任务被提交到线程池以后,首先会找有没有空闲存活线程,如果有则直接将任务交给这个空闲线程来执行,
                          //如果没有则会缓存到工作队列( BlockingQueue<Runnable> workQueue)中
                          //如果工作队列满了,才会创建一个新线程,然后从工作队列的头部取出一个任务交由新线程来处理,而将刚提交的任务放入工作队列尾部。线程池不会无限制的去创建新线程,
                          //它会有一个最大线程数量的限制,这个数量即由maximunPoolSize指定。

                          long keepAliveTime,  //一个线程如果处于空闲状态,并且当前的线程数量大于corePoolSize,那么在指定时间后,这个空闲线程会被销毁
                          TimeUnit unit, //超时单位
                          BlockingQueue<Runnable> workQueue, //新任务被提交后,会先进入到此工作队列中,任务调度时再从队列中取出任务
                          ThreadFactory threadFactory, //为线程池提供创建新线程的线程工厂
                          RejectedExecutionHandler handler //当工作队列中的任务已到达最大限制,并且线程池中的线程数量也达到最大限制,这时如果有新任务提交进来
                         ) 
}

5Redis basic data types

A plurality of types of data structures, such as a string (strings) , Hash (of the hashes) , lists (Lists) , set (sets) , an ordered set (sorted sets) and range queries, to the bitmaps , hyperloglogs and geospatial ( Geospatial ) Index radius query

6Redis persistence

1RDB (Redis DataBase)
writes a collective snapshot of the data in the memory to the disk within a specified time interval, which is also called a Snapshot in the jargon. When it is restored, it reads the snapshot file directly into the memory.

Redis will create (fork) a child process for persistence. It will first write the data to a temporary file. After the persistence process is over, it will replace the last persisted file with this temporary file. During the whole process, the main process does not perform any IO operations. This ensures extremely high performance. If large-scale data recovery is required, and the integrity of data recovery is not very sensitive, the RDB method is more efficient than the AOF method. The disadvantage of RDB is that the data after the last persistence may be lost. Our default is RDB, under normal circumstances there is no need to modify this configuration!
Sometimes we will back up this file in the production environment!
The file saved by rdb is dump.rdb is configured in the snapshot of our configuration file!

Triggering mechanism: 1 When the rules of save are met, the rdb rule will be automatically triggered. 2 Executing the fluxhall command will also trigger our rdb rule! 3 Exit redis, rdb files will also be generated!
Just put the rdb file in our redis startup directory. When redis starts, it will automatically check dump.rdb to restore the data!

Advantages:
1 Suitable for large-scale data recovery! 2 The integrity of the data is not high! 3 There is only one file dump.rdb, which is convenient for persistence. 4 To maximize performance, fork the child process to complete the write operation and let the main process continue to process commands, so IO is maximized. Use a separate sub-process for persistence. The main process will not perform any IO operations, which ensures the high performance of redis. 5 Compared with the large data set, it is more efficient than AOF in startup.
Disadvantages:
1 It takes a certain time interval to operate! If redis crashes unexpectedly, the last modified data will be gone! 2 When a fork process, it will take up a certain amount of memory space! !

2AOF (Append Only File)
AOF persistence (Append Only File persistence) is to record each write command executed by Redis into a separate log file. When Redis is restarted, the file in the persisted log will be restored. . When the two methods are enabled at the same time, the data recovery Redis will give priority to AOF recovery. AOF saves the appendonly.aof file

1 Every modification is synchronized, and the integrity of the file will be even better!
2Sync once per second, you may lose one second of data
3 Never sync, the most efficient!
Disadvantages:
1 Relative to the size of the data file, AOF is much larger than RDB, and the repair speed is also slower than RDB!
2Aof's operating efficiency is also slower than RDB, so our default configuration for redis is RDB persistence

7How to deal with when Redis cache data is full?

1. Add memory: This is the simplest and rude way, but the cost is relatively high

2. Memory elimination strategy
noeviction When the memory is insufficient to accommodate the newly written data, the new write operation will report an error
allkeys- lru When the memory is insufficient to accommodate the newly written data, in the key space, remove the least recently used key
allkeys- random When the memory is not enough to accommodate the newly written data, in the key space, a key is randomly removed
volatile- ttl When the memory is not enough to accommodate the newly written data, in the key space with the expiration time set, there is Priority removal of keys with earlier expiration time
3. Cluster to build a cluster

8The transaction mechanism of the database?

ACID principle of transaction
Atomicity (Atomicity) Atomicity
means that a transaction is an indivisible unit of work, and the operations in the transaction either all happen or never happen.
Consistency (Consistency)
The integrity of the data before and after the transaction must be consistent.
Durability Durability
means that once a transaction is committed, its changes to the data in the database are permanent, and then even if the database fails, it should not have any impact on it
. Isolation
The isolation of the transaction When accessing the database concurrently, a user's transaction is not interfered by other transactions, and the database is independent among concurrent transactions;

9Isolation level of the transaction?

Mysql default REPEATABLE_READ isolation level Oracle default READ_COMMITTED isolation level
Insert picture description here

10 Operation of basic query statement

Understanding of 11final keywords

Used to modify classes, attributes, and methods;
final-modified classes cannot be inherited,
final-modified methods cannot be overridden,
final-modified variables cannot be changed , and final-modified immutable is variable references, and Not the content pointed to by the reference, the content pointed to by the reference can be changed

12Java exception architecture

Insert picture description here

  1. Throwable
    Throwable is the superclass of all errors and exceptions in the Java language.
    Throwable contains two subclasses: Error and Exception, which are usually used to indicate that an abnormal situation has occurred.

  2. Error
    definition: Error class and its subclasses. An error that cannot be handled in the program means that a serious error has occurred in the running application .
    Features: This type of error generally indicates that there is a problem with the JVM when the code is running . Usually there are Virtual MachineError (virtual machine running error), NoClassDefFoundError (class definition error) and so on. For example, OutOfMemoryError: insufficient memory error ; StackOverflowError: stack overflow error . When such an error occurs, the JVM will terminate the thread.
    These errors are
    unchecked exceptions, non-code errors
    .

  3. Exception (exception) the
    program itself can catch and can handle exceptions . Exception This type of exception is divided into two categories: runtime exceptions and compile-time exceptions .

Runtime exception
definition: RuntimeException class and its subclasses represent the exceptions that may occur during JVM operation .

Feature: Java compiler will not check it. In other words, when such an exception may occur in the program, if it is neither "thrown through the throws statement" or "not caught by the try-catch statement", it will still be compiled . Such as NullPointerException null pointer exception , ArrayIndexOutBoundException array subscript out of bounds exception , ClassCastException type conversion exception , ArithmeticExecption arithmetic exception .

RuntimeException will be automatically thrown and automatically caught by the Java virtual machine (even if we don’t write an exception catching statement, an error will be thrown at runtime!!). The most common occurrence of such an exception is that there is a problem with the code itself, which should be logically resolved. Solve and improve the code .

Compile-time exception: Definition: Exception except RuntimeException and its subclasses.

Features: Java compiler will check it . If there are such exceptions in the program, such as ClassNotFoundException (the specified class exception is not found), IOException (IO stream exception), either declare it through throws and throw it, or catch it through try-catch, otherwise it cannot be compiled.

  1. Unchecked exceptions Unchecked exceptions and
    Java all exceptions can be divided into subjects abnormal (checked exception) and Unchecked exceptions (unchecked exception).

Checked exceptions The
compiler requires exceptions that must be handled . During the operation of the correct program, there are often abnormal situations that are prone to appear and meet expectations. Once such an exception occurs, it must be handled in some way. **Except for RuntimeException and its subclasses, other Exception exceptions are all checked exceptions. **The compiler will check for such exceptions, which means that when the compiler checks that there may be such exceptions somewhere in the application, it will prompt you to handle this exception-either use try-catch to catch or use method signatures Use the throws keyword to throw, otherwise the compilation will not pass.


Unchecked exceptions The compiler does not check and does not require exceptions that must be handled. That is to say, when such an exception occurs in the program, even if we don’t catch it with try-catch, we don’t use throws to throw the exception, and the compiler does not It will pass normally. Such exceptions include runtime exceptions (RuntimeException and its subclasses) and errors (Error).

13 Injection operation of spring object

1@Autowired ; 1 is automatically assembled by type; 2 is used directly on the attribute, and the automatic injection prerequisite is that the Bean object exists in the IOC container
2@Qualifier ; @Autowired is automatically assembled according to the type, plus **@Qualifier can be According to the method of byName ** automatic assembly; @Qualifier cannot be used alone

14spring interceptor

In recent projects, I plan to use Spring Security for permission control, but most of the previous projects were implemented with spring interceptors . In Spring MVC projects, Spring interceptors are used for permission control . Generally, there are two types of interceptors: one login interceptor and multiple permission verification interceptors .
Login interceptor : all requests, verify whether the user is logged in, and whether the user name and password are correct . Permission verification interceptor.
Multiple permission verification interceptors : different link rules use different interceptors to intercept and perform permission verification .

There are two ways to implement Spring's interceptor: the
first way: a custom Interceptor class should implement Spring's HandlerInterceptor interface, and the
second way is to implement Spring's WebRequestInterceptor interface.

The difference between Spring Interceptor and Filter:

1. The interceptor is based on the reflection mechanism of java , and the filter is based on the function callback .

2. The interceptor does not depend on the servlet container in the spring container, and the filter depends on the servlet container .

3. The filter only works before and after the servlet . The interceptor can go deep before and after the method, before and after the exception is thrown , so the use of the interceptor has greater flexibility. Therefore, in the Spring framework of the program, the interceptor should be used first. .

4. In the life cycle of the action, the interceptor can be called multiple times, while the filter can only be called once when the container is initialized .

5. The interceptor can obtain each bean in the IOC container, but the filter cannot . That is to say, injecting a service into the interceptor can call business logic more flexibly.

15SQL injection

The key to solving the SQL injection problem is to strictly check all data that may come from user input and use the principle of least privilege for database configuration.
1. All query statements use the parameterized query interface provided by the database, and parameterized statements use parameters instead of embedding user input variables into SQL statements . Almost all current database systems provide a parameterized SQL statement execution interface. Using this interface can effectively prevent SQL injection attacks .
2. The special characters ('"\angle brackets &*; etc.) entering the database are escaped or converted .
3. Variable types are strictly restricted . For example, integer variables are filtered by the intval() function. The storage field must correspond to the int type .
4. The data length should be strictly regulated to prevent the longer SQL injection statement from being executed correctly.
5. The coding of each data layer of the website is unified, and it is recommended to use UTF-8 coding. The inconsistency of upper and lower coding may cause some filtering models to be bypassed.
6. Strictly restrict the operation authority of the website user's database , and provide this user with only the authority that can satisfy his work, thereby minimizing the harm of the injection attack to the database .
7, to avoid the site shows SQL error message , such as the type of error, fields do not match and so on, to prevent an attacker using these error messages to make some judgment.
8,Before the website is released, it is recommended to use some professional SQL injection detection tools to detect and patch these SQL injection vulnerabilities in time .

The underlying understanding of 16HashMap

Implementation principle: HashMap adopts the chain address method. That is, the bottom layer is an array implementation, and each item of the array (that is, an Entry) is a linked list.

HashMap storage mechanism: first calculate the position of the entry corresponding to the key in the array according to the key , and then determine whether the entry is in the linked list corresponding to the position, if not, insert the head of the linked list, if it is, update the The value of the corresponding Entry in the linked list.

HashMap calculates the position of the array to which the key belongs : first calculate the hash value of the key , and then calculate the position of the array according to the hash function hashcode & (length-1) (because the array length of the HashMap is an integer power of 2, it uses bitwise arithmetic The result is the same as hash% length, but the efficiency of bit operation is much higher than that of remainder operation)

Expansion of HashMap: Whenever a HashMap is initialized, the default array size (table.size) is 16 (there is no 16 in the initialization stage, but resize=16 when adding elements), the default growth factor (loadFactor) is 0.75, ; When the number of elements exceeds the loadFactor of the array size, the array will be expanded . The expansion method adopted by HashMap is: double the size of the array each time, and then recalculate the position of each element in the HashMap in the array . You can also customize the size of the expanded capacity (HashMap(int initialCapacity)).

17 What is the difference between ArrayList && LinkedList?

Insert picture description here

Guess you like

Origin blog.csdn.net/zs18753479279/article/details/115215403