On the self-cultivation of programmers: concurrency, database, Spring interview development three-piece suit

Concurrent programming, database and Spring, I think this is a three-piece set of programmer development interviews. Spring provides development. The database is used to maintain and obtain data. Concurrency is to improve the performance of the program. It is very important and inseparable. Take a look every day, development is not difficult.
Insert picture description here

One, concurrent programming

In addition, I have compiled a collection of interview questions for 20 years, including spring, concurrency, database, Redis, distributed, dubbo, JVM, microservices, etc. The following figure is a partial screenshot, if you need it , click here , the password CSDN.

Insert picture description here
1. There are several ways to implement multithreading in Java

(1) Inherit the Thread class;

(2) Implement the Runnable interface;

(3) Implement Callable interface to create Thread thread through FutureTask wrapper;

(4) Use ExecutorService, Callable, and Future to implement multithreading with returned results (that is, use ExecutorService to manage the previous three methods).

2. How to stop a running thread

(1) Use the exit flag to make the thread exit normally, that is, the thread terminates when the run method is completed.

(2) Use the stop method to forcibly terminate, but this method is not recommended, because stop and suspend and resume are both expired and invalid methods.

(3) Use the interrupt method to interrupt the thread.

class MyThread extends Thread {
    
    
    volatile Boolean stop = false;
    public void run() {
    
    
        while (!stop) {
    
    
            System.out.println(getName() + " is running");
            try {
    
    
                sleep(1000);
            }
            catch (InterruptedException e) {
    
    
                System.out.println("week up from blcok...");
                stop = true;
                // 在异常处理代码中修改共享变量的状态
            }
        }
        System.out.println(getName() + " is exiting...");
    }
}
class InterruptThreadDemo3 {
    
    
    public static void main(String[] args) throws InterruptedException {
    
    
        MyThread m1 = new MyThread();
        System.out.println("Starting thread...");
        m1.start();
        Thread.sleep(3000);
        m1.interrupt();
        // 阻塞时退出阻塞状态
        Thread.sleep(3000);
        // 主线程休眠 3 秒以便观察线程 m1 的中断情况
        System.out.println("Stopping application...");
    }
}

3. What is the difference between notify() and notifyAll()?

Notify may cause deadlock, but notifyAll will not

At any time, only one thread can acquire a lock, that is to say, only one thread can run the code in synchronized. Use notifyall to wake up all threads in the wait state and re-enter the lock contention queue, while notify can only wake up one.

wait() should be used in conjunction with the while loop. If should not be used, the condition must be checked before and after the wait() call. If it is not met, you must call notify() to wake up another thread for processing, and continue to wait() until the condition is met. Execute down.

Notify() is an optimization of notifyAll(), but it has very precise application scenarios and requires correct use. Otherwise it may lead to deadlock. The correct scenario should be that the waiting in WaitSet is the same condition, and any one of them can be awakened to correctly handle the following matters. If the awakened thread cannot be handled correctly, be sure to continue to notify() the next thread, and you need to return to it. WaitSet.

4. What is the difference between sleep() and wait()?

For the sleep() method, we must first know that the method belongs to the Thread class. The wait() method belongs to the Object class
.

The sleep() method causes the program to suspend execution for a specified time, giving up the other thread of the cpu, but its monitoring state is still maintained, and it will automatically resume its running state when the specified time is up. In the process of calling the sleep() method, the thread will not release the object lock.

When the wait() method is called, the thread will give up the object lock and enter the waiting lock pool waiting for this object. Only after the notify() method is called for this object, the thread enters the object lock pool preparation and acquires the object lock and enters the running state.

5. What is volatile? Can order be guaranteed?

Once a shared variable (class member variable, class static member variable) is modified by volatile, then it has two layers of semantics:

(1) Ensure the visibility of different threads operating on this variable, that is, a thread modifies the value of a variable, and the new value is immediately visible to other threads. The volatile keyword will force the modified value Write to main memory immediately.

(2) Reordering instructions is prohibited.

Volatile is not an atomic operation

What is guaranteeing partial orderliness?

When the program executes the read operation or write operation of the volatile variable, all the changes in the previous operation must have been carried out, and the result has been visible to the subsequent operation; the subsequent operation must have not been carried out;

x = 2;//语句 1
y = 0;//语句 2
flag = true;//语句 3
x = 4;//语句 4
y = -1;//语句 5

Since the flag variable is a volatile variable, in the process of instruction reordering, statement 3 will not be placed before statement 1 and statement 2, nor will statement 3 be placed after statement 4 and statement 5. But note that the order of statement 1 and statement 2, and the order of statement 4 and statement 5 are not guaranteed.

Using Volatile is generally used for the double check lock of the state tag amount and singleton mode

6. What is the difference between the start() and run() methods in the Thread class?

The start() method is used to start the newly created thread, and the run() method is called internally in start(), which is not the same as calling the run() method directly. When you call the run() method, it will only be called in the original thread. If no new thread is started, the start() method will start the new thread.

7. Why wait, notify and notifyAll are not in the thread class?

The obvious reason is that the locks provided by JAVA are object-level rather than thread-level, and each object has a lock, which is obtained through a thread. If the thread needs to wait for some locks, it makes sense to call the wait() method in the object. If the wait() method is defined in the Thread class, it is not obvious which lock the thread is waiting for. Simply put, since wait, notify and notifyAll are lock-level operations, they are defined in the Object class because the lock belongs to the object.

8. Why should the wait and notify methods be called in a synchronized block?

(1) Only when the calling thread owns the exclusive lock of an object, can the wait(), notify() and notifyAll() methods of the object be called.

(2) If you don't do this, your code will throw an IllegalMonitorStateException.

(3) Another reason is to avoid race conditions between wait and notify.

The wait() method forces the current thread to release the object lock. This means that before calling the wait() method of an object, the current thread must have acquired the object's lock. Therefore, the thread must be in the synchronization method or synchronization code block of an object to call the wait() method of the object.

Before calling the notify() and notifyAll() methods of the object, the calling thread must have obtained the lock of the object. Therefore, the notify() or notifyAll() method of the object must be called in the synchronization method or synchronization code block of an object.

The reason for calling the wait() method is usually that the calling thread wants to continue execution after a special state (or variable) is set. The reason for calling notify() or notifyAll() is usually that the calling thread wants to tell other waiting threads: "The special state has been set." This state serves as a communication channel between threads, and it must be a mutable shared state (or variable).

9. What is the difference between interrupted and isInterruptedd methods in Java?

The main difference between interrupted() and isInterrupted() is that the former will clear the interrupted state while the latter will not. The interrupt mechanism of Java multi-threading is implemented with internal flags. Calling Thread.interrupt() to interrupt a thread will set the interrupt flag to true. When the interrupted thread calls the static method Thread.interrupted() to check the interrupt status, the interrupt status will be cleared. The non-static method isInterrupted() is used to query the interrupt status of other threads without changing the interrupt status flag. Simply put, any method that throws InterruptedException will clear the interrupt status. In any case, the interrupt status of a thread may be changed by other threads calling interrupts.

10. What is the difference between synchronized and ReentrantLock in Java?
Similarity:

There are many similarities between these two synchronization methods. They are both locked synchronization and blocking synchronization. That is to say, when a thread obtains an object lock and enters the synchronization block, other access to the synchronization block Threads must be blocked waiting outside the synchronized block, and the cost of thread blocking and wake-up is relatively high.

the difference:

The biggest difference between these two methods is that for Synchronized, it is a keyword of the Java language, which is a mutual exclusion at the native syntax level, and requires jvm implementation. ReentrantLock is an API-level mutex lock provided after JDK 1.5, which requires lock() and unlock() methods to cooperate with try/finally statement blocks.

After Synchronized is compiled, two bytecode instructions, monitorrenter and monitorexit, are formed before and after the synchronization block. When executing the monitorenter instruction, first try to acquire the object lock. If the object is not locked, or the current thread already owns the lock of the object, the lock counter is increased by 1, correspondingly, the lock counter is decreased by 1 when the monitorexit instruction is executed. When the counter is 0, the lock Was released. If acquiring the object lock fails, the current thread will block until the object lock is released by another thread.

Since ReentrantLock is a set of mutual exclusion locks provided under the java.util.concurrent package, compared to Synchronized, the ReentrantLock class provides some advanced functions, mainly the following 3 items:

(1) Waiting can be interrupted. When the thread holding the lock is not released for a long time, the waiting thread can choose to give up waiting, which is equivalent to Synchronized, which can avoid deadlock.

(2) Fair locks, when multiple threads are waiting for the same lock, they must acquire the locks in the order of the time they apply for the locks. Synchronized locks are not fair locks. The default constructor of ReentrantLock is an unfair lock created, which can be set to fair through the parameter true Lock, but fair lock performance is not very good.

(3) The lock binds multiple conditions, and a ReentrantLock object can bind to two objects at the same time.

Two, MySQL

Insert picture description here

1. What kinds of locks are there in Mysql?

(1) Table-level lock: low overhead and fast locking. There is no deadlock, the locking granularity is large, the probability of lock conflicts is high, and the concurrency is low.

(2) Row-level locks: expensive and slow to lock. There will be deadlocks, the lock granularity is small, the probability of lock conflicts is low, and the concurrency is high.

(3) Page locks: Overhead time, lock time, and lock granularity between table-level locks and row-level locks, deadlocks will occur, with moderate concurrency.

2. The difference between CHAR and VARCHAR?

(1) The length of CHAR is immutable, ranging from 1 to 255. If the storage length does not reach the defined length, it will be filled with spaces. The access speed is fast, but it is easy to waste space.

(2) The length of VARCHAR is variable, ranging from 1 to 65535. If the storage length does not reach the defined length, the actual length data is stored. The access speed is slightly slower, but it saves space.

3. Can you tell me the difference between myisam and innodb?

The myisam engine is the default engine before version 5.1. It supports full-text retrieval, compression, spatial functions, etc., but does not support transactions and row-level locks, so it is generally used in scenarios where there are a large number of queries and a small amount of insertion, and myisam does not support foreign keys. And the index and data are stored separately.

Innodb is based on a clustered index. Contrary to myisam, it supports transactions, foreign keys, and supports high concurrency through MVCC. Indexes and data are stored together.

4. Can you talk about the basic characteristics and isolation levels of transactions?
Transaction: In the database, a series of operations on data can be regarded as a whole, called transaction. This whole is either all executed or not executed at all.
The existence of ACID attributes ensures the reliability of transactions.
(1) Actomicity (atomicity): Atomicity requires that all operations in the transaction are either completed or rolled back to a previously unoperated state. That is, after a certain operation in the transaction fails, it will be equivalent to nothing happened, and there will be no change in part of the data.

(2) Consistency (Consistency): Consistency requires that the state of the database be consistent before and after the transaction is executed, that is, switch from one consistent state to another consistent state.

(3) Isolation: Isolation requires that concurrent transactions be isolated and invisible. That is, one transaction can't see the operation and data of another transaction.

(4) Durability (persistence): Durability requires that the modification of the database data by the transaction be permanent. That is, once the data is modified and submitted, its status will be permanently unchanged.

5. Concurrency issues-dirty reads, non-repeatable reads, phantom reads?

For multiple transactions running at the same time, if these transactions access the same data, the necessary isolation mechanism is not adopted, which will cause the following concurrency problems.
(1) Dirty read: Dirty read refers to when a transaction is accessing certain data, and the data is modified, and this data has not been submitted to the database, if another transaction also accesses this data , What is obtained is this modified data, and the data obtained at this time is incorrect, that is, dirty read.
For example: the age of tom is 22, and transaction A modifies the age of tom to 30. At this time, it has not been submitted to the database. At this time, transaction B gets the age of tom and gets 30. Transaction A rolls back the data. The data in the database is still 22, but The data obtained by transaction B is 30, which is a dirty read, and the data is read incorrectly.

(2) Non-repeatable read: Refers to a transaction that reads the same data multiple times. Before this transaction is over, another transaction also accesses the data and modifies it, which may cause inconsistent data read by the transaction multiple times , Which is not repeatable.
For example: Tom's age is 22, transaction A reads tom's age as 22, and the transaction is not over. At this time, transaction B modifies tom's age to 30 and submits it to the database. When transaction A reads tom's age as 30 again, the data read twice by transaction A is inconsistent, that is, it cannot be read repeatedly.

(3) Phantom reading: Refers to the phenomenon when the transaction is not executed independently. A transaction modifies a table, involving all rows of the table, while another transaction also modifies the table, such as adding or deleting a piece of data. At this time, the first transaction found that there was an extra or missing piece of data. This situation is phantom reading.
For example: Transaction A queries the current table with a total of 11 data, at this time transaction B inserts a piece of data into the table, and transaction A queries the current table with a total of 12 data again, which is a phantom read.

Note:
    Non-repeatable reading and phantom reading are somewhat similar in comprehension.
    Non-repeatable reading is an operation on a piece of data, and the key is to modify a piece of data.
    The phantom read is to operate on the table, the key is to add or delete a certain piece of data.

6. What is the isolation level of the transaction?

The database system must have the ability to isolate concurrently running transactions so that each transaction will not affect each other and avoid concurrency problems.
  Isolation level: refers to the degree of isolation between a transaction and other transactions. The higher the isolation level, the weaker the concurrency.
(1) Read Uncommitted: Read uncommitted content.
  Generally not used. Under this isolation level, the query will not be locked, that is, there may be two transactions operating on the same table. May cause "dirty read", "non-repeatable read", "phantom read".

(2) Read Committed: Only the submitted content can be read.
  Commonly used (oracle, SQL Server default isolation level). Under this isolation level, the query adopts a snapshot read mechanism, that is, uncommitted data will not be read, thus avoiding "dirty reads", but it may still lead to "non-repeatable reads" and "phantom reads".

(3) Repeatable Read (repeatable read)
  commonly used (mysql default isolation level). Under this isolation level, the query uses a snapshot read mechanism, and after the transaction is started, the current data cannot be modified, which can avoid "non-repeatable read", but it may still cause "phantom read" (adding or deleting a certain piece of data).

(4) Serializable (serialization) is
  generally not used. Under this isolation level, transactions will be executed serially (queuing execution), resulting in poor execution efficiency and high overhead. Can avoid "dirty read", "non-repeatable read", "phantom read".

【举例:】
select @@transaction_isolation; -- 用于查看当前数据库的隔离级别(8.0版本)
 set session transaction isolation level read committed; --用于设置隔离级别为 read committed


7. Talk about auto-incrementing primary key and UUID?

(1) Self-incrementing primary key, data is stored sequentially in physical structure, with good performance and small space occupation. Can be of type int and bigint. int 4 bytes, bigint 8 bytes, the theory should not appear in the project that the auto-increment primary key reaches the maximum value, because the data is too large, the efficiency will be greatly reduced, when a certain amount of data appears, the database and table operation should be performed .

(2) UUID, the data is stored randomly in the physical structure, with poor performance and large space occupation. Unique ID, never conflict.

Three, Spring

Insert picture description here

1. What is the Spring IOC container?

The core of the Spring framework is the Spring container. The container creates objects, assembles them, configures them, and manages their complete life cycle. The Spring container uses dependency injection to manage the components that make up the application. The container receives instructions for instantiation, configuration, and assembly of objects by reading the provided configuration metadata. The metadata can be provided through XML, Java annotations or Java code.
Insert picture description here
2. What is dependency injection?

In dependency injection, you don't have to create objects, but you must describe how to create them. You are not directly connecting components and services in the code, but describing which components in the configuration file require which services. They are assembled by the IoC container.

3. How many ways can dependency injection be accomplished?

Generally, dependency injection can be done in three ways, namely:

Constructor injection
setter injection
Interface injection
In the Spring Framework, only constructor and setter injection are used.

4. Distinguish between constructor injection and setter injection.
Insert picture description here
5. How many kinds of IOC containers are there in spring?

BeanFactory-BeanFactory is like a factory class that contains a collection of beans. It will instantiate the bean when requested by the client.

ApplicationContext-The ApplicationContext interface extends the BeanFactory interface. It provides some additional functions on the basis of BeanFactory.

6. Distinguish BeanFactory and ApplicationContext.
Insert picture description here

8. What is a spring bean?

They are the objects that form the backbone of the user's application.
Beans are managed by the Spring IoC container.
They are instantiated, configured, assembled and managed by the Spring IoC container.
Bean is created based on the configuration metadata provided by the user to the container.
9. What configuration methods does spring provide?

Based on xml configuration

The dependencies and services required by the bean are specified in the configuration file in XML format. These configuration files usually contain many bean definitions and application-specific configuration options. They usually start with the bean tag. E.g:

<bean id="studentbean" class="org.edureka.firstSpring.StudentBean">
        <property name="name" value="Edureka"></property>
    </bean>

Configuration based on annotations

Instead of using XML to describe bean assembly, you can configure the bean as the component class itself by using annotations on related class, method, or field declarations. By default, annotation assembly is not turned on in the Spring container. Therefore, you need to enable it in the Spring configuration file before using it. E.g:

<beans>
        <context:annotation-config/>
        <!-- bean definitions go here -->
    </beans>

Configuration based on Java API

Spring's Java configuration is achieved by using @Bean and @Configuration.

2.1. The @Bean annotation plays the same role as the element.

2.2. The @Configuration class allows to define inter-bean dependencies by simply calling other @Bean methods in the same class.

E.g:

public class StudentConfig {
    
    
    @Bean
    public StudentBean myStudent() {
    
    
        return new StudentBean();
    }
}

10. What is AOP?

AOP (Aspect-Oriented Programming), that is, aspect-oriented programming, it complements OOP (Object-Oriented Programming, object-oriented programming) and provides a perspective of abstract software structure different from OOP. In OOP, we use classes As our basic unit, the basic unit in AOP is Aspect (section)

11. What are the Aspect, Advice, Pointcut, JointPoint and Advice parameters in AOP?
Insert picture description here

  • Aspect-Aspect is a class that implements cross-cutting issues, such as transaction management. The aspect can be a common class configured and then configured in the Spring Bean configuration file, or we can use Spring AspectJ to support the @Aspect annotation to declare the class as an Aspect.
  • Advice-Advice is the action taken for a specific JoinPoint. In terms of programming, they are methods that are executed when a specific JoinPoint with a matching pointcut is reached in the application. You can think of Advice as a Spring Interceptor or a Servlet filter.
  • Advice Arguments-We can pass parameters in the advice method. We can use the args() expression in the pointcut to apply to any method that matches the parameter pattern. If we use it, then we need to use the same name in the advice method that determines the parameter type.
  • Pointcut-Pointcut is a regular expression that matches JoinPoint and is used to determine whether advice needs to be executed. Pointcut uses different types of expressions that match JoinPoint. The Spring framework uses the AspectJ Pointcut expression language to determine the JoinPoint that will apply the notification method.
  • JoinPoint-JoinPoint is a specific point in the application, such as method execution, exception handling, changing object variable values, etc. In Spring AOP, JoinPoint is always the executor of the method.

12. What are the ways to implement AOP?

The technologies for implementing AOP are mainly divided into two categories:

Static proxy-refers to using the commands provided by the AOP framework to compile, so that AOP proxy classes can be generated at the compilation stage, so it is also called compile-time enhancement; compile-time weaving (special compiler implementation) class-loading weaving (special class-loading) Implement).
Dynamic proxy-AOP dynamic proxy class is "temporarily" generated in memory at runtime, so it is also called runtime enhancement. JDK dynamic proxy CGLIB
13. What is the difference between Spring AOP and AspectJ AOP?

Spring AOP is implemented based on dynamic proxy mode; AspectJ is implemented based on static proxy mode. Spring AOP only supports PointCut at the method level; it provides full AOP support, and it also supports PointCut at the attribute level.

5. Finally:

In view of the fact that many people have been interviewing recently, I have also compiled a lot of interview topic materials here, as well as experience from other major companies. Hope it helps everyone.

The answers to the interview questions below are organized into document notes. I also sorted out some interview materials & the latest interview questions collected by some big companies in 2020 (all organized into documents, a small part of the screenshots), if necessary, you can click to enter the secret CSDN

Insert picture description here

Insert picture description here

Guess you like

Origin blog.csdn.net/banzhuanhu/article/details/109278699