Java interview must-test points--Lecture 02 (Part 2): Java language features and design patterns

Design pattern knowledge points

I talked about operating system and network knowledge before, and then there are the inspection points of design patterns. There are generally two points:

  • Implementation of common design patterns;

  • Design pattern usage scenarios.

Design patterns are divided into 3 major types and a total of 23 types:

  1. Creation type: factory method pattern, abstract factory pattern, singleton pattern, builder pattern, prototype pattern.

  2. Structural type: adapter mode, decorator mode, proxy mode, appearance mode, bridge mode, combination mode, flyweight mode.

  3. Behavioral: Strategy pattern, template method pattern, observer pattern, iterative sub-pattern, chain of responsibility pattern, command pattern, memo pattern, state pattern, visitor pattern, mediator pattern, interpreter pattern.

The most common design patterns are: singleton pattern, factory pattern, agent pattern, constructor pattern, chain of responsibility pattern, adapter pattern, observer pattern, etc., as shown in the figure below.

Regarding design patterns during the interview, you should understand what scenario problems different designs are used to solve, and be able to flexibly apply common design patterns. The following focuses on several commonly used design patterns.

Singleton pattern

The first is the singleton pattern, which is often used in actual business and is also the main inspection point in the design pattern. Here we introduce the implementation of thread-safe singleton mode.

There are three common ways to implement the singleton pattern.

  • The first is the static initialization method, also called the hungry method. The idea of ​​implementation is to complete the creation of the singleton instance when the class is initialized, so there will be no concurrency problems. In this way, the singleton will be created regardless of whether it will be used.

  • The second implementation method is double checking, also called the lazy method. This singleton instance will only be created when it is actually used. If it is not used, it will not be created. This method will inevitably face concurrency problems when multiple threads use the instance at the same time. In order to solve the problem of concurrent access, double check is performed through synchronized or lock to ensure that only one thread can create the instance. Pay attention here to the concurrency issues caused by memory visibility, and you must use the volatile keyword to modify singleton variables.

  • The third is the singleton registry method. The singleton mode of Bean in Spring is implemented through the singleton registry method.

The following is an introduction to commonly used design patterns based on the practical applications of design patterns, as shown in the figure below. When encountering similar problems during interviews, remember to combine design patterns with actual business scenarios to demonstrate your understanding and application capabilities of design patterns.

Factory pattern

The factory pattern is a commonly used way to create instances of different types. For example, various beans in Spring are created with different bean factory classes.

proxy mode

The proxy mode is mainly used in scenarios where it is not suitable or cannot directly reference another object. The proxy mode can be used to control the access behavior of the proxy object. Java's proxy mode is divided into static proxy and dynamic proxy. Static proxy refers to the proxy class that has been created during compilation, such as a class written in the source code; dynamic proxy refers to the proxy class that is dynamically created during the running of the JVM. Methods of using dynamic proxy include JDK dynamic proxy, CGLIB, and Javassist wait. If you encounter this problem during an interview, you can give an example of a dynamic proxy. For example, in Motan RPC, the dynamic proxy of JDK is used to encapsulate remote requests through reflection, making the service look like it is using local methods.

chain of responsibility model

The chain of responsibility model is a bit like a factory assembly line. Each node in the chain completes a certain kind of processing of objects. For example, the Pipeline used by the Netty framework when processing messages is a chain of responsibility model.

adapter mode

The adapter mode is similar to our common adapters. It adapts two mismatched objects and can also play a role in decoupling two different objects. For example, our commonly used log processing framework SLF4J, if we use SLF4J, can be decoupled from specific log implementation frameworks such as Log4j or Logback. Adapt implementation frameworks such as SLF4J and Log4j through different adapters to complete the use of the log function.

Observer pattern

The observer pattern is also called the publish-subscribe pattern. It is suitable for scenarios where a certain behavior of an object needs to trigger a series of events. For example, the processing of Stream streaming requests in gRPC is implemented through the observer pattern.

Constructor Pattern

The constructor pattern is suitable for an object that has many complex properties and needs to create different specific objects according to different situations, such as the builder method used when creating a PB object.

Java language feature knowledge points

A summary of knowledge points about Java language features is shown in the figure below.

Commonly used collection class implementations and the Java concurrency toolkit JUC are common test points. JUC will be explained in detail in the multi-threading course later.

Some of Java's collection classes require a focus on understanding the implementation of the class. For example, how HashMap and TreeMap are implemented, etc.

Dynamic proxy and reflection are features of the Java language. It is necessary to master the usage scenarios of dynamic proxy and reflection. For example, proxy classes are widely used in ORM frameworks. When RPC is called, the reflection mechanism is used to call the implementation class method.

Java basic data types are often asked in interviews, such as how much memory space each data type occupies, automatic transformation and forced transformation of data types, automatic boxing and unboxing of basic data types and wrapper data types, etc.

Java's references to objects are divided into four types: strong references, soft references, weak references, and virtual references. These references have different processing strategies during GC. Strong references will not be recycled by GC; soft references will be recycled by GC when the memory space is insufficient; Weak references are recycled every GC; virtual references must be used in conjunction with the reference queue and are mainly used to track the process of an object being garbage collected.

Java's exception handling mechanism is the try-catch-finally mechanism. You need to know the processing flow in try catch when an exception occurs; you need to understand the difference between Error and Exception.

Finally, Java's annotation mechanism and SPI extension mechanism can be properly understood as extension points.

Detailed explanation of Map

The basic knowledge about Java focuses on the most frequently examined points, HashMap and ConcurrentHashMap, as well as the new technical features of different versions of Java, as shown in the figure below.

In the interview, the question of Map implementation can test the data structure, basic Java implementation and mastery of concurrency problem handling ideas.

  1. HashMap

    1. Let's first look at the implementation of HashMap. Simply put, Java's HashMap is implemented by adding an array and a linked list. Each item in the array is a linked list. By calculating the HashCode of the stored object, we can calculate the location where the object is to be stored in the array, and use a linked list to resolve hash conflicts. The nodes in the linked list store key-value pairs.
    2. In addition to the implementation method, we also need to know the role of the fill factor and the rehash mechanism when the Map is expanded. We need to know that the capacity of the HashMap is a power of 2 because the remainder can be calculated through a bitwise AND operation, which is more time-consuming than calculating the modulus. quick. In addition, you need to know that HashMap is not thread-safe. In the case of multi-threaded put, it is possible to rehash when the capacity exceeds the fill factor, because in order to avoid tail traversal, HashMap uses head interpolation when inserting elements into the linked list. In multi-threaded scenarios An infinite loop may occur.
  2. ConcurrentHashMap

    1. From the non-thread safety of HashMap, the interviewer will naturally ask about the thread-safe ConcurrentHashMap. ConcurrentHashMap uses the idea of ​​segment lock to reduce the frequency of locking in concurrent scenarios. The implementation differences in JDK1.7 and 1.8 are very different. In 1.7, Segment is used for segment locking to reduce concurrent locking; in 1.8, CAS spin is used. Optimistic locking is used to improve performance, but performance will be average when the concurrency is high. In addition, ConcurrentHashMap in 1.8 introduces red-black trees to solve the problem of linked list sequential search when Hash conflicts occur. The enabling condition of the red-black tree is related to the length of the linked list and the total capacity of the Map. The default is to convert to a red-black tree when the linked list is greater than 8 and the capacity is greater than 64. It is recommended to read the source code in detail to learn this part.
Detailed explanation of Java version features

In recent years, Java has changed its previous version release style, and the release frequency has increased a lot. At present, most companies' production environments still use version 1.8, and a small number of them have upgraded to version 1.9 or 1.10. Java version 1.8 is a long-term supported version, and the latest version 1.11 is also a long-term supported version. In version 1.11 It already contains the functions of versions 1.9 and 1.10, so versions 1.8 and 1.11 are the versions we should focus on.

In version 1.8, Java added support for lambda expressions, making Java code writing more concise and more convenient to support parallel computing. And provides many Stream streaming APIs. Version 1.8 also supports the ability to reference methods, which can further simplify the writing of lambda expressions.

In version 1.8, interfaces can provide default methods, which can simplify some simple abstract classes. Finally, in version 1.8, the method area was adjusted and PermGen's permanent generation was replaced with Metaspace. The biggest difference between Metaspace and PermGen is that Metaspace is not in the virtual machine, but uses local memory. On the one hand, the purpose of replacement is to improve the management of metadata and improve GC efficiency. On the other hand, it is to facilitate the subsequent merger of HotSpot and JRockit.

The main features in versions 1.9 and 1.10 are the addition of a module system, setting G1 as the default garbage collector, and supporting local variable inference and other functions. These features are already included in version 1.11.

Version 1.11 is the latest long-term support version of Java, and will also be the main version in the future. The most exciting feature provided in version 1.11 is ZGC, a new garbage collector. ZGC is designed for large memory heaps and has a very powerful performance, able to achieve GC pause time below 10ms. ZGC will be further introduced in the next lesson. In addition, version 1.11 has enhanced the string processing API and provides functions such as character copying. Version 1.11 also has built-in HttpClient.

Inspection points and bonus points
Interview inspection points

From the interviewer's perspective, the review points of this class on computer basics and Java language features are summarized as follows.

  1. The first inspection point is the inspection of basic concepts and basic principles. It is required that the understanding of these two items must be correct and clear. For example, the concept of the 4/7 layer model of network protocols, the implementation principle of TCP protocol flow control, etc.

  2. The second point of examination is the implementation and usage postures of commonly used tools and models. For example, how is HashMap implemented in JDK 1.8? How many ways are there to implement the singleton pattern? In what scenarios should we use lazy-style singleton implementation, in what scenarios should we use hungry-style singleton implementation, etc.

  3. The third inspection point is some frequently used knowledge points. For example, what are your commonly used Linux commands and what problems are they used to solve?

  4. The fourth inspection point is a point that is easy to make mistakes in practical applications, such as the difference between == and equals. For example, improper use of strong references to objects may lead to memory leaks. It mainly examines the candidate's role and understanding of different object reference methods.

  5. The fifth inspection point is knowledge points related to the interview direction. For example, if the interview position is middleware research and development, the interview may involve more examination of storage and network-related knowledge.

bonus

The aforementioned inspection points are necessary conditions for passing the interview. Answering the questions does not necessarily guarantee passing the interview. Therefore, how to be better than other competitors and leave a better impression on the interviewer is the key to success. You need some buffs. These bonus points are not only specific to the content of this lesson, but also have certain generality in subsequent courses.

  1. Able to combine interview points with actual business scenarios, or with actual use experience.

    This can better reflect the understanding of knowledge points and highlight practical abilities. For example, when answering the question "What design patterns do you know?", not only can you tell how many design patterns are suitable and what types of scenarios they are suitable for, but you can also point out which famous frameworks use which designs when dealing with what problems. Pattern, or what design pattern you used when dealing with certain scenarios in a project, and what results you achieved. This will definitely leave a very good impression on the interviewer.

  2. Use counterexamples to describe problems caused by misuse of certain functions in actual scenarios.

    For example, when introducing the reflection mechanism, in addition to introducing the implementation method and application scenarios of the reflection mechanism, you can also mention that extensive use of reflection will have an impact on performance, and abuse should be avoided.

  3. Know the optimization points related to the inspection knowledge points.

    For example, when introducing TCP connection establishment and disconnection, it is best to point out that if a large number of time_wait occurs online, the system parameters can be adjusted to speed up the recycling and reuse of connections.

  4. Understand the latest technology trends related to knowledge points.

    For example, when introducing the implementation of ConcurrentHashMap, you can know the details of the improvements in version 1.8. Or when introducing HTTP, you can talk about the characteristics and implementation of HTTP2 and QUIC.

  5. When answering interview questions, try to increase the depth of the answer on the premise of a better understanding. For example, when introducing TCP's sliding window, it can talk about flow and congestion control, and further point out different algorithms for solving congestion.

    It should be noted here that the interviewer will usually follow the candidate's answer and continue to ask questions. If the details are not clear, it may be counterproductive.

Summary of real questions

A summary of the real questions is shown in the figure below.

The problem-solving ideas are as follows.

  • The first question: The difference and connection between threads and processes, mainly from the aspects of resource occupation, switching efficiency, communication method, etc.;

  • Question 2: The thread switching process mainly examines context switching, which requires saving registers, stacks and other objects, and switching from user mode to kernel mode. Finally, check the context switching situation through the vmstat command;

  • Question 3: For commonly used Linux commands, please refer to the commands mentioned in the previous operating system summary;

  • Questions 4 and 5 have been introduced in the detailed explanation of knowledge points, so be sure to master them;

  • Question 6: It roughly includes DNS resolution, TCP connection establishment, HTTP request, HTTP response, etc. When actually answering, you can draw a simple interaction diagram to illustrate.

Let’s summarize some real questions, including basic concepts and knowledge points introduced before, as shown in the figure below.

The topic of the next lesson is JVM principles.

Guess you like

Origin blog.csdn.net/g_z_q_/article/details/129758548