10 basic java questions (third bullet)

21. About pessimistic lock and optimistic lock

Pessimistic Locking Ideas
There are many ideas for solving thread safety, which can be discussed from the direction of "pessimistic locking".
Pessimistic lock, that is, when the data is modified, the locked state is used to exclude externally requested modifications. You must wait when you encounter a locked state.

Although the above solution does solve the problem of thread safety, don't forget that our scenario is "high concurrency". In other words, there will be many such modification requests, and each request needs to wait for a "lock". Some threads may never have the opportunity to grab this "lock", and such requests will die there. At the same time, there will be many such requests, which instantly increases the average response time of the system. As a result, the number of available connections is exhausted and the system falls into an exception.
Optimistic Locking Thinking At
this time, we can discuss the idea of ​​"optimistic locking". Optimistic locking is a more relaxed locking mechanism than "pessimistic locking". Most of them are updated with a version number (Version). I used it in hibernate. The realization is that all requests for this data are eligible to be modified, but a version number of the data will be obtained, and only the version number that matches can be updated successfully, and the other returns fail to snap up. In this case, we do not need to consider the problem of queues, but it will increase the computational overhead of the CPU. However, on the whole, this is a better solution.

There are many software and services that support the "optimistic lock" function. For example, watch in Redis is one of them. Through this realization, we ensure data security.

22. Briefly talk about how the sql statement is optimized

We generally need to pay attention to SQL specifications when developing. For example, the most basic thing is not to use * to query all fields, but also to often use table aliases, and often commit transactions to release the rollback point in time. If you use functions, try to use internal The function, and another optimization is that after the project is online, after a large amount of data is generated, the tester finds that some function points are slow to respond, and feedback to our developers, our developers find the SQL statement corresponding to this function point. If this SQL statement is more complicated to write, we have to use explain to analyze the execution plan of the SQL statement to see if the index is invalid, or the execution of a certain subquery is slow, and then we optimize these A SQL, what is the optimization method? For example, adding indexes, or creating views.

23. What is a deadlock

For example, suppose there are two processes P1 and P2, both of which require A and B resources. Now P1 holds A and waits for B resources, while P2 holds B and waits for A resources. Both of them wait for another resource and refuse to agree. Release resources and wait indefinitely like this, which forms a deadlock, which is also a kind of deadlock. Define a deadlock. If each process in a group of processes is waiting for an event that can only be triggered by other processes in the group, then the group of processes is deadlocked. Competing for non-preemptable resources causes deadlock, which is the first case we are talking about, and this is waiting for non-preemptible resources occupied by the other party.

24. MyBatis execution process

Our projects are all used in combination with Spring. We all give MyBatis's sqlSessionFactory to Spring for management. When the server is started, Spring will listen and load all the files in the configuration file. Spring will create it through reflection. Mapper implementation class, we call Service to call the dao layer.
When we use springboot, we have used it in combination with MyBatista. When we used it, he integrated the mapper under the tk. package provided by the mybatis official website to realize all the additions, deletions, and modifications of the single table.

25. Explain what an index is? Explain single-column index and joint index? When does the index fail? How to add an index?

A single-column index refers to creating an index on a certain column of a table, and a joint index is a joint creation of indexes on multiple columns. Single-column indexes can appear anywhere in the where condition, and joint indexes need to be written in a certain order. In the multi-condition query, the efficiency of the joint index is higher, and our joint index also creates up to two columns.
When we create indexes, we must also consider the update frequency of our table. If there are more indexes in the table, it will affect the update speed. Why does it affect the update speed? Because the process of creating an index is actually to build a binary tree, and every time the data is updated, the binary tree must be recalculated, which affects the update speed. I probably know so much about the indexes in our table.
The index is not always take effect, such as the following situations can lead to failure of the index effect:
1. If you have or conditions, even if conditionally indexed will not use (which is why the cause or minimize the use of)
attention : If you want to use or and want the index to take effect, you can only add an index to each column in the or condition. 2. A
like query starts with %, which will cause the index to fail
3. If the column type is a string, then it must Use quotation marks to quote the data in the condition, otherwise the index will fail
4. If mysql estimates that the full table scan is faster than the index, then the index is not used.
In addition, check the usage of the index
The index can actually be understood as a data query directory. The purpose of building an index is to improve the query speed of the table; when there is no index, the entire table is searched during the query. With the index, you can quickly find the required data according to the index; but the index cannot Random construction, because the index needs to be maintained, will reduce the efficiency of addition, deletion, and modification. It will complicate the maintenance of data, affect the efficiency of development, and index will also occupy the physical space of the database; therefore, we generally rarely create indexes during the development phase, testing phase, and trial operation phase of the project, because with indexes, System bugs make junk data particularly difficult to delete. Only increase the index after the project is officially launched to increase the speed of the project. Indexes are generally created on fields that are often used as query conditions, sorted fields, and fields that are associated relationships. Try to avoid large text fields, fields with a small amount of data (such as gender), and fields whose addition, deletion and modification performance is greater than retrieval performance; in addition, in some cases, even if an index is added, the index will not take effect, such as: index field is used Is not equal to (!= or <>) is consistent, a function is used, an operation is used, is null or is not null is used,
and the data type that does not match is compared, and% is used on both sides of the like query; there is another The point to note is that if a joint index is established on multiple fields, the index will only work when the first column of the composite index is referenced by the where clause. Because we want to use indexes to increase query efficiency, we must sacrifice the efficiency of addition, deletion and modification. To solve this problem, we often do master-slave replication of the database, and separate read and write. Create two databases at the same time, one master and one slave. The data of the two databases are completely consistent. The master database is used for writing operations. After the operation, the database will automatically synchronize the data to the slave database, and the slave database is used to perform read operations. . In this way, when we create an index, we can create it only in the read database. In this way, the index can increase query efficiency without affecting the efficiency of addition, deletion, and modification. After doing this, we can further optimize it, such as the optimization of the database engine. The main database uses the transactional engine Innodb because it performs addition, deletion and modification operations.
You can use the more efficient MyIASM engine to read the database without transaction. At the same time, according to the actual situation, you can also configure one master and multiple slaves or multiple masters and multiple slaves. There are two commonly used methods for index creation: CREATE [UNIQUE] INDEX index_name ON table_name (column_list); or ALTER TABLE table_name ADD INDEX index_name (id,name); for modification: ALTER TABLE table_name REBUILD INDEX index_name (column_list); for deletion :DROP INDEX index_name ON talbe_name
or: ALTER TABLE table_name DROP INDEX index_name to
view: select * from all_indexes where table_name='student';
Multiple fields in Conlum_list are separated by ",".

26. Talk about what transaction? How are transactions controlled in the code?

During development, we operate on two or more SQL statements at the same time. If one operation fails during the operation, the entire transaction is rolled back, and the submission is completed only when all of them are correct. For example, bank transfer, from account A to account B To transfer money, two SQL statements must be executed successfully at the same time. We directly configure it in Spring in the project and use it. The annotated transaction is used. The red font is used to understand
the transaction in Java. There are two main types, JDBC transaction (local Things) and JTA (Java Transaction API) transactions (distributed things); transactions have four characteristics: ACID atomicity, consistency, isolation, and durability. In the framework, we generally leave things to spring to manage. There are generally two ways to configure transactions in spring, one is declarative transaction and the other is annotation transaction. Annotation transactions are relatively simple and flexible. Configure a tx:annotation-driven annotation in the spring configuration file, and then add the @Transactional annotation to the required method. In declarative transactions, the point of cut is generally to scan the service layer implementation class, configure the propagation characteristics through method name matching, and determine which methods add transactions and which do not require things. Transactions mainly have five isolation levels and 7 propagation characteristics; the five isolation levels from low to high: mainly control whether dirty reads, non-repeatable reads, and illusion reads occur; the 7 propagation characteristics mainly determine whether to create a new transaction or take the current transaction;
we During development, if you don’t pay attention to the transaction, it will appear, dirty read, non-repeatable read, and phantom read. For example, let's talk about the following concepts one by one.Dirty
read:
refers to when a transaction is accessing data, and the data Modifications have been made, and this modification has not yet been committed to the database. At this time, another transaction also accesses the data and then uses the data. Because this data is data that has not yet been committed, the data read by another transaction is dirty data, and the operation based on the dirty data may be incorrect.
 Non-repeatable reading:
Refers to reading the same data multiple times within a transaction. Before this transaction is over, another transaction also accesses the same data. Then, between the two read data in the first transaction, due to the modification of the second transaction, the data read twice in the first transaction may be different. This happens that the data read twice in a transaction is different, so it is called non-repeatable read.
Phantom reading:
refers to a phenomenon that occurs when the transaction is not executed independently, for example, the first transaction modifies the data in a table, and this modification involves all data rows in the table. At the same time, the second transaction also modifies the data in this table. This modification is to insert a new row of data into the table. Then, the user who operates the first transaction will happen later

27. Deadlock must meet 4 conditions

1. Mutually exclusive conditions: In fact, the process uses the allocated resources exclusively, which means that a certain resource can only be occupied by one process within a period of time. If there are other processes requesting resources at this time, other threads can only wait until the process that holds the resources is used up and released. 2. Request and retention conditions: Refers to the process that has retained at least one resource, but has made a new resource request, and the resource has been occupied by other processes, at this time the requesting process is blocked, but it does not retain other resources it has acquired put. Non-deprivation condition: Refers to the resource that the process has acquired. It cannot be deprived before it is used up, and can only be released by itself when it is used up. Loop waiting condition: When a deadlock occurs, there must be a circular chain of processes equivalent to resources, that is, a collection of processes like {P0, P1, P2,..., Pn} P0 is waiting for a P1 to occupy Resource; P1 is waiting for the resource occupied by P2,..., Pn is waiting for the resource occupied by P0

28.Mysql optimization plan?

We generally start from the following points:

  1. Use a version that supports mysql master-slave replication
  2. Use indexes when using MySQL
  3. Optimize sql statement
  4. Optimize MySQL service, modify the MY.INI file, configure the cache size according to the server
  5. Cache based on server configuration index
  6. Use views to put redundant fields in a table
  7. Use the third-party technology mycat to split the database, horizontal split and vertical split, we use horizontal split
  8. Set the upper limit of the data stored in the table, and configure the read-write separation through mycat

29.Learn more about mysql internal functions

concat,trim,replace,substring,curdate() #return the current date, curtime() #return the current time, now() #return the current date+time if(value,true,false) #If the value is true, then return true, otherwise, return false
selectif (salary> 3000,'Hight','Low') from salary;
selectid, salary, if (salary <=> NULL,'NULL','NOT NULL') from salary;
2, ifnull (value1, value2)# If value1 is not empty, return value1, otherwise return value2
# can be used for null replacement
selectifnull(salary, 0.00) from salary; etc...

30. How does multithreading solve high concurrency?

The synchronized keyword mainly solves the problem of multi-threaded shared data synchronization.
ThreadLocal uses occasions to solve the problem of data inconsistency caused by concurrency in multiple threads.
Both ThreadLocal and Synchronized are used to solve multi-threaded concurrent access, but ThreadLocal and synchronized have an essential difference:
synchronized is the use of a lock mechanism, so that variables or code blocks can only be accessed by one thread at a time. And ThreadLocal provides a copy of the variable for each thread, so that each thread does not access the same object at a certain time, thus isolating the data sharing of multiple threads. Synchronized is just the opposite, it is used to obtain data sharing when communicating between multiple threads.

Guess you like

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