3W+ word length depth summary Java programmer interview questions collection of Essentials (with mind map).

Time:2020-10-21

1. How to jump out of the current multiple nested loops in Java?
In Java, if you want to jump out of multiple loops, you can define a label before the outer loop statement, and then use the break statement with a label in the code of the inner loop body to jump out of the outer loop. For example,

ok: for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
System.out.println("i=" + i + ",j=" + j);
if (j == 5)
break ok;  
}
}

In addition, I usually don’t use the labeling method, but let the result of the outer loop conditional expression be controlled by the inner loop body code, for example, to find a number in a two-dimensional array.

int arr[][] = { { 1, 2, 3 }, { 4, 5, 6, 7 }, { 9 } };
boolean found = false;
for (int i = 0; i < arr.length && !found; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.println("i=" + i + ",j=" + j);
if (arr[i][j] == 5) 
{
found = true;
break;
}
}
}

2. Please tell me the difference between the scope of public, private, protected, and not writing.

  • Private decorated member variables and functions can only be accessed in the class itself and inner classes.
  • Protected decorated member variables and functions can be accessed by the class itself, subclasses and classes in the same package.
  • Public decorated member variables and functions can be accessed by classes, subclasses, classes in the same package, and any other class.

By default (no writing), it belongs to a kind of package access, that is, it can be accessed by the class itself and by the classes in the same package.
The following table can clearly illustrate the role of scope operators in Java:
3W+ word length depth summary Java programmer interview questions collection of Essentials (with mind map).

3. How do you use session in JavaEE?
In the servlet API, session represents a session between the browser and the web server. In the web server, different browsers are distinguished by the session. Because the web server uses the HTTP protocol for communication, the web server does not know who the browser is requesting, and it will not record the browser’s access information. Therefore, the session is required to record who the requested browser is and how to maintain communication between the session and the browser? After the browser sends a request to a web site for the first time, the web server searches for resources according to the request path and generates a session. The web server returns the resources found to the browser as a response, and a cookie with a special name is attached to the response, which is the session ID. After that, when the browser sends a request again, it will bring this cookie information in the request information. The function of this cookie is to tell the web server that my browser has visited you, and you do not need to generate a session.

There are many applications of session

  • 1. Filter users who are not logged in
    It can be used to store user information. When a user logs in, the user information will be put into the session. If there is no login, there will be no user information in the session. In this way, users who are not logged in can be prevented from viewing some information.
  • 2. Prevent the form from being submitted repeatedly
  • 3. Shopping cart in online shopping mall

4. Benefits of layered design?
Each function is modularized according to the calling process. The advantage of modularization is that it can be combined at will. Benefits of layering:

  • 1. Decoupling between software is realized
  • 2. Facilitate division of labor
  • 3. Easy to maintain
  • 4. Improve the reuse of software components
  • 5. It’s easy to replace a product. For example, hibernate is used in the persistence layer. If you need to change the product to mybatis, you don’t need to change the code of other services. You can change the configuration directly
  • 6. It is convenient for the expansion of product functions
  • 7. Easy to adapt to the changing needs of users

5. What is the mechanism of implementing polymorphism in Java?

A reference variable defined by a parent class or interface can point to an instance object of a subclass or a specific implementation class, while the method called by the program is dynamically bound at run time, that is, the method referring to the specific instance object pointed to by the variable, that is, the method of the object running in memory, rather than the method defined in the type of the reference variable.

6. What is the difference between abstract and interface?
A class with the abstract modifier is an abstract class, which cannot be created by an abstract class. The class containing abstract methods must be defined as abstract class, and the methods in the abstract class need not be abstract. Abstract methods defined in abstract class must be implemented in concrete subclasses. Therefore, there cannot be abstract construction methods or abstract static methods. If the subclass does not implement all the abstract methods in the abstract parent class, the subclass must also be defined as abstract type.

Interface can be said to be a special case of abstract class. All methods in the interface must be abstract. The method definition in the interface defaults to public abstract type, and the member variable type in the interface defaults to public static final.
The following is a comparison of the two grammatical differences:

  • 1. Abstract classes can have constructors, but interfaces cannot have constructors.
  • 2. There can be ordinary member variables in the abstract class, but there are no ordinary member variables in the interface
  • 3. Abstract class can contain non abstract common methods. All methods in the interface must be abstract, and there can be no non abstract common methods.
  • 4. The access types of abstract methods in abstract classes can be public, protected and default types, but the abstract methods in the interface can only be of public type, and the default is public abstract type.
  • 5. Abstract classes can contain static methods, but interfaces cannot contain static methods
  • 6. Both abstract classes and interfaces can contain static member variables. The access types of static member variables in abstract classes can be arbitrary, but the variables defined in the interface can only be of public static final type, and the default is public static final type.
  • 7. A class can implement multiple interfaces, but it can only inherit one abstract class.

7. Can constructor be overridden?
Constructor cannot be inherited, so override cannot be overridden, but can be overloaded.

8. What are the characteristics of object-oriented?
There are three characteristics of object-oriented

  • Encapsulation: to ensure the integrity and security of the object’s own data.
  • Inheritance: establish the relationship between classes, realize code reuse, and facilitate system expansion.
  • Polymorphism: the same method call can realize different implementation methods.

9. Is string the most basic data type? Can I inherit the string class?
The basic data types of Java are as follows:

  • Integer: byte short int long
  • Float double
  • Character type: char
  • Boolean: Boolean

java.lang.String Class is of type final, so you cannot inherit it or modify it. In order to improve efficiency and save space, it is recommended to use the StringBuffer class for strings that need to be modified frequently.

10. Does the array have the length() method? Does the string have the length() method?
The array does not have the length () method, but has the length attribute.
String has the method length().

11. String s = new string (“ABC”); how many string objects have been created? What is the difference between them?
Answer: one or two
Analysis:

  • 1. If “ABC” has been created in the string buffer, it will not continue to be created. At this time, only one object new string (“ABC”) is created;
  • 2. If “ABC” is not created in the string buffer, two objects will be created, one with the value of “ABC” and the other with new string (“ABC”).

12. How many objects are created in the following statement: String s = a “+” B “+” C “+” d “
Only one string object is created, because this line of code is optimized by the compiler when compiling, which is equivalent to defining a “ABCD” string directly, so only one string object is created.

13. If there is a return statement in try {}, will the code in finally {} immediately after the try be executed, and when, before or after return?
The code in finally will certainly be executed, but the code in try will be executed first. If there is a return in the try, the return will be put into the function stack first, and then the code in finally will be executed.

  • ① . if there is a return in finally, it will directly return and terminate the program, and the return in the function stack will not be completed;
  • ② . if there is no return in finally, after the code in finally is executed, the content of return in try in function stack will be returned and the program will be terminated;

14. The difference between final, finally, and finalize

  • Final: used when declaring a global variable, which means that the variable cannot be modified or overridden. It is generally used to declare constants or values set by the system.
  • Finally: provides a finally block to perform any cleanup operations during exception handling. Finally blocks are executed regardless of whether an exception is thrown or caught.
  • Finalize: is the method name. Java technology allows you to use the finalize () method to do the necessary cleanup before the garbage collector clears the object from memory.

15. What are the similarities and differences between runtime exceptions and general exceptions?
Java provides two main types of exceptions: runtime exception and checked exception

  • Runtime exception, we can not handle it. Such exceptions are taken over by the virtual machine. When a runtime exception occurs, the system will throw the exception all the way to the upper layer, and always encounter the processing code. If the runtime exception is not handled, either the thread aborts or the main program terminates after the runtime exception.
  • General exception checked exception, Java requires programmers to try catch it. Therefore, in the face of such exceptions, whether we want to or not, we can only write a lot of catch blocks to deal with possible exceptions.

16. What is the difference between error and exception?

  • Error means system level error and exception that program does not need to handle. It is an internal error or hardware problem in Java running environment. For example: insufficient memory resources. For this kind of error, the program is basically powerless and has no choice but to exit the operation. It is thrown by the Java virtual machine.
  • Exception refers to an exception that needs to be caught or handled by the program. It deals with problems caused by flaws in program design or general problems caused by external input. It must be handled by the program. Exception is subdivided into runtime exception and checked exception.

17. Please write down the five most common runtime exceptions

  • ClassCastException type cast exception
  • The exception is thrown when the classnotfoundexception class is not found
  • The FileNotFoundException file did not find an exception
  • NullPointerException null pointer exception
  • Sqlexception operation database exception
  • Arithmetical exception
  • Illegalargumentexception passing illegal parameter exception
  • Indexoutofboundsexception subscript out of bounds exception
  • NoSuchElementException method did not find an exception

18. How does Java language handle exceptions? What are the meanings of the keywords: throws, throw, try, catch, finally? Can an exception be thrown in a try block?

  • The Java code to be detected is placed in the try {} statement block, which may throw exceptions or execute normally;
  • The catch (exception type) {} block is that when the Java runtime system receives the exception object thrown from the try block, it will find the catch block that can handle the exception to handle it (there can be multiple catch blocks);
  • Finally {} block is executed regardless of whether the system throws an exception or not. It is generally used to release resources. Except before System.exit (0);
  • Throw is used to throw an exception manually. As a programmer, you can throw exception manually at any position;
  • Throws is used to identify the exception to be thrown on the method, and the thrown exception is handled by the caller;

19. What’s the difference between ArrayList and vector and LinkedList?

  • (1) Vector is thread safe, but ArrayList is not.
  • (2) When the storage space is insufficient, ArrayList is increased by 50% by default, and vector is doubled by default.
  • (3) Vector can set parameters for capacity increase, but ArrayList can’t.
  • (4) LinkedList uses two-way linked list to store data. Index data by serial number needs to traverse forward or backward. However, when inserting data, you only need to record the items before and after the item, so the insertion speed is faster.

20. What’s the difference between list and map?

  • (1) List is a collection of data stored in a single column. The data stored in the list is sequential and can be repeated;
  • (2) Map is a collection of double column data such as key and value. The data stored in map has no order, its key cannot be repeated, and its value can be repeated.

21. What are the characteristics of the three interfaces of list, map and set when accessing elements?
Both list and set are collections of single column elements, and they have a common parent interface collection.

  • (1) A list represents a sequential set
    Storage element: when the add (object) method is called many times, the added objects are sorted in the order of first come first served, or queue jumping. That is, by calling the add (int index, object) method, the storage location of the current object in the collection can be specified.
    Take elements:

Method 1: iterator interface gets all, traverses each element one by one
Method 2: call get (index I) to specify which one to take.

  • (2) Duplicate elements are not allowed in set
    Storage element: the add method has a return value of Boolean. When there is no element in the collection and the add method can successfully add the element, it will return true; when the collection contains elements equal to the equals of an element, the add method cannot add the element, and the return result is false.
    Get elements: you can’t say which one to take. You can only get all the elements with iterator interface, and then traverse each element one by one.
  • (3) A map is a set of two columns, which is stored by the put method: put (obj key, obj value). Each time a map is stored, a pair of keys / values must be stored, and duplicate keys cannot be stored. This repeated rule is also equal by equals.
    Get the element: use the get (object key) method to get the corresponding value according to the key.

22. Name some common classes, packages and interfaces. Please give 5 examples each

  • Common classes:
    Object
    Date
    File
    Exception
    Random
    String
    integer
  • Common bags:
    java.io
    java.lang
    java.util
    java.sql
    java.net
  • Common interfaces:
    Set
    List
    Map
    Collection
    Runnable
    Session
    Servlet

23. How many types of streams exist in Java? JDK provides some abstract classes for each type of stream to inherit. Which classes are they?

  • Based on flow direction:
    InputStream
    OutputStream
  • Character based:
    Reader
    Writer
  • Matching between stream and character:
    InputStreamReader
    OutputStreamWriter

24. The difference between byte stream and character stream?

  • (1) Byte stream does not use buffer (memory) during operation, but is directly operated by file itself, while character stream uses buffer during operation, and then operates file through buffer.
  • (2) In byte stream, Chinese may be garbled and character stream will not.

25. What is java serialization and how to realize java serialization? Or explain what the serializable interface does.
Serialization is a mechanism used to process the object stream. The so-called object stream is to stream the content of the object. It can read and write the streaming objects, and transfer the streaming objects between networks. Serialization is to solve the problems caused by reading and writing object stream.

Implementation of serialization:The serializable interface is implemented for the class to be serialized, and then an output stream (e.g. fileoutputstream) is used to construct an objectoutputstream (object stream) object. Then, the object with obj parameter can be written out (i.e., its state is saved) by using the writeobject (object obj) method of objectoutputstream object, and the input stream is used to restore it;

Only objects of classes that implement serializable and externalizable interfaces can be serialized

Java serialization technology allows you to write the state of an object into a byte stream, and read the data in the byte stream from other places, and reconstruct the same object. This mechanism allows you to propagate objects over the network and persist them to databases, files and other systems at any time. Java serialization mechanism is the technical foundation of RMI, EJB and other technologies. Purpose: use the serialization of objects to save the current working state of the application, and it will be automatically restored to the last execution state when it is started again next time.

26. What is GC? Why do we have GC?
GC means garbage collection,Memory processing is the place where programmers are prone to problems. Forgetting or wrong memory will lead to instability or even crash of the program or system. The GC function provided by java can automatically monitor whether the object exceeds the scope, so as to achieve the purpose of automatically reclaiming memory. Java language does not provide the display operation method of releasing allocated memory. Java programmers don’t have to worry about memory management because the garbage collector does it automatically.

27. What are the methods of sorting? Please use java to implement a bubble sort.
The sorting methods are as follows:

  • Insertion sort (direct insertion sort, Hill sort)
  • Exchange sort (bubble sort, quick sort)
  • Select sort (direct select sort, heap sort)
  • Merge sort
  • Distribution sort (case sort, cardinal sort)
  • Bubble sort:
for(int i=0;i< arr.length -1. I + +) {// the outer loop controls the number of sorting passes  
for(int j=0;j< arr.length -1-I; j + +) {// the inner loop controls how many times each pass is sorted  
if(arr[j]>arr[j+1]){  
int temp=arr[j];  
arr[j]=arr[j+1];  
arr[j+1]=temp;  
}  
}  
}

The pithy formula of bubble sorting:

  • 1. N numbers are used to line up, and they are smaller and higher than the others.
  • 2. Outer cycle n-1, inner cycle n-1-i
  • 3. If you want to reduce the order, just change the greater than sign into the less than sign in the program.

28. Talk about the life cycle of servlets?
The life cycle of servletsIt is divided into the following steps:

  • First, load and instantiate
  • Second, initialization
  • Third, service
  • Fourth, destruction

When the container is started, the class of the servlet will be loaded and the object will be new. Then, when the user requests the servlet, the container will call the init method to initialize the servlet. This method will only be called once in the whole life cycle. Then, the service method will be called, and the doget or dopost methods will be called by this method to respond to the user. Then, the container will call the doget or dopost methods to respond to the user This servlet will be destroyed in case of resource shortage or long-term absence of requests to the servlet.

29. What is the difference between forward() and redirect() in servlet API?

  • (1) Forward is only the change of control in the container, and the address after the switch will not be displayed in the address bar of the client browser;
  • (2) Redirect is a complete jump. The browser will get the address of the jump and resend the request link. In this way, you can see the linked address after the jump from the browser’s address bar. Therefore, forward is more efficient. When forward can meet the needs, use the forward () method as much as possible, and it also helps to hide the actual links. But in some cases (for example, you need to jump to a resource on another server), you must use the sendredirect() method.
  • (3) Forward: forward page and forward page can share the data in the request
  • (4) Redirect: cannot share data

30、 request.getAttribute () and request.getParameter () what is the difference?

  • (1) request.getParameter It is used to receive the parameter values passed by the post and get methods
  • (2) request.getAttribute Is to get the value of the object container (session)
  • (3) request.getParameter The () method returns data of type string.
  • (4) request.getAttribute The () method returns an object that exists in the request scope.

31. What are the common built-in objects in JSP?

  • <1>、request
  • <2>、response
  • <3>、session
  • <4>、out
  • <5>、page
  • <6>、application
  • <7>、exception
  • <8>、pageContext
  • <9>、config

32. What are the similarities and differences between JSP and servlet, and what is the relationship between them?

  • ① JSP is an extension of Servlet Technology, which is essentially a simple way of servlet, and emphasizes the external expression of application. JSP is a “class servlet” after being compiled.
  • ② JSP is a combination of Java and HTML files with the extension. JSP. JSP focuses on view, and servlet is mainly used for control logic.
  • ③ The main difference between servlet, servlet and JSP is that the application logic of servlet is in Java file and completely separated from HTML in presentation layer.

33. What technologies are used to implement each part of MVC?
MVC is the abbreviation of model view controller. Through this design model, application logic, process and display logic are divided into different components.

  • (1) The model represents the business logic of the application (implemented through JavaBeans and EJB components)
  • (2) View is the representation of the application (generated by JSP page)
  • (3) The controller is to provide the process control of the application (usually a servlet)

34. What are the three paradigms of database?

  • The first paradigm: ensuring the atomicity of each column
    (atomic fields cannot be subdivided, otherwise it is not a relational database)
  • The second paradigm: on the basis of the first normal form, ensure that every column in the table is related to the primary key
    (uniqueness, a table only describes one thing)
  • The third paradigm: on the basis of the second paradigm, ensure that each column is directly related to the primary key column, not indirectly
    (each column is directly related to the primary key, and there is no transitive dependency)

35. What are some experiences in database optimization?

  • 1. Use index to improve efficiency and avoid calculation on index column.
  • 2. Avoid the use of ‘in the select clause*‘
  • 3. Reduce the times of accessing database
  • 4. Use commit as much as possible
  • 5. Replace having clause with where clause
  • 6. Replace in with exists and replace not in with not exists
  • 7. Use alias of table
  • 8. Avoid resource consuming operations
  • 9. Generally speaking, Preparedstatement has better performance than statement
  • 10. If the program can guarantee the integrity of the data, the foreign key should be removed when designing the database
  • 11. When there are many data to be queried, use paging to query
  • 12. Try not to use order by Rand ()
  • 13. Optimize query by using query cache
  • 14. Try not to use not in and like statements

36、 Class.forName What is the role of?

  • Class.forName ( xxx.xx.xx )It returns a class. Any class in Java must be loaded on the virtual machine to run. This sentence is used to load the class.
  • Class.forName ( xxx.xx.xx )In other words, the JVM will execute the static code segment of the class, dynamically load and create class objects. The most familiar thing is to load the driver class when JDBC connects to the database.

37. What is the working mechanism of data connection pool?
The J2EE server will establish a certain number of pool connections when it is started, and maintain no less than this number of pool connections all the time. When a client program needs a connection, the pool driver returns an unused pool connection and marks it as busy. If there are currently no idle connections, the pool driver creates a certain number of new connections, which are determined by the configuration parameters. When the used pool connection call is completed, the pool driver marks the connection as idle and other calls can use the connection.

38. Why use ORM? What’s the difference between ORM and JDBC?

  • Object relational mapping (ORM) pattern is a technology to solve the mismatch between object-oriented and relational database. In short, ORM is to automatically persist the objects in the program to the relational database by using metadata that describes the mapping between objects and databases.
  • ORM is an idea, which is to change the object into a record in the database or to change the record in the database into an object. We can use JDBC to realize this idea. In fact, if our project is written in strict accordance with OOP mode, our JDBC program, whether intentionally or unintentionally, is already implementing ORM work.
  • Now there are many ORM tools. They call JDBC at the bottom to realize ORM work. If we use these tools directly, we can save the tedious details of using JDBC directly and improve the development efficiency. The more ORM tool used now is hibernate.

39. What parsing technologies does XML have? What are the differences?

XML has the following two parsing technologies:
  • (1) DOM (document object model) document object model
  • (2)SAX(Simple API for XML)

The differences between them are as followsDOM is a one-time operation to read the entire document into memory. If the document is relatively small, reading it into memory can greatly improve the speed of operation. However, if the document is large, DOM will be more difficult. So SAX is applied at this time, it is not a one-time reading of the entire document into memory, which is awesome for handling large documents.

40. Talk about your understanding of struts.

  • Struts framework is the encapsulation of MVC mode, which provides developers with three logical components of MVC, mainly including actionservlet, action and struts- config.xml The control layer is composed of configuration files, and ActionForm is responsible for the function of model layer, while the view layer of struts is mainly completed by JSP;
  • It processes a request: the actionservlet receives a request, and then determines which action to process and which ActionForm saves the data according to the configuration file, and then determines which JSP should display the data through the return value of the action.

41. Advantages and disadvantages of struts
advantage:

  • (1) The MVC mode is implemented, and the hierarchical structure is clear, so that programmers only need to pay attention to the implementation of business logic.
  • (2) Rich tag library greatly improves the efficiency of development.
  • (3) Struts2 provides rich interceptor implementations.
  • (4) Through the configuration file, you can master the relationship between the various parts of the whole system.
  • (5) The exception handling mechanism only needs to configure the exception mapping in the configuration file to handle the exception accordingly.
  • (6) Struts2 has high scalability. The core jar package of Struts2 consists of a struts- default.xml In this file, some default beans, resulttype types, default interceptor stack are set. All these default settings can be changed by users using the configuration file, and can be changed to beans and resulttypes developed by themselves. Therefore, if a user develops a plug-in, it can be easily integrated with the Struts2 framework with a simple configuration, which realizes the pluggable feature of the framework for plug-ins.
  • (7) The idea of aspect oriented programming is also well embodied in strut2, and the most important embodiment is the use of interceptors. Interceptors are small functional units one by one. Users can combine these interceptors into a large interceptor. The combined interceptor is just like a single interceptor, as long as it is configured into an action

Disadvantages:

  • (1) It is still a little troublesome to get the parameters from JSP in action in Struts2. The getter and setter methods can be configured for the properties in the action of Struts2, and the request parameters can be set to these properties through the default interceptor. If you use this method, when there are many request parameters, the action class will be bloated by these form attributes, which makes people feel confused. In addition, the properties in action can not only be used to obtain request parameters, but also output to JSP, which will be more chaotic. Suppose you get the parameter money = 100000 from JSP 1, but the action needs to be output to JSP 2, but the output format is different, money = 100000, so the value of money in the action will change.
  • (2) The verification is cumbersome, too cumbersome and too detailed. If the verification is wrong, it can only give the user some information. If there are multiple fields, and each field will return to a different screen when there is an error in each field, this function is not easy to implement under the framework of strut2 with the help of the verification logic provided by the framework.
  • (3) Security needs to be improved. Struts2 exposes two high-risk security vulnerabilities, one is the remote code execution vulnerability when using the abbreviated navigation parameter prefix, and the other is the open redirection vulnerability when using the abbreviated redirection parameter prefix. These loopholes can enable hackers to obtain the “highest authority” of the website server, thus turning the enterprise server into a “chicken” in the hands of hackers

42. Talk about your understanding of spring.
First of all, spring is an open source framework. Spring is created to simplify enterprise application development. Using spring, simple JavaBeans can realize functions that only EJB can achieve before. Spring is an IOC and AOP container framework.

In the field of java development, spring is a lightweight, non-invasive java development framework relative to EJB.

The main core of spring is:

  • (1) . inversion of control (IOC): in the traditional java development mode, when we needed an object, we would use new or getInstance to directly or indirectly call the constructor to create an object. In the spring development mode, the spring container used the factory pattern to create the object we needed. We did not need to create it ourselves, but called directly We can use the objects provided by spring, which is the idea of inversion of control. There are three ways to instantiate a Java object: class constructor, static factory method and instance factory method. When spring is used, we don’t need to care how to instantiate an object. Spring automatically instantiates an object for us through the inversion of control mechanism.
  • (2) Dependency injection (DI): the basic idea of dependency injection is that spring uses the set method of Java Bean object or the construction method with parameters to automatically set the required value for the properties of the required object when we create the required object.
  • (3) Aspect oriented programming (AOP): in the idea of object-oriented programming (OOP), we abstract things vertically into objects. In aspect oriented programming, some similar aspects of an object are abstracted horizontally into a facet. The process of common operations such as permission verification, transaction management, logging and so on is the idea of aspect oriented programming.

43. What is the role of AOP?
AOP (aspect oriented programming) is a programming paradigm, which is used to improve object-oriented programming by considering program structure from another perspective.

The main functions are as follows

  • 1. Reduce the coupling between modules.
  • 2. Make the system easy to expand.
  • 3. Better code reuse

44. Talk about your understanding of hibernate.
Hibernate is an open source object relational mapping (ORM) framework. It encapsulates JDBC with a very lightweight object, which enables Java programmers to manipulate the database with the object programming thinking at will.

Advantages of Hibernate:

  • 1. Encapsulate the code of JDBC accessing database, which greatly simplifies the tedious repetitive code of data access layer.
  • 2. Hibernate is a mainstream persistence framework based on JDBC and an excellent ORM implementation. He greatly simplifies the coding of Dao layer
  • 3. Hibernate uses java reflection instead of bytecode enhancers for transparency.
  • 4. Hibernate has good performance and excellent flexibility of mapping. It supports a variety of relational databases, from one-to-one to many to many complex relationships.

Hibernate core class:
Configuration、SessionFactory 、Session

45. The difference between update() and saveorupdate() in Hibernate

  • If update() is to update an existing managed object, the update() method must be used. This object is in the data.
  • The method of saveorupdate() is to update or insert. If there is a primary key, it will be updated. If there is no primary key, it will be inserted.

46. Describe the advantages and disadvantages of hibernate and JDBC?

  • (1) Compared with hibernate in performance, JDBC has advantages in flexibility.
  • (2) Hibernate has advantages in easy to learn and easy to use.
  • (3) JDBC has advantages when many complex multi table linked queries and complex database operations are used.

47. How to write a one to many configuration file in Hibernate?
One to many configuration file method:
Add a collection object on one side and encapsulate it. Then add labels to the corresponding mapping file, set external inspection, and set the corresponding type of collection objects through the one to many tag.

48. What is the difference between mybatis and Hibernate?
Advantages of mybatis:

  • (1) Mybatis can perform more detailed SQL optimization and reduce query fields.
  • (2) Mybatis is easy to master, but hibernate has a high threshold.

Hibernate advantages:

  • <1> , hibernate Dao layer development is simpler than mybatis, mybatis needs to maintain SQL and result mapping.
  • <2> Hibernate maintains and caches objects better than mybatis, and it is more convenient to maintain objects added, deleted, and queried.
  • <3> Hibernate database portability is very good, mybatis database portability is not good, different databases need to write different SQL.
  • <4> Hibernate has a better secondary caching mechanism, and third-party caching can be used. Mybatis itself provides a poor caching mechanism.

49. What is the function of the reverse attribute of Hibernate?

  • Used to specify the associated controller, the inverse property is false by default
  • If false, the association is controlled by itself
  • If true, the association is controlled by the other party

50. Introduce hibernate’s level 2 cache
Built in cache:Hibernate comes with it and cannot be unloaded. Generally, during hibernate initialization, hibernate will put the mapping metadata and predefined SQL statements into the sessionfactory cache. The built-in cache is read-only.

External cache:Generally speaking, the secondary cache is external cache. By default, sessionfactory will not enable this cache plug-in. The data in the external cache is the replication of database data, and the physical media of the external cache can be memory or hard disk.

Suitable for putting data into L2 cache:
  • Rarely modified
  • Data that is not very important allows for occasional concurrency problems
  • Data not suitable for putting into L2 cache
  • Often modified
  • Financial data, no concurrent problems are allowed
  • Data shared with other application data

51. The difference between load() and get() in session

  • (1) The load method supports delayed loading, while the get method does not.
  • (2) The load method throws objectnotfoundexception when no data is found, while the get method returns null.

52. The relationship and difference between B / s and C / S

(1) C / S (client / server) client / server

Concept: it refers to the communication mode between the client and the server. The client provides the user request interface, and the server responds to the request and processes it, and returns it to the client. The client displays these contents
Protocol: any general protocol
Advantages: reduce system overhead and make full use of the advantages of hardware environment at both ends
Disadvantages: high maintenance cost

(2) B / S (Browser / server) browser / server

Concept: this structure of user interface is completely implemented through WWW browser, some transactions are implemented in the front end, and the main transaction logic is implemented on the server side
Protocol: http protocol
Advantages: saving development cost

The difference between them is as follows

Hardware environment is different:

  • C / s: private network, small LAN
  • B / s: wide area network, only need operating system and browser

Different safety requirements:

  • C / s: generally for fixed user groups, high security
  • B / s: publish some public information with B / S

For different program architectures:

  • C / s: pay attention to the process, check the authority multiple times, and less consider the running speed of the system
  • B / s: multiple considerations on security and access speed

Software reuse is different:

  • C / s: need to consider overall, build reusability is not as good as B / s
  • B / s: independent component, good reusability

System maintenance is different:

  • C / s: it is difficult to maintain it from the overall perspective
  • B / s: individual replacement of components, easy maintenance and upgrading

The problem is different:

  • C / s: fixed user interface, high security, the same operating system
  • B / s: the user is not fixed and has little relationship with the operating platform

Different user interfaces:

  • C / s: on Windows platform, the performance method is limited
  • B / s: browser, vivid expression, reduced difficulty and development cost

Information flow is different:

  • C / s: centralized mechanical management, low interaction
  • B / s: information flow can change, more like a trading center

53. What are the features of spring MVC framework?

  • 1. It is based on component technology. All application objects, whether controllers and views, or business objects, are Java components, and are tightly integrated with other infrastructure provided by spring.
  • 2. Does not rely on servlet API (although the goal is, it does depend on servlet when it is implemented)
  • 3. You can use any view technology, not just JSP
  • 4. Support the mapping strategy of various request resources
  • 5. It should be easy to expand

54. How does spring MVC work?

  • 1. The user sends a request to the front-end controller, dispatcherservlet
  • 2. The dispatcher servlet receives the request and calls the handler mapping processor mapper.
  • 3. The processor mapper finds the specific processor according to the request URL, generates the processor object and the processor interceptor (if any) and returns it to the dispatcher servlet.
  • 4. The dispatcher servlet calls the processor through the handleradapter processor adapter
  • 5. Executive processor (controller, also known as back-end controller).
  • 6. The controller returns modelandview after execution
  • 7. Handleradapter returns modelandview of controller execution result to dispatcher servlet
  • 8. Dispatcherservlet passes modelandview to viewreslver view parser
  • 9. After the viewresolver is parsed, the specific view is returned
  1. The dispatcher servlet renders the view (that is, the model data is filled into the view).
  1. Dispatcherservlet responds to users

55. What are the differences between spring MVC and struts 2?

  • 1. The entry of spring MVC is a servlet, that is, the front-end controller, while the entry of Struts2 is a filter filter.
  • 2. Springmvc is based on method development (a URL corresponds to a method). The request parameters are passed to the formal parameters of the method, which can be designed as single instance or multiple instances (single instance is recommended). Struts2 is based on class development, and parameters are passed through class properties, which can only be designed as multiple instances.
  • 3. Struts uses value stack to store the data of request and response, and accesses the data through ognl. Spring MVC parses the content of request request and assigns value to method parameters through parameter parser, encapsulates the data and view into modelandview objects, and finally transfers the model data in modelandview to the page through the requests field. The JSP view parser uses JSTL by default.

56. Please introduce the five states of thread

  • First, create state. When the thread object is generated, the start method of the object is not called, which means that the thread is in the creation state, and the handwritten string inversion and bubble sorting are performed;
  • Second, ready state. When the start method of the thread object is called, the thread enters the ready state. However, the thread scheduler has not set the thread as the current thread, so it is in the ready state. After the thread runs, it will also be ready after it comes back from waiting or sleeping.
  • Third, operation state. The thread scheduler sets the thread in the ready state as the current thread. At this time, the thread enters the running state and starts to run the code in the run function.
  • Fourth, blocking state. When a thread is running, it is suspended, usually to wait for a certain time (for example, a resource is ready) to continue running. Sleep, suspend, wait and other methods can cause thread blocking.
  • Fifth, the state of death. If the run method of a thread ends or the stop method is called, the thread will die. For a thread that has died, you can no longer use the start method to make it ready

57. Differences between post submission and get submission

The get method transmits the user’s data through URL request, connects the field names and their contents in the form as a pair of strings, and passes the data parameters with the URL string itself. On the server side, you can transfer the user’s data from ‘query’_ String ‘is directly read from the variable, which is highly efficient, but it lacks security, and it is unable to process complex data (it can only be strings, for example, it can not be processed in servlet / JSP, and Java functions such as vector can not be used, and the amount of data input is very small, which is generally limited to about 2 KB);

The post method uses HTTP post mechanism to send the names of the fields in the form and their contents in the HTML header to the server side for action Attribute can refer to the program processing, the program will read the data of the form and process it through stdin mode: in terms of transmission mode, parameters will be packaged in datagram and transmitted from content_ Length, which is read from the environment variable, is easy to transfer larger data. At the same time, because the data is not exposed in the browser’s address bar, the security is relatively high, but this processing efficiency will be affected.

Suggestions:Unless you are sure that the data you submit can be submitted at one time, please use post method as far as possible; submitting data in get mode will bring security problems; user name and password will appear on the URL when submitting data through get method; therefore, post is recommended for form submission.

58. What is dirty reading, non repeatable reading and hallucination reading
Dirty read is also called invalid data read out.One transaction reads data that has not been committed by another transaction, which is called dirty read.
For example, transaction T1 modifies a row of data, but it has not been committed. At this time, transaction T2 reads the data modified by transaction T1, and then transaction T1 rolls back for some reason. The data read by transaction T2 is dirty and non repeatable. It means that two identical queries return different results in the same transaction.
For example, transaction T1 reads a certain data, transaction T2 reads and modifies the data, and T1 reads the data again in order to check the read value, and different results are obtained.

Hallucination is a phenomenon that occurs when a transaction is not executed independently,For example, the first transaction modifies the data in a table, which involves all the data rows in the table. At the same time, the second transaction also modifies the data in the table. This modification is to insert a new row of data into the table. Then, in the future, the user who operates the first transaction will find that there are no modified data rows in the table, which is like an illusion. For example: system administrator a changes the scores of all students in the database from the specific score to ABCDE level, but system administrator B inserts a specific score record at this time. When system administrator a finds that there is still a record that has not been changed after the modification, it is like hallucination, which is called phantom reading.

59. Please introduce the transaction isolation level of spring

  • (1) Default the default transaction isolation level
  • (2)READ_ UNCOMMITTED(read_ Uncommitted) read uncommitted. One transaction can operate another uncommitted transaction, which can not avoid dirty read, non repeatable read, hallucination read, the lowest isolation level and the highest concurrency performance
  • (3)READ_ COMMITTED(read_ Committed) read has been committed, one transaction can not operate on another uncommitted transaction, which can prevent dirty read, non repeatable read and hallucination read.
  • (4)REPEATABLE_ READ(repeatable_ Read) can avoid dirty reading, non repeated reading and unreal reading
  • (5) Serializable (serializable) has the highest isolation level, the lowest resource consumption and the highest cost. It can prevent dirty read, non repeatable read and illusion read

60. Select and sort by dictation

public static void selectSort(int[] a) {  
int minIndex = 0;  
int temp = 0;  
if ((a == null) || (a.length == 0))  
return;  
for (int i = 0; i < a.length - 1; i++) {  
Minindex = I; // minimum array index of unordered area  
for (int j = i + 1; j < a.length; j++) {  
//Find the smallest data in the unordered area and save its array subscript  
if (a[j] < a[minIndex]) {  
minIndex = j;  
        }  
     }  
//Put the smallest element at the front of the loop  
temp = a[i];  
a[i] = a[minIndex];  
a[minIndex] = temp;  
   }  
}

61. The difference between session and cooie
Specifically, the cookie mechanism adopts the scheme of keeping state on the client side, while the session mechanism adopts the scheme of keeping state on the server side. Since the scheme of keeping state on the server side also needs to save an identity on the client side, the session mechanism needs to use the cookie mechanism to save the identity.

62. What is spring IOC container?
Spring IOC is responsible for creating objects, managing objects (through dependency injection), assembling objects, configuring objects, and managing the entire life cycle of these objects.

63. What are the different types of IOC (dependency injection) methods in spring?
Constructor dependency injection:Constructor dependency injection is implemented by the container triggering the constructor of a class, which has a series of parameters, each of which represents a dependency on other classes.
Setter method injection:Setter method injection is to call setter method of bean after instantiating bean by calling nonparametric constructor or nonparametric static factory method, that is, dependency injection based on setter is implemented

64. What kinds of bean scopes does spring support?

  • Singleton: beans have only one instance in each spring IOC container.
  • Prototype: a bean definition can have multiple instances.
  • Request: each HTTP request creates a bean that is valid only in the case of Web-based spring ApplicationContext.
  • Session: in an HTTP session, a bean definition corresponds to an instance. This scope is only valid in the case of Web-based spring ApplicationContext.
  • Global session: in a global HTTP session, a bean definition corresponds to an instance. This scope is only valid in the case of Web-based spring ApplicationContext.

65. What are the common design patterns of J2EE? Let’s talk about the factory mode
23 design patterns in Java:
Factory, builder, factory method, prototype, singleton, facade, adapter, bridge, composite, decorator and flyweight, Proxy, command, interpreter, visitor, iterator, mediator, memento, observer, state, strategy, template Method, chain of responsibility

Factory mode:Factory pattern is a frequently used pattern. A class implemented according to the factory pattern can generate an instance of a class in a group of classes according to the data provided. Usually, this group of classes has a common abstract parent class and implements the same method, but these methods operate differently for different data. First of all, we need to define a base class whose subclasses implement the methods in the base class in different ways. Then we need to define a factory class, which can generate different subclass instances according to the conditions. After getting an instance of a subclass, developers can call methods in the base class without considering which instance of the subclass is returned

66. What is your understanding of database transactions?
In the database, the so-called transaction refers to a group of logical operation units, that is, a group of SQL statements. When some operations in this cell fail, the whole transaction is rolled back and the commit is completed only if all operations are correct. The key point to judge whether the transaction is configured successfully is whether the transaction will be rolled back when an exception occurs. In JDBC, the transaction is automatically committed by default. Each time an SQL statement is executed, if the execution is successful, it will be automatically committed to the database, but cannot be rolled back.
Characteristics of the transaction (acid attribute)

  • 1. Atomicity
    Atomicity means that a transaction is an indivisible unit of work, and the operations in the transaction either occur or do not occur.
  • 2. Consistency
    Transactions must cause the database to transition from one consistent state to another. (data will not be destroyed)
  • 3. Isolation
    Transaction isolation means that the execution of a transaction cannot be interfered by other transactions
  • 4. Durability
    Persistence means that once a transaction is committed, its changes to the data in the database are permanent

67. Talk about your understanding of database index
1. The concept of index
Index is to improve the speed of data retrieval. The index of a database is similar to that of a book. In books, the index allows users to quickly find the information they need without having to look through the whole book. In a database, an index also allows a database program to quickly find data in a table without having to scan the entire database
2. Advantages of indexing

a. Create a unique index to ensure the uniqueness of each row of data in the database table
b. Greatly speed up the speed of data retrieval, which is also the main reason for creating indexes
c. Reduce disk IO (can be located directly like a dictionary)

3. Disadvantages of index

a. It takes time to create and maintain indexes, which increases with the amount of data
b. The index takes up extra physical space
c. When the data in the table is added, deleted and modified, the index should also be dynamically maintained, which reduces the speed of data maintenance

68. Steps of JDBC operating database
① Loading database driver Class.forName (“database driven class”);
② Connection con= DriverManager.getConnection ();
③ , operation database Preparedstatement stat= con.prepareStatement (sql); stat.executeQuery ();
④ Close the database and release the connection con.close ();

69. Introduce optimistic lock and pessimistic lock

  • Optimistic lock: every time you query the data, you think that others will not modify it, so it will not be locked. However, when updating, it will judge whether others have updated the data during this period. You can use the version number, time stamp and other mechanisms. Optimistic lock is suitable for multi read application types, which can improve throughput
  • Pessimistic lock: every time you query the data, you think that others will modify it. Therefore, every time you query the data, you will lock it. If someone wants to take the data, it will block until it gets the lock. The traditional relational database uses this kind of locking mechanism, such as through select . for update.

70. How do you understand Ajax

  • Ajax, fully known as “asynchronous JavaScript and XML”, is a web development technology to create interactive web applications.
  • Using Ajax can improve the user experience, asynchronous data transmission and improve performance. Ajax can’t cross domain, so-called cross domain means that it can’t cross multiple websites (multiple domain names), or multiple projects.
  • We can solve the problem of cross domain Ajax through jsonp, and the essence of jsonp is to dynamically add script tags to achieve.

71. Do you know about load balancing?
Load balance is one of the factors that must be considered in the design of distributed system architecture. It usually means that the request data is evenly distributed to multiple operating units. The key of load balancing is “uniform”. The common Internet distributed architecture is divided into client layer, reverse proxy nginx layer, site layer, service layer and data layer.
Load balancing has two meanings

  • 1. A large number of concurrent access or data traffic are shared to multiple node devices for separate processing, which reduces the waiting time of users;
  • 2. The calculation of a single heavy load is shared to multiple node devices for parallel processing. After the processing of each node device, the results are summarized and returned to the user. The system processing capacity is greatly improved

72. Please talk about the Linux instructions you are familiar with

Ls lists the files in the directory
CD to a directory
CP replication
MV Mobile
RM delete
PWD view current location
Tar decompression tar.gz file
MKDIR create folder
Touch to create a file
VI edit (VIM)
Cat view
Chmod set file permissions

73. Brief introduction of project life cycle

  • 1. Demand analysis
  • 2. Outline design
  • 3. Detailed design (use case diagram, flow chart, class diagram)
  • 4. Power Designer
  • 5. Code development
  • 6. Unit test (JUnit white box test) (developer)
    SVN version management tool (submit, update code, document)
  • 7. Integration test (black box test, LoadRunner (write test script) (advanced test))
  • 8. On line trial operation (user inspection)
  • 9. Load runner
  • 10. Officially launched
  • 11. Maintenance

74. Talk about thread deadlock in your understanding
Deadlock is caused by multiple threads accessing shared resources, which is caused by improper access sequence. Usually, a thread locks a resource a and wants to lock resource B; in another thread, it locks resource B and wants to lock resource a to complete its own operation. Both threads want to get each other’s resources, but are unwilling to release their own resources, resulting in two threads Are waiting and unable to execute.
Causes of Deadlock:It is caused by improper access to shared resources
To put it simply: the so-called deadlock refers to the phenomenon of two or more threads waiting for each other due to competing for resources in the process of execution. If there is no external force, they will not be able to advance.

75. Introduce the guard thread
There are two types of threads in Java:User thread, daemon thread

  • (1) In a more popular way, any Guardian thread is the nanny of all non daemons in the entire JVM: as long as any non daemons thread in the current JVM instance has not ended, the daemons will all work; only when the last non Guardian thread finishes, the guardian thread will finish working with the JVM.
  • (2) The most typical application of guardian thread is GC (garbage collector), which is a very competent guardian.
  • (3) The only difference between a daemon thread and a normal thread is that when all threads in the JVM are daemons, the JVM can exit; if there is one or more non daemons threads, it will not exit. (the above is for normal exit System.exit Will quit)

All the contents of the article are collected from the network. If there are any errors or other problems, you are welcome to leave comments and make corrections. If you have any help, please click like + forward to share.

The following is a summary of the Java interview points collection:

Anti pattern design
In short, antipattern refers to the design patterns / methods that are often used to solve the problems that are often faced, such as inefficient, bad, or to be optimized. Even an anti pattern can be a wrong development idea / idea. Here I would like to give a simple example: in object-oriented design / programming, there is a very important principle, the single responsibility principle. The central idea is that for a module or a class, the module or class should only be responsible for one function of the system / software, and the responsibility should be completely encapsulated by the class. When developers need to modify a function of the system, this module / class is the most important modification place. The corresponding antipattern is God class. Generally speaking, this class controls many other classes and also depends on many other classes. The whole class is not only responsible for its main single function, but also responsible for many other functions, including some auxiliary functions. Many developers who maintain old programs may have encountered this type. There are thousands of lines of code in a class, with many functions, but the responsibility is not clear and single. Unit testing procedures have become extremely complex. This class takes much longer to maintain / modify than other classes. Most of the time, this situation is not intentional by developers. In many cases, it is mainly due to the changes of system age, demand, project resource pressure, project team personnel flow, and system structure changes, resulting in some small, single principle class slowly becoming bloated. Finally, when the class becomes a maintenance nightmare (especially after the departure of a familiar developer), refactoring the class becomes a difficult project.

Design of sub database and sub table
Vertical sub tableIt is common in daily development and design. The popular saying is “big tables split small tables”. Splitting is based on the “columns” (fields) in relational databases. Usually, there are many fields in a table. You can create a new “extended table” to split the fields that are not frequently used or have a large length and put them in the extended table. In the case of many fields, splitting is really more convenient for development and maintenance (the author has seen that in a legacy system, a large table contains more than 100 columns). In a sense, it can also avoid the problem of “cross page” (MySQL and MSSQL are stored through “data page” at the bottom. The problem of “cross page” may cause additional performance overhead. It is recommended that the operation of splitting fields should be done in the database design stage. If it is split in the development process, the previous query statements need to be rewritten, which will bring some extra costs and risks, so it is recommended to be cautious.

Vertical sub databaseIn today’s era of “micro service”, it has become very popular. The basic idea is to divide different databases according to business modules, instead of putting all the data tables in the same database as in the early days. The “service-oriented” splitting operation at the system level can solve the coupling and performance bottleneck at the business system level, which is conducive to the expansion and maintenance of the system. The principle of database level splitting is also interlinked. Similar to the “governance” and “degradation” mechanism of services, we can also manage, maintain, monitor and extend the data of different business types.

As we all know, the database is often the most likely to become the bottleneck of the application system, and the database itself belongs to “stateful”, which is relatively difficult to achieve “horizontal expansion” compared with the web and application server. The connection resources of the database are precious and the processing capacity of the single machine is limited. In the high concurrency scenario, the vertical sub database can break through the bottleneck of IO, connection number and single machine hardware resources to a certain extent, which is an important means to optimize the database architecture in large-scale distributed systems.

Then, many people did not fundamentally understand why they want to split up, nor did they master the principles and skills of splitting. They just blindly imitated the practices of large factories. This leads to many problems after splitting (for example: cross database join, distributed transaction, etc.).

Horizontal sub tableIt is also called horizontal table splitting, which is easier to understand. It is to distribute different data rows in the table into different database tables according to certain rules (these tables are kept in the same database), so as to reduce the amount of data in a single table and optimize query performance. The most common way is to hash and split the module through fields such as primary key or time. Horizontal table splitting can reduce the amount of data in a single table and alleviate the query performance bottleneck to a certain extent. But in essence, these tables are still stored in the same library, so there will still be IO bottlenecks at the library level. Therefore, this practice is generally not recommended.

Horizontal sub database and sub tableWith the same idea of horizontal table splitting mentioned above, the only difference is that these split tables are stored in different data. This is what many large Internet companies have chosen. In a sense, “hot and cold data separation” is used in some systems to migrate less used historical data to other databases. In general, it only provides data query by default. In the scenario of high concurrency and massive data, sub database and sub table can effectively alleviate the performance bottleneck and pressure of single machine and single database, and break through the bottleneck of IO, connection number and hardware resources. Of course, the investment in hardware costs will be higher. At the same time, it will also bring some complex technical problems and challenges (such as complex queries across partitions, cross sharding transactions, etc.).

Distributed dilemma and Countermeasures

  • Data migration and expansion
    The strategy of horizontal sub table is summarized as two cases: random sub table and continuous sub table. Continuous sub table may have the problem of data hotspots. Some tables may be frequently queried, resulting in greater pressure. The hot data table becomes the bottleneck of the whole database, while some tables may store historical data, and rarely need to be queried. Another advantage of continuous sub table is that it is relatively easy. It does not need to consider the migration of old data. It can be automatically expanded by adding sub tables. The data of randomly divided tables is relatively uniform, so it is not easy to appear the bottleneck of hot spots and concurrent access. However, the split table extension needs to migrate the old data.
    If you want to learn java engineering, high performance and distributed, easy to understand. Micro service, spring, mybatis, netty source code analysis, double 11 actual combat or interview difficult friends can add 582505643 to the group leader, feel stupid cute can come to her to cheat information, are dry goods.
    The design of horizontal table is very important. We need to evaluate the growth rate of business in the short and medium term, plan the capacity of the current data volume, and calculate the approximate number of slices by integrating cost factors. For the problem of data migration, the general approach is to read the data through the program, and then write the data to each sub table according to the specified sub table strategy.
  • Table association problem
    In the case of single database and single table, joint query is very easy. However, with the evolution of sub database and sub table, joint query will encounter cross database association and cross table relationship. At the beginning of the design, we should try our best to avoid the joint query, which can be assembled in the program or avoided by anti normal design.
  • Pagination and sorting
    In general, the list needs to be sorted according to the specified fields when paging. In the case of single database and single table, paging and sorting are also very easy. However, with the evolution of sub database and sub table, cross database sorting and cross table sorting will also be encountered. In order to ensure the accuracy of the final results, we need to sort and return the data in different sub tables, summarize and re sort the result sets returned by different sub tables, and finally return them to users.
  • Distributed transaction problem
    With the evolution of sub database and sub table, there will be distributed transaction problems, so how to ensure the consistency of data has become a problem that must be faced. At present, there is no good solution for distributed transaction, which is difficult to meet the strong consistency of data. In general, it is necessary to make the stored data as consistent as possible to ensure that the system can recover and correct itself after a short period of time, and finally the data will be consistent.
  • Distributed globally unique ID
    In the case of single database and single table, it is really simple to use the database auto increment feature to generate the primary key ID. In the environment of sub database and sub table, the data is distributed on different sub tables, so the self growth characteristics of database can not be used. You need to use a globally unique ID, such as UUID, guid, and so on.

Deadlock problems encountered by MySQL

There are four necessary conditions for deadlock

(1) Mutex condition: a resource can only be used by one process at a time.
(2) Request and hold condition: when a process is blocked by a request for resources, it holds the acquired resources.
(3) The condition of not depriving: the resources obtained by the process can not be forcibly deprived before they are used up.
(4) Cyclic waiting condition: a cyclic waiting resource relationship is formed between several processes.

These four conditions are the necessary conditions for deadlock. As long as the system deadlocks, these conditions are bound to be true, and as long as one of the above conditions is not met, deadlock will not occur.The following methods help to minimize deadlocks:
(1) Access objects in the same order.
(2) Avoid user interaction in transactions.
(3) Keep the transaction short and in a batch.
(4) Use a low isolation level.
(5) Use the binding connection.

The principle of database index
Database index is a sort data structure in database management system, which helps to query and update data in database table quickly. The implementation of index usually uses B-tree and its variant B + tree.

The difference between clustered index and nonclustered index

  • 1) . a clustered index can only have one table, while a non clustered index can have more than one table
  • 2) Clustered index storage records are physically continuous, while nonclustered indexes are logically continuous and physical storage is not
  • 3) Clustered index: the physical storage is sorted according to the index; the clustered index is an index organization form, and the logical order of the key value of the index determines the physical storage order of the table data rows
    Nonclustered index: physical storage is not sorted by index; nonclustered index is ordinary index, which only creates corresponding index for data column, and does not affect the physical storage order of the whole table
  • 4) The index is described by the data structure of binary tree. We can understand cluster index as follows: the leaf node of the index is the data node. The leaf node of the non clustered index is still the index node, but there is a pointer to the corresponding data block.

Redis persistence mechanism and how to implement it
Redis has two persistence mechanisms, RDB and AOF.

  • RDB persistence saves a snapshot of that point in time at a specific interval.
  • Aof persistence mode records the write operations received by each server. When the service is started, the recorded operations are executed one by one to reconstruct the original data. The format of the write operation command record is consistent with the redis protocol, and it is saved by appending.
  • The persistence of redis can be disabled, that is, you can make the life cycle of data exist only in the running time of the server.

The two methods of persistence can exist at the same time, but when redis restarts, AOF files will be preferentially used to rebuild data.

Cache degradation

  • Page demotion: in a big promotion or some special circumstances, some pages occupy some scarce service resources. In case of emergency, the whole page can be downgraded to achieve the loss of soldiers;
  • Page fragment downgrade: for example, the merchant part in the product details page needs to be downgraded due to data error;
  • Page asynchronous request downgrading: for example, there are asynchronous loading requests such as recommendation information / delivery to on the product details page. If the response of these information is slow or there is a problem with the back-end service, it can be demoted;
  • Service function degradation: for example, when rendering the product details page, some less important services need to be called, such as related classification, hot list, and these services can be degraded if they are not obtained directly under abnormal circumstances;
  • Read demotion: for example, in the multi-level cache mode, if there is a problem with the back-end service, it can be demoted to read-only cache, which is suitable for scenarios with low requirements for read consistency; if you want to learn java engineering, high-performance, distributed, and easy to understand. Micro service, spring, mybatis, netty source code analysis, double 11 actual combat or interview difficult friends can add 582505643 to the group leader, feel stupid cute can come to her to cheat information, are dry goods.
  • Write downgrade: for example, we can only update the cache, and then asynchronously and synchronously reduce the inventory to DB to ensure the final consistency. At this time, we can downgrade the DB to cache.
  • Crawler demotion: when promoting activities, crawler traffic can be directed to static pages or return empty data, thus protecting the back-end scarce resources.
  • Automatic switch degradation
    Automatic degradation is based on system load, resource usage, SLA and other indicators.
  • Timeout degradation
    When the accessed database / HTTP service / remote call response is slow or slow for a long time, and the service is not a core service, it can be automatically degraded after timeout; for example, there are recommended content / evaluation on the product details page, but the recommended content / evaluation is not displayed temporarily, which will not have a great impact on the user’s shopping process; for this kind of service, it can be degraded after timeout. If you are calling someone else’s remote service, define a maximum service response time with the other party. If the time-out is exceeded, it will be automatically degraded.
Java web learning path

============

3W+ word length depth summary Java programmer interview questions collection of Essentials (with mind map).

Tools and knowledge for Java programming

==============

3W+ word length depth summary Java programmer interview questions collection of Essentials (with mind map).

The basic structure of the JVM

========

3W+ word length depth summary Java programmer interview questions collection of Essentials (with mind map).

SSH Framework

=====

3W+ word length depth summary Java programmer interview questions collection of Essentials (with mind map).

Relationship between design patterns

=========

3W+ word length depth summary Java programmer interview questions collection of Essentials (with mind map).

Java knowledge structure system diagram

3W+ word length depth summary Java programmer interview questions collection of Essentials (with mind map).

Java knowledge learning plan

3W+ word length depth summary Java programmer interview questions collection of Essentials (with mind map).

Learning needs to know:

1. What is it
2. What problems have been solved
3. How did it happen

All the contents of the article are collected from the network. If there are any errors or other problems, you are welcome to leave comments and make corrections. If you have any help, please click like + forward to share.

Welcome to the official account of the brother of migrant workers:Migrant workers’ technology road
3W+ word length depth summary Java programmer interview questions collection of Essentials (with mind map).