The latest and most comprehensive Java interview questions and answers (212)

Article Directory


This article is divided into nineteen modules, namely: " Java 基础、容器、多线程、反射、对象拷贝、Java Web 、异常、网络、设计模式、Spring/Spring MVC、Spring Boot/Spring Cloud、Hibernate、MyBatis、RabbitMQ、Kafka、Zookeeper、MySQL、Redis、JVM ", as shown in the figure below:

在这里插入图片描述

It contains a total of 212 interview questions. The purpose of this article is to compile a detailed and authoritative interview list for readers and friends. Let's enter the topic together.

1. Java Basics

1. What is the difference between JDK and JRE?

JDK: The abbreviation of Java Development Kit, Java Development Kit, provides a Java development environment and operating environment.
JRE: Short for Java Runtime Environment, the Java runtime environment provides the required environment for Java to run.
Specifically, the JDK actually includes the JRE, the compiler Javac that compiles the Java source code, and many tools for debugging and analyzing Java programs. Simply put: if you need to run Java programs, you only need to install JRE, and if you need to write Java programs, you need to install JDK.

2. What is the difference between == and equals?

"== Interpretation"

The effect of == is different for basic types and reference types, as follows:

Basic type: compares whether the values ​​are the same;
reference type: compares whether the references are the same;
code example:

String x = "string";
String y = "string";
String z = new String("string");
System.out.println(x==y); // true
System.out.println(x==z); // false
System.out.println(x.equals(y)); // true
System.out.println(x.equals(z)); // true

Code interpretation: because x and y point to the same reference, == is also true, and the new String() method is rewritten to open up memory space, so the result of == is false, and equals always compares values, so The results are all true.

"Interpretation of equals"

equals is essentially ==, but String and Integer rewrite the equals method and turn it into a value comparison. See the code below to understand.

First look at the default equals compares an object with the same value, the code is as follows:

classCat{
    
    
    publicCat(String name){
    
    
        this.name = name;
    }
    
    private String name;
 
    public String getName(){
    
    
        return name;
    }

    public void setName(String name){
    
    
        this.name = name;
    }
 }

Cat c1 = new Cat("小花");
Cat c2 = new Cat("小花");
System.out.println(c1.equals(c2)); // false

The output is beyond our expectation, it is false? What's going on, you can see the source code of equals, the source code is as follows:

publications(Object obj){
    
    
        return (this == obj);
}

It turns out that equals is essentially ==.

That's the question, why do two String objects with the same value return true? code show as below:

String s1 = new String("小花");
String s2 = new String("小花");
System.out.println(s1.equals(s2)); // true

Similarly, when we entered the equals method of String, we found the answer, the code is as follows:

publicbooleanequals(Object anObject){
    
    
    if (this == anObject) {
    
    
        return true;
    }
    if (anObject instanceof String) {
    
    
        String anotherString = (String)anObject;
        int n = value.length;
        if (n == anotherString.value.length) {
    
    
            char v1[] = value;
            char v2[] = anotherString.value;
            int i = 0;
            while (n-- != 0) {
    
    
                if (v1[i] != v2[i])
                    return false;
                i++;
            }
            return true;
        }
    }
    return false;
}

It turned out that String rewrote the equals method of Object and changed the reference comparison to value comparison.

"Summary" : == is a value comparison for basic types, and a reference comparison for reference types; and equals is a reference comparison by default, but many classes re-equals method, such as String, Integer, etc. It becomes a value comparison, so in general, equals compares whether the values ​​are equal.

3. If the hashCode() of two objects is the same, then equals() must also be true, right?

No, the hashCode() of two objects is the same, equals() is not necessarily true.

Code example:

String str1 = "通话";
String str2 = "重地";
System.out.println(String.format("str1:%d | str2:%d",  str1.hashCode(), str2.hashCode()));
System.out.println(str1.equals(str2));

The result of execution:

str1:1179395 | str2:1179395

false

4. What is the role of final in Java?

  • The final modified class is called the final class, which cannot be inherited.
  • Final modified methods cannot be overridden.
  • Variables modified by final are called constants. Constants must be initialized, and the value cannot be modified after initialization.

5. What is Math. round(-1. 5) equal to in Java?

It is equal to -1, because when taking values ​​on the number axis, the middle value (0.5) is rounded to the right, so positive 0.5 is rounded up, and negative 0.5 is discarded directly.

6. Is String a basic data type?

String is not a basic type, there are 8 basic types: byte, boolean, char, short, int, float, long, double, and String is an object.

7. What classes are there for manipulating strings in Java? What's the difference between them?

The classes for manipulating strings are: String, StringBuffer, StringBuilder.

The difference between String and StringBuffer and StringBuilder is that String declares an immutable object, each operation will generate a new String object, and then point the pointer to the new String object, while StringBuffer and StringBuilder can operate on the basis of the original object, So it is best not to use String when the content of the string is often changed.

The biggest difference between StringBuffer and StringBuilder is that StringBuffer is thread-safe, while StringBuilder is non-thread-safe, but the performance of StringBuilder is higher than that of StringBuffer, so it is recommended to use StringBuilder in a single-threaded environment and StringBuffer in a multi-threaded environment.

8. Is String str="i" the same as String str=new String("i")?

Not the same, because the way memory is allocated is different. String str="i", the Java virtual machine will allocate it to the constant pool; while String str=new String("i") will be allocated to the heap memory.

9. How to reverse a string?

Use the reverse() method of StringBuilder or stringBuffer.

Sample code:

// StringBuffer reverse
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("abcdefg");
System.out.println(stringBuffer.reverse()); // gfedcba
// StringBuilder reverse
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("abcdefg");
System.out.println(stringBuilder.reverse()); // gfedcba

10. What are the commonly used methods of the String class?

  • indexOf(): Returns the index of the specified character.
  • charAt(): Returns the character at the specified index.
  • replace(): String replacement.
  • trim(): Removes blanks at both ends of the string.
  • split(): splits the string and returns a split string array.
  • getBytes(): returns the byte type array of the string.
  • length(): Returns the length of the string.
  • toLowerCase(): Convert the string to lowercase letters.
  • toUpperCase(): Convert the string to uppercase characters.
  • substring(): Intercepts a string.
  • equals(): String comparison.

11. Does an abstract class have to have abstract methods?

No, abstract classes don't have to have abstract methods.

Sample code:

abstract classCat{
    
    
    public static void sayHi(){
    
    
        System.out.println("hi~");
    }
}

In the above code, the abstract class does not have abstract methods but it can run normally.

12. What is the difference between a normal class and an abstract class?

Ordinary classes cannot contain abstract methods, abstract classes can contain abstract methods.
Abstract classes cannot be instantiated directly, ordinary classes can be instantiated directly.

13. Can an abstract class be decorated with final?

No, defining an abstract class is to allow other classes to inherit. If it is defined as final, the class cannot be inherited, which will cause conflicts with each other. Therefore, final cannot modify an abstract class. As shown in the figure below, the editor will also prompt an error message:

14. What is the difference between interface and abstract class?

  • Implementation: Subclasses of abstract classes use extends to inherit; interfaces must use implements to implement interfaces.
  • Constructor: Abstract classes can have constructors; interfaces cannot.
  • Number of implementations: A class can implement many interfaces; but only one abstract class can be inherited.
  • Access modifiers: methods in interfaces are modified by public by default; methods in abstract classes can be any access modifiers.

15. How many types of IO streams are there in Java?

  • Divided by function: input stream (input), output stream (output).
  • Divided by type: byte stream and character stream.

The difference between byte stream and character stream is: byte stream transmits 8-bit input and output data in bytes, and character stream transmits 16-bit input and output data in character units.

16. What is the difference between BIO, NIO, and AIO?

  • BIO: Block IO Synchronous blocking IO is the traditional IO we usually use. It is characterized by a simple mode, easy to use, and low concurrent processing capacity.
  • NIO: Non IO synchronous non-blocking IO is an upgrade of traditional IO. The client and server communicate through Channel (channel) to realize multiplexing.
  • AIO: Asynchronous IO is an upgrade of NIO, also called NIO2, which realizes asynchronous non-blocking IO, and the operation of asynchronous IO is based on event and callback mechanism.

17. What are the common methods of Files?

  • Files.exists(): Check whether the file path exists.
  • Files.createFile(): Create a file.
  • Files.createDirectory(): Create a folder.
  • Files.delete(): Delete a file or directory.
  • Files.copy(): Copy files.
  • Files.move(): Move files.
  • Files.size(): View the number of files.
  • Files.read(): Read a file.
  • Files.write(): Write to a file.

2. Container

18. What are the Java containers?

Java containers are divided into two categories: Collection and Map, and there are many subcategories under them, as follows:

  • Collection

  • List

    • ArrayList

    • LinkedList

    • Vector

    • Stack

  • Set

    • HashSet
    • LinkedHashSet
    • TreeSet
  • Map

  • HashMap

    • LinkedHashMap
  • TreeMap

  • ConcurrentHashMap

  • Hashtable

19. What is the difference between Collection and Collections?

  • Collection is a collection interface, which provides general interface methods for basic operations on collection objects, and all collections are its subclasses, such as List, Set, etc.
  • Collections is a wrapper class that contains many static methods and cannot be instantiated, just like a tool class, such as the sorting method provided: Collections.sort(list).

20. What is the difference between List, Set, Map?

The difference between List, Set, and Map is mainly reflected in two aspects: whether the elements are ordered, and whether elements are allowed to repeat.

The difference between the three is as follows:
在这里插入图片描述

21. What is the difference between HashMap and Hashtable?

  • Storage: HashMap allows key and value to be null, but Hashtable does not.
  • Thread safety: Hashtable is thread safe, while HashMap is not thread safe.
  • Recommended use: As you can see in the class comments of Hashtable, Hashtable is a reserved class and is not recommended to be used. It is recommended to use HashMap in a single-threaded environment instead, and use ConcurrentHashMap instead if multi-threaded use is required.

22. How to decide to use HashMap or TreeMap?

For operations such as inserting, deleting, and locating an element in the Map, HashMap is the best choice, because relatively speaking, the insertion of HashMap will be faster, but if you want to traverse a key collection in an orderly manner, then TreeMap is better choice.

23. Tell me about the implementation principle of HashMap?

HashMap is implemented based on the Hash algorithm. We store it through put (key, value) and get it through get (key). When the key is passed in, HashMap will calculate the hash value according to key.hashCode(), and save the value in the bucket according to the hash value. When the calculated hash values ​​are the same, we call it a hash conflict. HashMap uses a linked list and a red-black tree to store values ​​with the same hash value. When the number of hash conflicts is relatively small, use a linked list; otherwise, use a red-black tree.

24. Tell me about the implementation principle of HashSet?

HashSet is implemented based on HashMap. The bottom layer of HashSet uses HashMap to save all elements. Therefore, the implementation of HashSet is relatively simple. The operations related to HashSet are basically completed by directly calling the relevant methods of the underlying HashMap. HashSet does not allow duplicate values.

25. What is the difference between ArrayList and LinkedList?

  • Data structure implementation: ArrayList is the data structure implementation of dynamic array, and LinkedList is the data structure implementation of doubly linked list.
  • Random access efficiency: ArrayList is more efficient than LinkedList in random access, because LinkedList is a linear data storage method, so you need to move the pointer to search from front to back.
  • Addition and deletion efficiency: LinkedList is more efficient than ArrayList in non-head and tail addition and deletion operations, because ArrayList addition and deletion operations will affect the subscripts of other data in the array.

In general, ArrayList is recommended when elements in the collection need to be read frequently, and LinkedList is recommended when there are many insertion and deletion operations.

26. How to realize the conversion between array and List?

  • Array to List: Use Arrays.asList(array) to convert.
  • List to array: Use the toArray() method that comes with List.

Code example:

// list to array
List<String> list = new ArrayList<String>();
list.add("王磊");
list.add("的博客");
list.toArray();
// array to list
String[] array = new String[]{
    
    "王磊","的博客"};
Arrays.asList(array);

27. What is the difference between ArrayList and Vector?

  • Thread safety: Vector uses Synchronized to achieve thread synchronization, which is thread safe, while ArrayList is not thread safe.
  • Performance: ArrayList is better than Vector in terms of performance.
  • Expansion: Both ArrayList and Vector will dynamically adjust the capacity according to actual needs, but the expansion of Vector will double each time, while ArrayList will only increase by 50%.

28. What is the difference between Array and ArrayList?

  • Array can store basic data types and objects, while ArrayList can only store objects.
  • Array is specified with a fixed size, while the size of ArrayList is automatically expanded.
  • There are not as many built-in methods in Array as in ArrayList, such as addAll, removeAll, iteration and other methods only in ArrayList.

29. What is the difference between poll() and remove() in Queue?

  • The same point: both return the first element and delete the returned object in the queue.
  • The difference: if there is no element, poll() will return null, and remove() will directly throw NoSuchElementException.

Code example:

Queue<String> queue = new LinkedList<String>();
queue.offer("string"); // add
System.out.println(queue.poll());
System.out.println(queue.remove());
System.out.println(queue.size());

30. Which collection classes are thread safe?

Vector, Hashtable, and Stack are all thread-safe, while HashMap is non-thread-safe. However, after JDK 1.5, with the emergence of Java.util.concurrent, they also have their own corresponding thread-safe classes, such as HashMap corresponding to The thread-safe class is ConcurrentHashMap.

31. What is iterator Iterator?

The Iterator interface provides an interface for traversing any Collection. We can get iterator instances from a Collection using the iterator method. Iterators replace Enumeration in the Java collection framework, and iterators allow the caller to remove elements during iteration.

32. How to use Iterator? What are the characteristics?

Iterator usage code is as follows:

List<String> list = new ArrayList<>();
Iterator<String> it = list.iterator();
while(it.hasNext()){
    
    
  String obj = it.next();
  System.out.println(obj);
}

The feature of Iterator is safer, because it can ensure that when the currently traversed collection elements are changed, a ConcurrentModificationException will be thrown.

33. What is the difference between Iterator and ListIterator?

  • Iterator can traverse Set and List collections, while ListIterator can only traverse List.
  • Iterator can only traverse in one direction, while ListIterator can traverse in both directions (forward/backward traversal).
  • ListIterator inherits from the Iterator interface, and then adds some additional functions, such as adding an element, replacing an element, and getting the index position of the previous or following element.

34. How to ensure that a collection cannot be modified?

You can use the Collections.unmodifiableCollection(Collection c) method to create a read-only collection so that any operations that change the collection will throw a Java.lang.UnsupportedOperationException.

The sample code is as follows:

List<String> list = new ArrayList<>();
list.add("x");
Collection<String> clist = Collections.unmodifiableCollection(list);
clist.add("y"); // 运行时此行报错
System.out.println(list.size());

3. Multithreading

35. What is the difference between parallelism and concurrency?

Parallelism: Multiple processors or multi-core processors process multiple tasks simultaneously.
Concurrency: Multiple tasks are executed on the same CPU core in turn (alternately) according to subdivided time slices. From a logical point of view, those tasks are executed at the same time.
As shown below:

请添加图片描述

Concurrency = two queues and a coffee machine.

Parallel = two queues and two coffee machines.

36. What is the difference between thread and process?

A program has at least one process, a process has at least one thread, and a process can also have multiple threads to increase the execution speed of the program.

37. What is a daemon thread?

A daemon thread is a special process that runs in the background. It is independent of the controlling terminal and periodically performs some task or waits for some event to occur. Garbage collection threads are special daemon threads in Java.

38. What are the ways to create threads?

There are three ways to create threads:

  • Inherit Thread to rewrite the run method;
  • Implement the Runnable interface;
  • Implement the Callable interface.

39. What is the difference between runnable and callable?

runnable 没有返回值,callable 可以拿到有返回值,callable 可以看作是 runnable 的补充。

40. What are the states of a thread?

The state of the thread:

  • NEW not started yet

  • RUNNABLE is executing

  • BLOCKED blocked (blocked by synchronization lock or IO lock)

  • WAITING Permanent waiting state

  • TIMED_WAITING Waiting for the specified time to wake up again

  • TERMINATED Execution complete

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

  • Class differences: sleep() comes from Thread, and wait() comes from Object.
  • Release the lock: sleep() does not release the lock; wait() releases the lock.
  • The usage is different: sleep() will automatically resume when the time is up; wait() can use notify()/notifyAll() to wake up directly.

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

notifyAll() will wake up all threads, and wake up one thread after notify(). After notifyAll() is called, all threads will be moved from the waiting pool to the lock pool, and then participate in the competition for the lock. If the competition is successful, the execution will continue. If the competition is unsuccessful, it will stay in the lock pool and wait for the lock to be released before participating in the competition again. And notify() will only wake up one thread, and which thread to wake up is controlled by the virtual machine.

43. What is the difference between run() and start() of a thread?

The start() method is used to start the thread, and the run() method is used to execute the thread's runtime code. run() can be called repeatedly, while start() can only be called once.

44. What are the ways to create a thread pool?

There are seven ways to create a thread pool, the core of which is the last one:

  • newSingleThreadExecutor(): Its feature is that the number of worker threads is limited to 1, and it operates an unbounded work queue, so it ensures that all tasks are executed sequentially, at most one task is active, and users are not allowed Change the thread pool instance, so it can avoid changing the number of threads;
  • newCachedThreadPool(): It is a thread pool used to handle a large number of short-term work tasks. It has several distinctive features: it will try to cache threads and reuse them. When no cached threads are available, new worker threads will be created; if If the thread is idle for more than 60 seconds, it will be terminated and removed from the cache; when it is idle for a long time, this thread pool will not consume any resources. It internally uses SynchronousQueue as a work queue;
  • newFixedThreadPool(int nThreads): Reuse the specified number (nThreads) of threads, behind it is an unbounded work queue, and at most nThreads worker threads are active at any time. This means that if the number of tasks exceeds the number of active queues, it will wait for idle threads to appear in the work queue; if a worker thread exits, a new worker thread will be created to make up the specified number nThreads;
  • newSingleThreadScheduledExecutor(): Create a single-threaded pool and return ScheduledExecutorService, which can perform scheduled or periodic work scheduling;
  • newScheduledThreadPool(int corePoolSize): Similar to newSingleThreadScheduledExecutor(), a ScheduledExecutorService is created, which can perform regular or periodic work scheduling, the difference is whether a single worker thread or multiple worker threads;
  • newWorkStealingPool(int parallelism): This is a thread pool that is often ignored by people. This creation method is only added in Java 8. It will build ForkJoinPool internally, use the Work-Stealing algorithm to process tasks in parallel, and the processing order is not guaranteed;
  • ThreadPoolExecutor(): It is the most primitive thread pool creation. The above 1-3 creation methods are all encapsulation of ThreadPoolExecutor.

45. What are the states of the thread pool?

  • RUNNING: This is the most normal state, accepting new tasks and processing tasks in the waiting queue.
  • SHUTDOWN: Do not accept new task submissions, but will continue to process tasks in the waiting queue.
  • STOP: Do not accept new task submissions, no longer process tasks in the waiting queue, and interrupt threads that are executing tasks.
  • TIDYING: All tasks are destroyed, workCount is 0, and the hook method terminated() will be executed when the state of the thread pool is converted to TIDYING state.
  • TERMINATED: After the terminated() method ends, the state of the thread pool will become this.

46. ​​What is the difference between submit() and execute() methods in thread pool?

  • execute(): Only Runnable type tasks can be executed.
  • submit(): Runnable and Callable tasks can be executed.

Callable type tasks can get the return value of execution, while Runnable execution has no return value.

47. How to ensure the safety of multi-threaded operation in Java programs?

  • Method 1: Use safe classes, such as classes under java.util.concurrent.

  • Method 2: Use automatic lock synchronized.

  • Method 3: Use manual lock Lock.

The Java sample code for manual locking is as follows:

Lock lock = new ReentrantLock();
lock.lock();
try {
    
    
    System.out.println("获得锁");
} catch (Exception e) {
    
    
    // TODO: handle exception
} finally {
    
    
    System.out.println("释放锁");
    lock.unlock();
}

48. What is the principle of synchronized lock upgrade in multithreading?

Synchronized lock upgrade principle: There is a threadid field in the object header of the lock object. When the threadid is accessed for the first time, the threadid is empty, and the jvm allows it to hold a biased lock, and sets the threadid as its thread id. First judge whether the threadid is consistent with its thread id, if it is consistent, you can use this object directly, if not, upgrade the biased lock to a lightweight lock, acquire the lock by spinning a certain number of times, after a certain number of executions, if it is not normal When the object to be used is obtained, the lock will be upgraded from a lightweight lock to a heavyweight lock. This process constitutes an upgrade of a synchronized lock.

The purpose of the lock upgrade: the lock upgrade is to reduce the performance consumption caused by the lock. After Java 6, the implementation of synchronized is optimized, and the biased lock is upgraded to a lightweight lock and then upgraded to a heavyweight lock, thereby reducing the performance consumption caused by the lock.

49. What is deadlock?

When thread A holds exclusive lock a and tries to acquire exclusive lock b, while thread B holds exclusive lock b and tries to acquire exclusive lock a, it will happen that the two threads AB and AB are holding each other's needs. The lock, and the blocking phenomenon that occurs, we call it deadlock.

50. How to prevent deadlock?

  • Try to use tryLock (long timeout, TimeUnit unit) method (ReentrantLock, ReentrantReadWriteLock), set the timeout time, timeout can exit to prevent deadlock.
  • Try to use java.util.concurrent concurrent class instead of your own handwritten lock.
  • Try to reduce the granularity of lock usage, and try not to use the same lock for several functions.
  • Minimize synchronized code blocks.

51. What is ThreadLocal? What are the usage scenarios?

ThreadLocal provides an independent copy of the variable for each thread that uses the variable, so each thread can change its own copy independently without affecting the corresponding copies of other threads.

The classic usage scenarios of ThreadLocal are database connection and session management.

52. Tell me about the underlying implementation principle of synchronized?

Synchronized is implemented by a pair of monitorenter/monitorexit instructions, and the monitor object is the basic implementation unit of synchronization. Before Java 6, the implementation of monitor was completely dependent on the mutex lock inside the operating system. Because of the need to switch from user mode to kernel mode, synchronization operation is an indiscriminate heavyweight operation with low performance. But in Java 6, the Java virtual machine has made drastic improvements to this, providing three different monitor implementations, which are often referred to as three different locks: Biased Locking, lightweight locks and Heavyweight lock with greatly improved performance.

53. What is the difference between synchronized and volatile?

  • volatile is a variable modifier; synchronized is a modified class, method, and code segment.
  • Volatile can only realize the modification visibility of variables, but cannot guarantee atomicity; while synchronized can guarantee the modification visibility and atomicity of variables.
  • Volatile will not cause thread blocking; synchronized may cause thread blocking.

54. What is the difference between synchronized and Lock?

  • synchronized can lock classes, methods, and code blocks; while lock can only lock code blocks.
  • Synchronized does not need to manually acquire and release locks. It is easy to use. When an exception occurs, it will automatically release the lock and will not cause deadlock; while lock needs to be locked and released by itself. If it is not used properly and there is no unLock() to release the lock, it will cause deadlock Lock.
  • Through Lock, you can know whether the lock has been successfully acquired, but synchronized cannot.

55. What is the difference between synchronized and ReentrantLock?

The early implementation of synchronized is relatively inefficient. Compared with ReentrantLock, the performance of most scenarios is quite different, but synchronized has been greatly improved in Java 6.

The main differences are as follows:

  • ReentrantLock is more flexible to use, but there must be a cooperative action to release the lock;
  • ReentrantLock must manually acquire and release the lock, while synchronized does not need to manually release and open the lock;
  • ReentrantLock is only applicable to code block locks, while synchronized can be used to decorate methods, code blocks, etc.

56. Tell me about the principle of atomic?

atomic mainly uses CAS (Compare And Wwap) and volatile and native methods to ensure atomic operations, thereby avoiding the high overhead of synchronized and greatly improving execution efficiency.

4. Reflection

57. What is reflection?

Reflection is in the running state. For any class, you can know all the properties and methods of this class; for any object, you can call any of its methods and properties; The function of the method is called the reflection mechanism of the Java language.

58. What is Java serialization? When is serialization required?

Java serialization is to save the state of various objects in memory, and to read out the saved object state.

The following situations require Java serialization:

  • When you want to save the object state in memory to a file or database;
  • When you want to use sockets to transfer objects over the network;
  • When you want to transfer objects via RMI (Remote Method Invocation).

59. What is a dynamic proxy? What are the applications?

A dynamic proxy is a dynamically generated proxy class at runtime.

The applications of dynamic proxy include spring aop, hibernate data query, back-end mock of test framework, rpc, Java annotation object acquisition, etc.

60. How to implement dynamic proxy?

JDK native dynamic proxy and cglib dynamic proxy. JDK's native dynamic proxy is implemented based on interfaces, while cglib is implemented based on subclasses that inherit the current class.

5. Object copy

61. Why use cloning?

The cloned object may contain some properties that have been modified, and the properties of the new object are still the values ​​at the time of initialization, so when a new object is needed to save the "state" of the current object, it depends on the clone method.

62. How to implement object cloning?

  • Implement the Cloneable interface and override the clone() method in the Object class.
  • Implement the Serializable interface, realize cloning through serialization and deserialization of objects, and realize real deep cloning.

63. What is the difference between deep copy and shallow copy?

  • Shallow clone: ​​When an object is copied, only itself and the member variables of the value type contained in it are copied, while the member objects of the reference type are not copied.
  • Deep clone: ​​In addition to the object itself being copied, all member variables contained in the object will also be copied.

6. Java Web

64. What is the difference between JSP and servlet?

JSP is an extension of servlet technology, which is essentially a simple way of servlet. The main difference between servlet and JSP is that the application logic of servlet is in the Java file, and it is completely separated from the html in the presentation layer. In the case of JSP, Java and html can be combined into a file with the extension of JSP. document. JSP focuses on the view, and servlets are mainly used for control logic.

65. What built-in objects does JSP have? What are the functions?

JSP has 9 built-in objects:

  • request: encapsulates the client's request, which contains parameters from the get or post request;
  • response: Encapsulates the server's response to the client;
  • pageContext: other objects can be obtained through this object;
  • session: the object that encapsulates the user session;
  • application: an object that encapsulates the server's operating environment;
  • out: the output stream object that outputs the server response;
  • config: the configuration object of the web application;
  • page: JSP page itself (equivalent to this in Java program);
  • exception: The object that encapsulates the exception thrown by the page.

66. Tell me about the 4 scopes of JSP?

  • page: Represents objects and properties associated with a page.
  • request: Represents objects and properties related to a request made by the client. A request may span multiple pages and involve multiple Web components; temporary data that needs to be displayed on the page can be placed in this scope.
  • session: Represents objects and attributes related to a session established between a user and the server. Data related to a user should be placed in the user's own session.
  • application: Represents objects and properties related to the entire Web application, which is essentially a global scope that spans the entire Web application, including multiple pages, requests, and sessions.

67. What is the difference between session and cookie?

  • The storage location is different: the session is stored on the server side; the cookie is stored on the browser side.
  • Different security: cookie security is general, stored in the browser, can be forged and modified.
  • Capacity and number limit: There is a capacity limit for cookies, and there is also a limit for the number of cookies under each site.
  • Diversity of storage: sessions can be stored in Redis, databases, and applications; cookies can only be stored in browsers.

68. Tell me about the working principle of session?

The working principle of the session is that after the client login is completed, the server will create a corresponding session. After the session is created, the session id will be sent to the client, and the client will store it in the browser. In this way, every time the client accesses the server, it will bring the sessionid with it. After the server gets the sessionid, it will find the corresponding session in the memory, so that it can work normally.

69. If the client prohibits cookies, can the session still be used?

It can be used, the session only relies on the cookie to store the sessionid, if the cookie is disabled, you can use the method of adding the sessionid to the url to ensure that the session can be used normally.

70. What is the difference between spring mvc and struts?

  • Interception level: struts2 is class-level interception; spring mvc is method-level interception.
  • Data independence: The methods of spring mvc are basically independent, exclusive request and response data, the request data is obtained through parameters, the processing results are returned to the framework through ModelMap, and variables are not shared between methods; while struts2 although methods It is also independent, but all its action variables are shared, which will not affect the running of the program, but it brings us some trouble when coding and reading the program.
  • Interception mechanism: struts2 has its own interceptor mechanism, and spring mvc uses an independent aop method, which leads to a larger configuration file volume of struts2 than spring mvc.
  • Support for ajax: spring mvc integrates ajax, all ajax is very convenient to use, only one annotation @ResponseBody is needed; while struts2 generally needs to install plug-ins or write code by itself.

71. How to avoid SQL injection?

  • Use preprocessing PreparedStatement.
  • Use regular expressions to filter out special characters in characters.

72. What is an XSS attack and how to avoid it?

XSS attack: Cross-site scripting attack, which is a common vulnerability in Web programs. The principle is that attackers insert malicious script codes (css codes, Javascript codes, etc.) Cookies, breaking page structure, redirecting to other sites, etc.

The core of preventing XSS is to filter the input data.

73. What is a CSRF attack and how to avoid it?

CSRF: Cross-Site Request Forgery (Chinese: Cross-Site Request Forgery), it can be understood that the attacker has stolen your identity and sent malicious requests in your name, such as: sending emails, sending messages, purchasing goods in your name, virtual Money transfer, etc.

Defense means:

  • Verify the source address of the request;
  • Key operations add verification codes;
  • Add token to the request address and verify it.

Seven. Abnormal

74. What is the difference between throw and throws?

  • Throw: is to actually throw an exception.
  • throws: is the declaration that an exception may be thrown.

75. What is the difference between final, finally, and finalize?

  • final: It is a modifier. If the class is modified, this class cannot be inherited; if the method and variable are modified, it means that this method and this variable cannot be changed, but can only be used.
  • finally: It is the last part of try{} catch{} finally{}, which means that it will be executed no matter what happens. The finally part can be omitted, but if the finally part exists, the code in finally will be executed.
  • finalize: It is a method of the Object class, and this method of the reclaimed object will be called when the garbage collector is executed.

76. Which part of try-catch-finally can be omitted?

try-catch-finally Both catch and finally can be omitted, but not at the same time, that is to say, when there is try, it must be followed by a catch or finally.

77. In try-catch-finally, if there is a return in the catch, will finally still be executed?

finally will be executed, even if it is return in catch, the return in catch will wait until the code in finally is executed before it will be executed.

78. What are the common exception classes?

  • NullPointerException null pointer exception
  • ClassNotFoundException The specified class does not exist
  • NumberFormatException string to number exception
  • IndexOutOfBoundsException Array subscript out of bounds exception
  • ClassCastException data type conversion exception
  • FileNotFoundException file not found exception
  • NoSuchMethodException Method does not exist exception
  • IOException IO exception
  • SocketException Socket exception

8. Network

79. What do the http response codes 301 and 302 represent? What's the difference?

  • 301: Permanent redirect.
  • 302: Temporary redirect.

The difference between them is that 301 is more beneficial to search engine optimization (SEO); 302 has the risk of being prompted as network blocking.

80. What is the difference between forward and redirect?

forward is to forward and redirect is to redirect:

  • The url in the address bar shows: the foward url will not change, but the redirect url will change;
  • Data sharing: forward can share the data in the request, but redirect cannot;
  • Efficiency: forward is more efficient than redirect.

81. Briefly describe the difference between tcp and udp?

tcp and udp are protocols in the transport layer of the OSI model. tcp provides reliable communication transport, while udp is often used to allow broadcast and detail control to application communication transport.

The difference between the two is roughly as follows:

  • tcp is connection-oriented, and udp is non-connection-oriented, that is, no connection is required before sending data;

  • tcp provides reliable service (data transmission), udp cannot guarantee;

  • tcp is byte-oriented, udp is packet-oriented;

  • tcp data transmission is slow, udp data transmission is fast;

82. Why does tcp need to shake hands three times, can't it be done twice? Why?

If two handshakes are used, the connection will be established as long as the server sends a confirmation packet, but since the client does not respond to the server's request at this time, the server will always wait for the client at this time, so the server will be wasted certain resources. If the three-way handshake is used, the server will know that the client does not request to establish a request if it does not receive a confirmation from the client, and the resources of the server will not be wasted.

83. Tell me how the tcp sticky packet is generated?

The tcp sticky packet may occur at the sending end or the receiving end. Let’s look at the causes of sticky packets at both ends:

  • Sticky packets at the sender: the sender needs to wait for the buffer to be full before sending out, resulting in sticky packets;
  • Sticky packets at the receiver: The receiver does not receive the buffered packets in time, resulting in multiple packets being received.

84. What are the seven-layer models of OSI?

  • Physical layer: use the transmission medium to provide a physical connection for the data link layer, and realize the transparent transmission of the bit stream.
  • Data Link Layer: Responsible for establishing and managing links between nodes.
  • Network layer: Through the routing selection algorithm, select the most appropriate path for the message or packet to pass through the communication subnet.
  • Transport layer: Provide users with reliable end-to-end error and flow control to ensure the correct transmission of messages.
  • Session layer: Provides methods for establishing and using connections to the presentation layers of two entities.
  • Presentation layer: Deal with the representation of user information, such as encoding, data format conversion, encryption and decryption, etc.
  • Application layer: Provide services directly to users and complete various tasks that users want to complete on the network.

85. What is the difference between get and post requests?

  • The get request will be actively cached by the browser, but the post will not.
  • There is a size limit for get passing parameters, but not for post.
  • The transmission of post parameters is more secure. The parameters of get will be limited to the url in plain text, but the parameters of post will not.

86. How to achieve cross domain?

There are several options for implementing cross-domain:

  • The server-side running cross-domain setting CORS is equal to *;
  • Use the annotation @CrossOrigin to run cross-domain on a single interface;
  • Use jsonp cross-domain;

87. Tell me about the implementation principle of JSONP?

jsonp: JSON with Padding, which uses the src connection of the script tag to access the characteristics of different sources, and loads the "JS function" returned by the remote to execute.

Nine. Design pattern

88. Tell me about the design patterns you are familiar with?

  • Singleton mode: Guaranteed to be created once, saving system overhead.
  • Factory pattern (simple factory, abstract factory): decoupled code.
  • Observer pattern: defines one-to-many dependencies between objects, so that when an object changes, all its dependents will be notified and updated automatically.
  • Appearance mode: Provide a unified interface to access a group of interfaces in the subsystem. The appearance defines a high-level interface to make the subsystem easier to use.
  • Template method mode: defines the skeleton of an algorithm, and defers some steps to subclasses. The template method allows subclasses to redefine the steps of the algorithm without changing the structure of the algorithm.
  • State Pattern: Allows an object to change its behavior when its internal state changes, the object appears as if its class has been modified.

89. What is the difference between simple factory and abstract factory?

  • Simple factory: It is used to produce any product in the same hierarchical structure, and it cannot do anything about adding new products.
  • Factory method: used to produce fixed products in the same hierarchical structure, and supports adding arbitrary products.
  • Abstract factory: It is used to produce all products of different product families, and it is powerless to add new products; it supports the addition of product families.

十. Spring/Spring MVC

90. Why use spring?

  • Spring provides ioc technology, and the container will help you manage dependent objects, so that you don't need to create and manage dependent objects yourself, and it is easier to achieve program decoupling.
  • Spring provides transaction support, making transaction operations more convenient.
  • Spring provides slice-oriented programming, which makes it easier to deal with a certain type of problem.
  • More convenient framework integration, spring can easily integrate other frameworks, such as MyBatis, hibernate, etc.

91. Explain what is aop?

AOP is a technology for aspect-oriented programming, which realizes the unified maintenance of program functions through pre-compilation and runtime dynamic proxy.

To put it simply, it is the programming idea of ​​unified processing of a certain "cutting face" (category), such as unified processing of logs and exceptions.

92. Explain what is ioc?

ioc: Inversion of Control (Chinese: Inversion of Control) is the core of spring. For the spring framework, spring is responsible for controlling the life cycle of objects and the relationship between objects.

In simple terms, control refers to the current object's control over internal members; inversion of control means that this control is not managed by the current object, but by other (classes, third-party containers) to manage.

93. What are the main modules of spring?

  • spring core: The most basic part of the framework, providing ioc and dependency injection features.
  • spring context: The context package built on the basis of the core package provides a framework-style object access method.
  • spring dao: Data Access Object provides an abstraction layer of JDBC.
  • spring aop: Provides an aspect-oriented programming implementation, allowing you to customize interceptors, point cuts, etc.
  • spring Web: Provides integrated features for Web development, such as file upload, ioc container initialization using servlet listeners and ApplicationContext for Web.
  • spring Web mvc: The mvc package in spring provides the implementation of Model-View-Controller (MVC) for Web applications.

94. What are the commonly used injection methods in spring?

  • setter property injection
  • constructor injection
  • Annotation injection

95. Are beans in spring thread-safe?

The bean in spring defaults to the singleton mode, and the spring framework does not perform multi-threaded encapsulation processing on the singleton bean.

In fact, most of the time, spring beans are stateless (such as dao class), and all beans are also safe to some extent, but if the bean is stateful (such as view model objects), it is up to the developer to ensure thread safety. Yes, the easiest way is to change the scope of the bean, change "singleton" to "prototype", so that the requested bean is equivalent to new Bean(), so thread safety can be guaranteed.

  • To be stateful is to have a data storage function.
  • Stateless means no data is saved.

96. How many bean scopes does spring support?

Spring supports 5 scopes, as follows:

  • singleton: There is only one bean instance in the spring ioc container, and the bean exists in singleton mode, which is the default value of the system;

  • prototype: A new instance is created every time a bean is called from the container, that is, every time getBean() is equivalent to executing the new Bean() operation;

  • Scope in the web environment:

  • request: A bean is created for each http request;

  • session: the same http session shares a bean instance;

  • global-session: used for portlet container, because each portlet has a separate session, globalsession provides a global http session.

"Note:" The use of prototype scope requires careful consideration, because frequent creation and destruction of beans will bring a lot of performance overhead.

97. What are the ways to automatically assemble beans in spring?

  • no: Default value, means no autowiring, explicit bean reference should be used for wiring.
  • byName: It injects object dependencies based on the name of the bean.
  • byType: It injects object dependencies based on type.
  • Constructor: To inject dependencies through a constructor, a large number of parameters need to be set.
  • autodetect: The container is first assembled using autowire via the constructor, and if not, via byType.

98. What are the implementation methods of spring transactions?

  • 声明式事务:声明式事务也有两种实现方式,基于 xml 配置文件的方式和注解方式(在类上添加 @Transaction 注解)。
  • 编码方式:提供编码的形式管理和维护事务。

99. 说一下 spring 的事务隔离?

spring 有五大隔离级别,默认值为 ISOLATION_DEFAULT(使用数据库的设置),其他四个隔离级别和数据库的隔离级别一致:

  • ISOLATION_DEFAULT:用底层数据库的设置隔离级别,数据库设置的是什么我就用什么;

  • ISOLATION_READ_UNCOMMITTED:未提交读,最低隔离级别、事务未提交前,就可被其他事务读取(会出现幻读、脏读、不可重复读);

  • ISOLATION_READ_COMMITTED:提交读,一个事务提交后才能被其他事务读取到(会造成幻读、不可重复读),SQL server 的默认级别;

  • ISOLATION_REPEATABLEREAD:可重复读,保证多次读取同一个数据时,其值都和事务开始时候的内容是一致,禁止读取到别的事务未提交的数据(会造成幻读),MySQL 的默认级别;

  • ISOLATION_SERIALIZABLE:序列化,代价最高最可靠的隔离级别,该隔离级别能防止脏读、不可重复读、幻读。

「脏读」 :表示一个事务能够读取另一个事务中还未提交的数据。比如,某个事务尝试插入记录 A,此时该事务还未提交,然后另一个事务尝试读取到了记录 A。

「不可重复读」 :是指在一个事务内,多次读同一数据。

「幻读」 :指同一个事务内多次查询返回的结果集不一样。比如同一个事务 A 第一次查询时候有 n 条记录,但是第二次同等条件下查询却有 n+1 条记录,这就好像产生了幻觉。发生幻读的原因也是另外一个事务新增或者删除或者修改了第一个事务结果集里面的数据,同一个记录的数据内容被修改了,所有数据行的记录就变多或者变少了。

100. Tell me about the running process of spring mvc?

  • spring mvc first sends the request to DispatcherServlet.
  • DispatcherServlet queries one or more HandlerMappings to find the Controller that handles the request.
  • DispatcherServlet then submits the request to the corresponding Controller.
  • After the Controller performs business logic processing, it will return a ModelAndView.
  • Dispathcher queries one or more ViewResolver view resolvers to find the view object specified by the ModelAndView object.
  • The view object is responsible for rendering back to the client.

101. What are the components of spring mvc?

  • Pre-controller DispatcherServlet.
  • Mapping controller HandlerMapping.
  • Processor Controller.
  • Model and View ModelAndView.
  • View resolver ViewResolver.

102. What is the role of @RequestMapping?

Map http requests to corresponding classes/methods.

103. What is the role of @Autowired?

@Autowired It can annotate class member variables, methods and constructors, complete the work of automatic assembly, and eliminate the set/get method through the use of @Autowired.

11. Spring Boot/Spring Cloud

104. What is spring boot?

 spring boot 是为 spring 服务的,是用来简化新 spring 应用的初始搭建以及开发过程的。

105. Why use spring boot?

  • Simple configuration
  • Operate independently
  • automatic assembly
  • No code generation and xml configuration
  • Provide application monitoring
  • easy to use
  • Improve development efficiency

106. What is the core configuration file of spring boot?

Two configuration files of spring boot core:

  • bootstrap (.yml or .properties): boostrap is loaded by the parent ApplicationContext, which is loaded before applicationton, and the properties in boostrap cannot be overwritten;
  • application (.yml or .properties): for automatic configuration of spring boot projects.

107. What are the types of spring boot configuration files? What's the difference?

Configuration files have .properties format and .yml format, the main difference between them is the calligraphy style.

The .properties configuration is as follows:

spring.RabbitMQ.port=5672

The .yml configuration is as follows:

spring:
    RabbitMQ:
        port: 5672

The yml format does not support @PropertySource annotation import.

108. What are the ways of spring boot to achieve hot deployment?

  • Use devtools to start hot deployment, add devtools library, and set spring. devtools. restart. enabled to true in the configuration file;
  • Use the Intellij Idea editor, tick automatic compilation or manual recompilation.

109. What is the difference between jpa and hibernate?

The full name of jpa is Java Persistence API, which is the Java persistence interface specification, and hibernate belongs to the specific implementation of jpa.

110. What is spring cloud?

Spring cloud is an ordered collection of a series of frameworks. It uses the development convenience of spring boot to subtly simplify the development of distributed system infrastructure, such as service discovery registration, configuration center, message bus, load balancing, circuit breaker, data monitoring, etc., can be done with the development style of spring boot to one-click launch and deployment.

111. What is the function of spring cloud circuit breaker?

In a distributed architecture, the role of the circuit breaker mode is similar. When a service unit fails (similar to a short circuit in an electrical appliance), an error response is returned to the caller through the fault monitoring of the circuit breaker (similar to a blown fuse). , rather than a long wait. In this way, the thread will not be occupied for a long time due to calling the faulty service and will not be released, avoiding the spread of faults in the distributed system.

112. What are the core components of spring cloud?

  • Eureka: Services are registered for discovery.
  • Feign: Based on the dynamic proxy mechanism, according to the annotation and the selected machine, splice the request url address and initiate the request.
  • Ribbon: To achieve load balancing, select one of multiple machines for a service.
  • Hystrix: Provides thread pools, different services use different thread pools, realizes the isolation of different service calls, and avoids the problem of service avalanche.
  • Zuul: gateway management, the Zuul gateway forwards the request to the corresponding service.

12. Hibernate

113. Why use hibernate?

  • hibernate is the encapsulation of jdbc, which greatly simplifies the tedious and repetitive code of the data access layer.
  • hibernate is an excellent ORM implementation, which simplifies the coding function of the DAO layer to a large extent.
  • Can carry on the transplantation work of the database very conveniently.
  • A caching mechanism is provided, which is efficient for program execution changes.

114. What is an ORM framework?

ORM (Object Relation Mapping) object-relational mapping is to map relational data in the database into objects in the program.

Advantages of using ORM: improved development efficiency, reduced development costs, simpler and more object-oriented development, and stronger portability.

115. How to view the printed SQL statement on the console in hibernate?

Just set hibernate. show_SQL to true in Config. However, it is not recommended to enable it, as it will reduce the operating efficiency of the program.

116. How many query methods does hibernate have?

Three types: hql, native SQL, and conditional query Criteria.

117. Can hibernate entity class be defined as final?

The entity class can be defined as a final class, but in this case, the delayed association in hibernate proxy mode cannot be used to provide performance, so it is not recommended to define the entity class as final.

118. What is the difference between using Integer and int for mapping in hibernate?

The Integer type is an object, and its value is allowed to be null, while int is a basic data type, and its value cannot be null.

119. How does hibernate work?

  • Read and parse configuration files.
  • Read and parse the mapping file to create a SessionFactory.
  • Open Session.
  • Create a transaction.
  • Perform persistence operations.
  • Commit the transaction.
  • Close the session.
  • Close the SessionFactory.

120. What is the difference between get() and load()?

  • When querying data, if there is no object specified by OID, get() returns null; load() returns a proxy object.
  • load() supports lazy loading; get() does not support lazy loading.

121. Tell me about the caching mechanism of hibernate?

Hibernate commonly used caches include first-level cache and second-level cache:

Level 1 cache: also called Session cache, which is only valid within the scope of the Session and does not require user intervention. It is maintained by hibernate itself and can be cleared by: evict(object); clear() clears all caches in the level 1 cache ;flush() flush out the cache;

Second-level cache: application-level cache, valid in all sessions, supports configuration of third-party caches, such as: EhCache.

122. What are the states of hibernate objects?

  • Temporary/transient state: The object that is directly new, the object has not been persisted (not saved in the database), and is not managed by the Session.
  • Persistence state: When the methods such as save/saveOrupdate/get/load/list of Session are called, the object is in the persistent state.
  • Free state: After the Session is closed, the object is in the free state.

123. What is the difference between getCurrentSession and openSession in hibernate?

  • getCurrentSession will bind the current thread, but openSession will not.

  • The getCurrentSession transaction is controlled by Spring and does not need to be closed manually, while openSession requires us to manually open and commit the transaction ourselves.

124. Do hibernate entity classes have to have a parameterless constructor? Why?

Each entity class in hibernate must provide a no-argument constructor, because the hibernate framework uses the reflection api to create an instance of the entity class by calling ClassnewInstance(). If there is no no-argument constructor, an exception will be thrown.

Thirteen. MyBatis

125. MyBatis 中 #{}和 ${}的区别是什么?

#{}是预编译处理,${}是字符替换。在使用 #{}时,MyBatis 会将 SQL 中的 #{}替换成“?”,配合 PreparedStatement 的 set 方法赋值,这样可以有效的防止 SQL 注入,保证程序的运行安全。

126. MyBatis 有几种分页方式?

分页方式:逻辑分页和物理分页。

「逻辑分页:」 使用 MyBatis 自带的 RowBounds 进行分页,它是一次性查询很多数据,然后在数据中再进行检索。

「物理分页:」 自己手写 SQL 分页或使用分页插件 PageHelper,去数据库查询指定条数的分页数据的形式。

127. RowBounds 是一次性查询全部结果吗?为什么?

RowBounds 表面是在“所有”数据中检索数据,其实并非是一次性查询出所有数据,因为 MyBatis 是对 jdbc 的封装,在 jdbc 驱动中有一个 Fetch Size 的配置,它规定了每次最多从数据库查询多少条数据,假如你要查询更多数据,它会在你执行 next()的时候,去查询更多的数据。就好比你去自动取款机取 10000 元,但取款机每次最多能取 2500 元,所以你要取 4 次才能把钱取完。只是对于 jdbc 来说,当你调用 next()的时候会自动帮你完成查询工作。这样做的好处可以有效的防止内存溢出。

128. MyBatis 逻辑分页和物理分页的区别是什么?

  • 逻辑分页是一次性查询很多数据,然后再在结果中检索分页的数据。这样做弊端是需要消耗大量的内存、有内存溢出的风险、对数据库压力较大。
  • 物理分页是从数据库查询指定条数的数据,弥补了一次性全部查出的所有数据的种种缺点,比如需要大量的内存,对数据库查询压力较大等问题。

129. MyBatis 是否支持延迟加载?延迟加载的原理是什么?

MyBatis 支持延迟加载,设置 lazyLoadingEnabled=true 即可。

延迟加载的原理的是调用的时候触发加载,而不是在初始化的时候就加载信息。比如调用 a. getB(). getName(),这个时候发现 a. getB() 的值为 null,此时会单独触发事先保存好的关联 B 对象的 SQL,先查询出来 B,然后再调用 a. setB(b),而这时候再调用 a. getB(). getName() 就有值了,这就是延迟加载的基本原理。

130. 说一下 MyBatis 的一级缓存和二级缓存?

  • 一级缓存:基于 PerpetualCache 的 HashMap 本地缓存,它的声明周期是和 SQLSession 一致的,有多个 SQLSession 或者分布式的环境中数据库操作,可能会出现脏数据。当 Session flush 或 close 之后,该 Session 中的所有 Cache 就将清空,默认一级缓存是开启的。

  • 二级缓存:也是基于 PerpetualCache 的 HashMap 本地缓存,不同在于其存储作用域为 Mapper 级别的,如果多个SQLSession之间需要共享缓存,则需要使用到二级缓存,并且二级缓存可自定义存储源,如 Ehcache。默认不打开二级缓存,要开启二级缓存,使用二级缓存属性类需要实现 Serializable 序列化接口(可用来保存对象的状态)。

开启二级缓存数据查询流程:二级缓存 -> 一级缓存 -> 数据库。

缓存更新机制:当某一个作用域(一级缓存 Session/二级缓存 Mapper)进行了C/U/D 操作后,默认该作用域下所有 select 中的缓存将被 clear。

131. MyBatis 和 hibernate 的区别有哪些?

  • 灵活性:MyBatis 更加灵活,自己可以写 SQL 语句,使用起来比较方便。
  • 可移植性:MyBatis 有很多自己写的 SQL,因为每个数据库的 SQL 可以不相同,所以可移植性比较差。
  • Learning and usage threshold: MyBatis is relatively simple to get started, and the usage threshold is also lower.
  • Second-level cache: hibernate has a better second-level cache, and its second-level cache can be replaced by a third-party second-level cache.

132. What Executors does MyBatis have?

MyBatis has three basic Executors:

  • SimpleExecutor: Open a Statement object every time update or select is executed, and close the Statement object immediately when it is used up;
  • ReuseExecutor: Execute update or select, use SQL as the key to find the Statement object, use it if it exists, create it if it does not exist, do not close the Statement object after use, but place it in the Map for next use. In short, it is to reuse the Statement object;
  • BatchExecutor: Execute update (no select, jdbc batch processing does not support select), add all SQL to the batch processing (addBatch()), wait for unified execution (executeBatch()), it caches multiple Statement objects, each Statement objects wait for executeBatch() batch processing to be executed one by one after addBatch() is completed, which is the same as jdbc batch processing.

133. What is the implementation principle of the MyBatis pagination plugin?

The basic principle of the paging plug-in is to use the plug-in interface provided by MyBatis to implement a custom plug-in, intercept the SQL to be executed in the plug-in interception method, then rewrite the SQL, and add the corresponding physical paging statement and physical paging parameters according to the dialect dialect.

134. How does MyBatis write a custom plugin?

"Principle of custom plug-in implementation"

The MyBatis custom plug-in intercepts the four MyBatis objects (Executor, StatementHandler, ParameterHandler, ResultSetHandler):

  • Executor: intercepts the internal executor, which is responsible for calling StatementHandler to operate the database, and automatically maps the result set through ResultSetHandler, and it also handles the operation of the second-level cache;

  • StatementHandler: Intercepts the processing of SQL syntax construction. It is the object that MyBatis directly executes SQL scripts with the database. In addition, it also implements the first-level cache of MyBatis;

  • ParameterHandler: Intercept parameter processing;

  • ResultSetHandler: Intercept the processing of the result set.

"The key to custom plug-in implementation"

The MyBatis plug-in needs to implement the Interceptor interface. The methods contained in the interface are as follows:

public interfaceInterceptor{
    
       
   Object intercept(Invocation invocation)throws Throwable;       
   Object plugin(Object target);    
   voidsetProperties(Properties properties);
}
  • The setProperties method is to configure custom related properties when MyBatis configures the plug-in, that is: the parameter configuration of the interface implementation object;
  • The plugin method is used by the plug-in to encapsulate the target object. Through this method, we can return the target object itself, or return a proxy of it. We can decide whether to intercept and then decide what kind of target object to return. The official provides an example : return Plugin. wrap(target, this);
  • The intercept method is the method to be executed when interception is to be performed.

"Custom plugin implementation example"

Official plugin implementation:

@Intercepts({
    
    @Signature(type = Executor.class, method= "query",
        args = {
    
    MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})})
publicclassTestInterceptorimplementsInterceptor{
    
    
   public Object intercept(Invocation invocation)throws Throwable {
    
    
     Object target = invocation.getTarget(); //被代理对象
     Method method = invocation.getMethod(); //代理方法
     Object[] args = invocation.getArgs(); //方法参数
     // do something . . . . . .  方法拦截前执行代码块
     Object result = invocation.proceed();
     // do something . . . . . . . 方法拦截后执行代码块
     return result;
   }
   public Object plugin(Object target){
    
    
     return Plugin.wrap(target, this);
   }
}

14. RabbitMQ

135. What are the usage scenarios of RabbitMQ?

  • Panic buying activities, shaving peaks and filling valleys, to prevent the system from collapsing.
  • Delay information processing, such as sending email reminders to users who have placed orders but have not paid after 10 minutes.
  • Decoupling the system, you can write module extensions separately for new functions. For example, after the user confirms the evaluation, the function of returning points to the user is added. At this time, there is no need to add the function of adding new points to the business code. The integral interface subscribes to the message queue for confirming the evaluation. To add any functions later, you only need to subscribe to the corresponding message queue.

136. What are the important roles of RabbitMQ?

Important roles in RabbitMQ are: producers, consumers and agents:

  • Producer: the creator of the message, responsible for creating and pushing data to the message server;
  • Consumer: the receiver of the message, used to process data and confirm the message;
  • Agent: It is RabbitMQ itself, which is used to play the role of "express delivery". It does not produce messages itself, but only plays the role of "express delivery".

137. What are the important components of RabbitMQ?

  • ConnectionFactory (connection manager): The manager for establishing a connection between the application and Rabbit, used in the program code.
  • Channel: The channel used for message push.
  • Exchange (exchange): used to receive and distribute messages.
  • Queue (queue): used to store the producer's message.
  • RoutingKey (routing key): used to distribute the generator's data to the switch.
  • BindingKey (binding key): used to bind the message of the exchange to the queue.

138. What is the role of vhost in RabbitMQ?

vhost: Each RabbitMQ can create many vhosts, which we call virtual hosts. Each virtual host is actually a mini version of RabbitMQ, which has its own queues, switches and bindings, and has its own permission mechanism.

139. How are RabbitMQ messages sent?

First, the client must connect to the RabbitMQ server to publish and consume messages. A tcp connection will be created between the client and the rabbit server. Once the tcp is opened and passed the authentication (authentication is the username and password you send to the rabbit server), your The client and RabbitMQ create an amqp channel (channel). The channel is a virtual connection created on the "real" tcp. Amqp commands are sent out through the channel. Each channel will have a unique id, whether it is published Messages and subscription queues are all done through this channel.

140. How does RabbitMQ ensure the stability of messages?

  • Provides transaction functionality.
  • By setting the channel to confirm mode.

141. How does RabbitMQ avoid message loss?

  • The message is persisted to the disk to ensure that the message will not be lost when the server restarts.
  • There is at least one physical disk in each cluster, and messages are guaranteed to drop to disk.

142. What are the conditions to ensure the success of message persistence?

  • The declared queue must set persistent durable to true.

  • The message push delivery mode must be set to persistent, and the deliveryMode is set to 2 (persistent).

  • The message has arrived at the persistent exchange.

  • The message has arrived on the persistent queue.

The above four conditions are met to ensure the success of message persistence.

143. What are the disadvantages of RabbitMQ persistence?

The disadvantage of persistence is that it reduces the throughput of the server because disk is used instead of memory storage, which reduces throughput. You can try to use ssd hard disk to alleviate the throughput problem.

144. How many broadcast types does RabbitMQ have?

  • direct (default mode): The most basic and simplest mode, the sender sends the message to the subscriber, and if there are multiple subscribers, the message is sent by polling by default.
  • headers: Similar to direct, but the performance is very poor, this type is hardly used.
  • fanout: distribution mode, distribute consumption to all subscribers.
  • topic: match the subscription mode, use the regular pattern to match to the message queue, and all the matches can be received.

145. How does RabbitMQ implement a delayed message queue?

There are two ways to implement the delay queue:

  • After the message expires, it enters the dead letter exchange, and then forwards it to the delayed consumption queue by the exchange to realize the delay function;
  • Use the RabbitMQ-delayed-message-exchange plugin to implement the delayed function.

146. What is the use of RabbitMQ cluster?

Clusters serve two main purposes:

  • High availability: if a server has a problem, the entire RabbitMQ can continue to be used;
  • High capacity: the cluster can carry more messages.

147. What are the types of RabbitMQ nodes?

  • Disk node: Messages are stored to disk.
  • Memory nodes: All messages are stored in memory, and the messages will be lost after restarting the server. The performance is higher than that of the disk type.

148. What issues should be paid attention to when building a RabbitMQ cluster?

  • Use "-link" connection between each node, this property can not be ignored.
  • The erlang cookie value used by each node must be the same, and this value is equivalent to the function of "secret key", which is used for authentication of each node.
  • There must be one disk node in the entire cluster.

149. Is each node of RabbitMQ a complete copy of other nodes? Why?

No, for two reasons:

  • Consideration of storage space: If each node has a complete copy of all queues, the new node will not only increase the storage space, but will add more redundant data;
  • Performance considerations: If each message needs to be completely copied to each cluster node, then the new node does not improve the ability to process messages, at most it will maintain the same performance as a single node or even worse.

150. What happens if the only disk node in the RabbitMQ cluster crashes?

If the disk node with the only disk crashes, the following operations cannot be performed:

  • Can't create queue

  • Can't create switch

  • Could not create binding

  • Can't add user

  • Can't change permissions

  • Cannot add and remove cluster nodes

If the only disk node crashes, the cluster can keep running, but you can't change anything.

151. Does RabbitMQ have any requirements for the stop order of cluster nodes?

RabbitMQ has requirements for the order in which the cluster is stopped. The memory nodes should be shut down first, and then the disk nodes should be shut down last. If the order is just the opposite, it may cause the loss of messages.

15. Kafka

152. Can kafka be used independently of zookeeper? Why?

Kafka cannot be used alone without zookeeper, because kafka uses zookeeper to manage and coordinate kafka's node servers.

153. How many data retention strategies does kafka have?

Kafka has two data storage strategies: retention according to expiration time and retention according to the size of stored messages.

154. Kafka is set to clear data for 7 days and 10G at the same time. By the fifth day, the message reached 10G. How will Kafka handle it at this time?

At this time, kafka will perform data clearing work, and the data will be cleared regardless of the time and size that meet the conditions.

155. What will cause kafka to run slowly?

  • cpu performance bottleneck
  • Disk read and write bottleneck
  • network bottleneck

156. What should be paid attention to when using Kafka cluster?

  • The number of clusters is not as many as possible, preferably not more than 7, because the more nodes, the longer it takes for message replication, and the lower the throughput of the entire group.
  • The number of clusters is preferably odd, because more than half of the faulty clusters cannot be used, and setting it to an odd number has a higher fault tolerance rate.

16. Zookeeper

157. What is zookeeper?

zookeeper is a distributed, open source distributed application coordination service, an open source implementation of google chubby, and an important component of hadoop and hbase. It is a software that provides consistent services for distributed applications. Its functions include: configuration maintenance, domain name service, distributed synchronization, group service, etc.

158. What functions does zookeeper have?

  • Cluster management: monitor node survival status, running requests, etc.
  • Master node election: After the master node hangs up, a new round of master election can be started from the standby node. The master node election refers to the election process, and zookeeper can assist in completing this process.
  • Distributed locks: zookeeper provides two types of locks: exclusive locks and shared locks. An exclusive lock means that only one thread can use a resource at a time. A shared lock is shared by a read lock. Read-write mutual exclusion means that multiple threads can read the same resource at the same time. If you want to use a write lock, only one thread can use it. Zookeeper can control distributed locks.
  • Naming service: In a distributed system, by using the naming service, the client application can obtain information such as the address of the resource or service, the provider, etc. according to the specified name.

159. How many deployment modes does zookeeper have?

Zookeeper has three deployment modes:

  • Stand-alone deployment: run on a cluster;
  • Cluster deployment: running multiple clusters;
  • Pseudo-cluster deployment: A cluster starts multiple zookeeper instances to run.

160. How does zookeeper ensure the state synchronization of master and slave nodes?

The core of zookeeper is atomic broadcast, which ensures the synchronization between servers. The protocol that implements this mechanism is called the zab protocol. The zab protocol has two modes, recovery mode (master election) and broadcast mode (synchronization). When the service starts or after the leader crashes, zab enters the recovery mode. When the leader is elected and most servers complete the state synchronization with the leader, the recovery mode ends. State synchronization ensures that the leader and server have the same system state.

161. Why is there a master node in the cluster?

In a distributed environment, some business logic only needs to be executed by a certain machine in the cluster, and other machines can share the results, which can greatly reduce repeated calculations and improve performance, so the master node is needed.

162. There are 3 servers in the cluster, one of the nodes is down, can zookeeper still be used at this time?

It can continue to be used, and the singular server can continue to be used as long as no more than half of the servers are down.

163. Tell me about the notification mechanism of zookeeper?

The client will create a watcher event for a certain znode. When the znode changes, these clients will receive a notification from zookeeper, and then the client can make business changes according to the change of the znode.

Seventeen. MySQL

164. What are the three paradigms of the database?

  • The first normal form: The emphasis is on the atomicity of the column, that is, each column of the database table is an indivisible atomic data item.
  • Second normal form: The attributes of the entity are required to be completely dependent on the primary key. The so-called complete dependence means that there cannot be attributes that only depend on a part of the primary key.
  • Third Normal Form: Any non-key attribute does not depend on other non-key attributes.

165. There are a total of 7 pieces of data in an auto-increment table, delete the last 2 pieces of data, restart the MySQL database, and insert another piece of data, what is the id at this time?

  • If the table type is MyISAM, then the id is 8.

  • If the table type is InnoDB, the id is 6.

  • InnoDB tables only record the maximum id of the auto-increment primary key in memory, so the maximum id will be lost after restarting.

166. How to get the current database version?

Use select version() to get the current MySQL database version.

167. Tell me what is ACID?

  • Atomicity: All operations in a transaction are either completed or not completed, and will not end in a middle link. If an error occurs during the execution of the transaction, it will be restored (Rollback) to the state before the transaction started, as if the transaction had never been executed. That is, transactions are indivisible and irreducible.
  • Consistency (consistency): Before the transaction begins and after the transaction ends, the integrity of the database has not been violated. This means that written data must fully comply with all preset constraints, triggers, cascading rollbacks, etc.
  • Isolation: The ability of the database to allow multiple concurrent transactions to read, write and modify its data at the same time. Isolation can prevent data inconsistency caused by cross-execution when multiple transactions are executed concurrently. Transaction isolation is divided into different levels, including read uncommitted (Read uncommitted), read committed (read committed), repeatable read (repeatable read) and serialization (Serializable).
  • Durability (persistence): After the transaction processing ends, the modification to the data is permanent, even if the system fails, it will not be lost.

168. What is the difference between char and varchar?

  • "char(n)": fixed-length type, such as subscribing to char(10), when you enter the three characters "abc", they still occupy 10 bytes, and the other 7 bytes are empty bytes.
    Chat Advantages: High efficiency; Disadvantages: Occupies space; Applicable scenarios: Store the md5 value of the password, fixed length, using char is very suitable.

  • "varchar(n)": variable length, the stored value is the length of the byte occupied by each value plus a byte used to record its length.
    Therefore, it is more appropriate to consider varcahr in terms of space; it is more appropriate to consider char in terms of efficiency, and the use of the two requires a trade-off.

169. What is the difference between float and double?

  • float can store up to 8-digit decimal numbers and occupies 4 bytes in memory.

  • Double can store 16-bit decimal numbers at most, and occupies 8 bytes in memory.

170. What is the difference between inner join, left join and right join in MySQL?

Inner connection keyword: inner join; left connection: left join; right connection: right join.

The inner join is to display the matching associated data; the left join is to display all the tables on the left, and the table on the right shows the data that meets the conditions; the right join is just the opposite.

171. How is the MySQL index implemented?

An index is a data structure that satisfies a specific lookup algorithm, and these data structures point to data in a certain way, so as to achieve efficient lookup of data.

Specifically, the index in MySQL is implemented differently by different data engines, but the index of the current mainstream database engine is implemented by B+ tree. The search efficiency of B+ tree can reach the performance of dichotomy. After finding the data area, it can The complete data structure is found, and the performance of all indexes is better.

172. How to verify whether the MySQL index meets the requirements?

Use explain to see how SQL executes query statements, so as to analyze whether your index meets the requirements.

explain 语法:explain select * from table where type=1。

173. Tell me about the transaction isolation of the database?

MySQL's transaction isolation is added in the MySQL.ini configuration file, and added at the end of the file:

"transaction-isolation = REPEATABLE-READ
"

Available configuration values: READ-UNCOMMITTED, READ-COMMITTED, REPEATABLE-READ, SERIALIZABLE.

READ-UNCOMMITTED:未提交读,最低隔离级别、事务未提交前,就可被其他事务读取(会出现幻读、脏读、不可重复读)。
READ-COMMITTED:提交读,一个事务提交后才能被其他事务读取到(会造成幻读、不可重复读)。
REPEATABLE-READ:可重复读,默认级别,保证多次读取同一个数据时,其值都和事务开始时候的内容是一致,禁止读取到别的事务未提交的数据(会造成幻读)。
SERIALIZABLE:序列化,代价最高最可靠的隔离级别,该隔离级别能防止脏读、不可重复读、幻读。

"Dirty read" : Indicates that a transaction can read uncommitted data in another transaction. For example, a transaction tries to insert record A, and the transaction has not been committed at this time, and then another transaction tries to read record A.

"Non-repeatable read" : refers to reading the same data multiple times within a transaction.

"Phantom reading" : It means that the result sets returned by multiple queries in the same transaction are different. For example, the same transaction A has n records in the first query, but there are n+1 records in the second query under the same conditions, which seems to be an illusion. The reason for phantom reading is that another transaction adds or deletes or modifies the data in the result set of the first transaction. If the data content of the same record is modified, the records of all data rows will become more or less.

174. Tell me about the engines commonly used in MySQL?

  • InnoDB engine: the default database engine after mysql 5.1, which provides support for database acid transactions, and also provides row-level locks and foreign key constraints. Its design goal is to handle database systems with large data capacity. When MySQL is running, InnoDB will build a buffer pool in memory to buffer data and indexes. However, the engine does not support full-text search, and it starts relatively slowly. It does not save the number of rows in the table, so when the select count(*) from table command is executed, the entire table needs to be scanned. Due to the small granularity of the lock, the write operation will not lock the entire table, so using it in a scenario with a high degree of concurrency will improve efficiency.
  • MyIASM engine: does not provide transaction support, nor does it support row-level locks and foreign keys. Therefore, when executing insert and update statements, that is, when performing write operations, the table needs to be locked, so the efficiency will be reduced. However, unlike InnoDB, the MyIASM engine saves the number of rows in the table, so when the select count(*) from table statement is executed, the saved value can be directly read without scanning the entire table. Therefore, if the read operations of the table are far more than the write operations, and the support of transactions is not required, MyIASM can be used as the first choice of the database engine.

175. Tell me about MySQL's row locks and table locks?

MyISAM only supports table locks, InnoDB supports table locks and row locks, and the default is row locks.

  • Table-level locks: low overhead, fast locking, and no deadlocks. The locking granularity is large, the probability of lock conflicts is the highest, and the amount of concurrency is the lowest.
  • Row-level locks: high overhead, slow locking, and deadlocks. The lock strength is small, the probability of lock conflicts is small, and the concurrency is the highest.

176. Talk about optimistic locking and pessimistic locking?

  • Optimistic locking: Every time you go to get the data, you think that others will not modify it, so it will not be locked, but when you submit the update, you will judge whether others have updated the data during this period.

  • Pessimistic locking: Every time you go to get the data, you think that others will modify it, so every time you get the data, you will lock it, so that others will stop if they want to get the data until the lock is released.

The optimistic lock of the database needs to be implemented by yourself. Add a version field in the table, and add 1 to the successful value of each modification, so that each time you modify it, first compare whether the version you own is consistent with the current version of the database. Modify, so that optimistic locking is implemented.

177. What are the methods for troubleshooting MySQL problems?

  • Use the show processlist command to view all current connection information.
  • Use the explain command to query the execution plan of the SQL statement.
  • Enable the slow query log to view the SQL of the slow query.

178. How to optimize the performance of MySQL?

  • Create an index for the search field.
  • Avoid using select * to list the fields that need to be queried.
  • Split table vertically.
  • Choose the correct storage engine.

Eighteen. Redis

179. What is Redis? What are the usage scenarios?

Redis is a cache database developed in C language.

Redis usage scenarios:

  • Record the number of likes, clicks, and comments on posts;
    cache recent hot posts;
    cache article details;
    record user session information.

180. What are the functions of Redis?

  • Data caching function
  • The function of distributed lock
  • Support data persistence
  • Support business
  • Support message queue

181. What is the difference between Redis and memcache?

  • The storage methods are different: memcache stores all the data in the memory, and it will hang up after power failure, and the data cannot exceed the memory size; Redis stores part of it on the hard disk, which can ensure the persistence of the data.
  • Data support type: memcache supports relatively simple data types; Redis has complex data types.
  • The underlying models are different: the underlying implementation methods between them and the application protocol for communicating with the client are different. Redis has built a vm mechanism by itself, because if the general system calls system functions, it will waste a certain amount of time to move and request .
  • The size of value is different: Redis can reach a maximum of 512mb; memcache is only 1mb.

182. Why is Redis single-threaded?

Because cpu is not the bottleneck of Redis, the bottleneck of Redis is most likely to be machine memory or network bandwidth. Since single-threading is easy to implement, and the cpu will not become a bottleneck, it is logical to adopt a single-threaded solution.

Regarding the performance of Redis, the official website also has it. Ordinary notebooks can easily handle hundreds of thousands of requests per second.

And single thread does not mean that it is slow, nginx and nodejs are also representatives of high performance single thread.

183. What is cache penetration? How to deal with it?

  • Cache penetration: refers to the query of a data that must not exist. Since the cache is a miss, it needs to be queried from the database. If the data cannot be found, it will not be written into the cache. This will cause the non-existent data to go to the database every time it is requested. Query, resulting in cache penetration.

  • Solution: The most simple and crude method If the data returned by a query is empty (whether the data does not exist or the system fails), we will cache the empty result, but its expiration time will be very short, the longest is no more than five minutes.

184. What is cache avalanche? How to deal with it?

  • Cache avalanche: When the cache server restarts or a large number of caches fail in a certain period of time, when they fail, it will put a lot of pressure on the back-end system and cause the system to crash.
  • solution:
  1. After the cache expires, the number of threads that read the database and write the cache is controlled by adding locks or queues. For example, only one thread is allowed to query data and write cache for a certain key, while other threads wait;
  2. do secondary cache;
  3. For different keys, set different expiration times to make the cache invalidation time as uniform as possible;

185. What data types does Redis support?

Data types supported by Redis: string (string), list (list), hash (dictionary), set (set), zset (ordered set).

186. What are the Java clients supported by Redis?

Supported Java clients include Redisson, jedis, lettuce, etc.

187. What is the difference between jedis and Redisson?

  • jedis: Provides comprehensive support for Redis commands.
  • Redisson: It implements a distributed and scalable Java data structure. Compared with jedis, Redisson's functions are relatively simple, and it does not support Redis features such as sorting, transactions, pipelines, and partitions.

188. How to ensure the consistency of cache and database data?

  1. Knock out the cache

If the data is more complex, the cache update operation will become extremely complicated, so it is generally recommended to choose to eliminate the cache instead of updating the cache.

  1. Choose to eliminate the cache first, and then update the database

If the database is updated first, and then the cache is eliminated, if the elimination of the cache fails, subsequent requests will get dirty data until the cache expires.

If the cache is eliminated first and then the database is updated, if the database update fails, only one cache penetration will occur. In comparison, the latter has no essential impact on the business.

  1. Delayed double deletion strategy

The following scenario: At the same time, there is a request A for an update operation, and another request B for a query operation.

  1. Request A to perform a write operation and delete the cache
  2. Request B query found that the cache does not exist
  3. Request B to query the database to get the old value
  4. Request B to write the old value to the cache
  5. Request A to write the new value to the database

A data inconsistency problem arises. The delayed double-deletion strategy was adopted to solve the problem.

public void write(String key,Object data){
    
    
    redisUtils.del(key);
    db.update(data);
    Thread.Sleep(100);
    redisUtils.del(key);
}

By doing this, the cache dirty data generated within 1 second can be deleted again. This time setting can be adjusted according to the Russian business scenario.

  1. Scenarios where database reads and writes are separated

Two requests, one request A for update operation, the other request B for query operation.

  1. Request A to perform a write operation and delete the cache
  2. Request A to write data into the database,
  3. Request B query cache found that the cache has no value
  4. Request B to query from the slave library. At this time, the master-slave synchronization has not been completed, so the query is the old value
  5. Request B to write the old value to the cache
  6. The database completes the master-slave synchronization, and the slave library becomes the new value

The delayed double-deletion strategy is still used to solve this problem.

189. How many ways are there for Redis persistence?

  • There are two ways, or two strategies, for Redis persistence:

  • RDB (Redis Database): snapshot storage of your data can be performed at specified time intervals.

  • AOF (Append Only File): Every received write command is appended to the file through the write function.

190. How does Redis implement distributed locks?

Redis distributed locks actually occupy a "pit" in the system. When other programs also occupy the "pit", they can continue to execute if the occupation succeeds. If they fail, they can only give up or try again later.

Occupying the pit generally uses the setnx (set if not exists) instruction, which is only allowed to be occupied by one program, and calls del to release the lock after use.

//使用uuid,解决锁释放的问题
@GetMapping
public void testLock() throws InterruptedException {
    
    
    String uuid = UUID.randomUUID().toString();
    Boolean b_lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid, 10, TimeUnit.SECONDS);
    if(b_lock){
    
    
        Object value = redisTemplate.opsForValue().get("num");
        if(StringUtils.isEmpty(value)){
    
    
            return;
        }
        int num = Integer.parseInt(value + "");
        redisTemplate.opsForValue().set("num",++num);
        Object lockUUID = redisTemplate.opsForValue().get("lock");
        if(uuid.equals(lockUUID.toString())){
    
    
            redisTemplate.delete("lock");
        }
    }else{
    
    
        Thread.sleep(100);
        testLock();
    }
}

191. What are the defects of Redis distributed locks?

Redis distributed locks cannot solve the timeout problem. Distributed locks have a timeout period. If the execution of the program exceeds the timeout period of the lock, problems will occur.

192. How does Redis do memory optimization?

Try to use the hash table of Redis, and store relevant information in the hash table instead of storing each field separately, which can effectively reduce memory usage. For example, the user object of the web system should be put into the hash table and then stored in Redis as a whole, instead of setting keys for the user's name, age, password, email address and other fields for storage.

193. What are the Redis elimination strategies?

  • volatile-lru: Select the least recently used data from the data set (server.db[i].expires) with an expiration time set.
  • volatile-ttl: Select the data that is about to expire from the data set (server.db[i].expires) with an expiration time set.
  • volatile-random: Randomly select data elimination from the data set (server.db[i].expires) with an expiration time set.
  • allkeys-lru: Pick out the least recently used data from the dataset (server.db[i].dict).
  • allkeys-random: Randomly select data elimination from the dataset (server.db[i].dict).
  • no-enviction (eviction): Prohibits data eviction.

194. What are the common performance problems of Redis? How to solve it?

  • Writing memory snapshots by the main server will block the work of the main thread. When the snapshot is relatively large, it will have a great impact on performance, and the service will be suspended intermittently. Therefore, it is best not to write memory snapshots on the main server.
  • The performance problem of Redis master-slave replication. For the speed of master-slave replication and the stability of the connection, the master-slave library is best located in the same local area network.

19. JVM

195. Tell me about the main components of the JVM? and its role?

  • Class Loader (ClassLoader)

  • Runtime Data Area

  • Execution Engine

  • Native Interface

"The role of the component:" First, the Java code is converted into bytecode through the class loader (ClassLoader), and the runtime data area (Runtime Data Area) then loads the bytecode into the memory, and the bytecode file is just the JVM A set of instruction set specifications cannot be directly handed over to the underlying operating system for execution, so a specific command parser execution engine (Execution Engine) is required to translate bytecodes into underlying system instructions, and then hand them over to the CPU for execution. In this process, it is necessary to call the native library interface (Native Interface) of other languages ​​to realize the function of the whole program.

196. Tell me about the JVM runtime data area?

The runtime data area of ​​different virtual machines may be slightly different, but they all comply with the Java Virtual Machine Specification. The areas stipulated in the Java Virtual Machine Specification are divided into the following five parts:

  • Program Counter Register: The line number indicator of the bytecode executed by the current thread. The job of the bytecode parser is to change the value of this counter to select the next bytecode instruction to be executed, branch , loop, jump, exception handling, thread recovery and other basic functions all need to rely on this counter to complete;
  • Java Virtual Machine Stacks (Java Virtual Machine Stacks): used to store information such as local variable tables, operand stacks, dynamic links, and method exits;
  • Native Method Stack: It has the same function as the virtual machine stack, except that the virtual machine stack serves the Java method, while the native method stack serves for the virtual machine to call the Native method;
  • Java heap (Java Heap): The largest piece of memory in the Java virtual machine is shared by all threads, and almost all object instances allocate memory here;
  • Method area (Methed Area): Used to store data such as class information, constants, static variables, and just-in-time compiled code that have been loaded by the virtual machine.

197. Tell me about the difference between stacks?

  • In terms of function: the heap is used to store objects, and the stack is used to execute programs.
  • Sharing: The heap is shared by threads, and the stack is private to threads.
  • Space size: The heap size is much larger than the stack.

198. What are queues and stacks? What's the difference?

  • Both queues and stacks are used to pre-store data.

  • Queues allow elements to be retrieved first-in-first-out, but there are exceptions, and the Deque interface allows elements to be retrieved from both ends.

  • A stack is similar to a queue, but it performs last-in, first-out retrieval of elements.

199. What is the parental delegation model?

Before introducing the parent delegation model, let's talk about the class loader. For any class, the uniqueness in the JVM needs to be established by the class loader that loads it and the class itself. Each class loader has an independent class namespace. The class loader loads the class file into the JVM memory according to the specified fully qualified name, and then converts it into a class object.

Class loader classification:

  • Bootstrap ClassLoader, which is part of the virtual machine itself, is used to load the class library in the Java_HOME/lib/ directory, or in the path specified by the -Xbootclasspath parameter and recognized by the virtual machine;

  • Other class loaders:

  • Extension ClassLoader (Extension ClassLoader): Responsible for loading <java_home style="box-sizing: border-box; outline: 0px !important;"> libext directory or all class libraries in the path specified by the Java.ext.dirs system variable ;

  • Application class loader (Application ClassLoader). Responsible for loading the specified class library on the user classpath (classpath), we can use this class loader directly. In general, if we do not have a custom class loader, this loader is used by default.

Parental delegation model: If a class loader receives a class loading request, it will not load the class by itself first, but will delegate the request to the parent class loader to complete. This is the case for each class loader , so that all loading requests will be sent to the top-level startup class loader, and only when the parent loading cannot complete the loading request (it does not find the required class in its search scope), the child loader will try to load the class .

200. Tell me about the execution process of class loading?

Class loading is divided into the following 5 steps:

  • Loading: Find the corresponding class file according to the search path and import it;
  • Check: Check the correctness of the loaded class file;
  • Preparation: allocate memory space for static variables in the class;
  • Resolution: The virtual machine replaces symbolic references in the constant pool with direct references. A symbolic reference is understood as a mark, and a direct reference directly points to an address in memory;
  • Initialization: Perform initialization work on static variables and static code blocks.

201. How to judge whether the object can be recycled?

There are generally two ways to judge:

  • Reference counter: Create a reference count for each object. When there is an object reference, the counter is +1, and when the reference is released, the count is -1. When the counter is 0, it can be recycled. It has a disadvantage that it cannot solve the problem of circular references;
  • Reachability analysis: starting from GC Roots to search downwards, the path traveled by the search is called the reference chain. When an object does not have any reference chain connected to GC Roots, it proves that the object can be recycled.

202. What are the reference types in Java?

  • Strong reference: It will not be recycled when GC occurs.
  • Soft references: Objects that are useful but not necessary, and will be recycled before memory overflow occurs.
  • Weak references: Objects that are useful but not necessary will be recycled in the next GC.
  • Phantom reference (ghost reference/phantom reference): Objects cannot be obtained through phantom references. PhantomReference is used to implement phantom references. The purpose of phantom references is to return a notification during gc.

203. Tell me what garbage collection algorithms does the JVM have?

  • Mark-sweep algorithm: mark useless objects, and then clear and recycle them. Disadvantages: Inefficient, unable to remove debris.
  • Mark-sorting algorithm: mark useless objects, let all surviving objects move to one end, and then directly clear the memory outside the end boundary.
  • Copy algorithm: Divide two memory areas of equal size according to capacity, copy the living object to another block when one block is used up, and then clean up the used memory space at one time. Disadvantages: The memory usage is not high, only half of the original.
  • Generational algorithm: Divide the memory into several blocks according to the life cycle of the object, usually the new generation and the old generation. The new generation basically adopts the copy algorithm, and the old generation uses the marking algorithm.

204. Tell me what kind of garbage collectors does the JVM have?

  • Serial: The earliest single-threaded serial garbage collector.
  • Serial Old: The old version of the Serial garbage collector is also single-threaded and can be used as an alternative to the CMS garbage collector.
  • ParNew: It is a multi-threaded version of Serial.
  • Parallel and ParNew collectors are similarly multi-threaded, but Parallel is a throughput-first collector that can sacrifice waiting time for system throughput.
  • Parallel Old is the old generation version of Parallel. Parallel uses the copy memory recovery algorithm, and Parallel Old uses the mark-organize memory recovery algorithm.
  • CMS: A collector that aims to obtain the shortest pause time, very suitable for B/S systems.
  • G1: A GC implementation that takes into account both throughput and pause time. It is the default GC option after JDK 9.

205. Describe the CMS garbage collector in detail?

CMS is the abbreviation of Concurrent Mark-Sweep in English. It is a garbage collector that obtains the shortest recovery pause time at the expense of throughput. For applications that require server response speed, this garbage collector is very suitable. Add "-XX:+UseConcMarkSweepGC" to the parameters of starting the JVM to specify the use of the CMS garbage collector.

CMS is implemented using the mark-clear algorithm, so a large amount of memory fragments will be generated during gc. When the remaining memory cannot meet the program running requirements, the system will appear Concurrent Mode Failure, and the temporary CMS will use the Serial Old recycler Perform garbage removal, performance will be reduced at this time.

206. What are the new generation garbage collector and the old generation garbage collector? What's the difference?

  • New generation collector: Serial, ParNew, Parallel Scavenge

  • Old age collector: Serial Old, Parallel Old, CMS

  • Whole heap collector: G1

  • The new generation garbage collector generally uses the copy algorithm. The advantage of the copy algorithm is high efficiency, but the disadvantage is low memory utilization; the old generation collector generally uses the mark-sort algorithm for garbage collection.

207. Briefly describe how the generational garbage collector works?

The generational collector has two partitions: the old generation and the new generation. The default space of the new generation accounts for 1/3 of the total space, and the default proportion of the old generation is 2/3.

The new generation uses the replication algorithm. There are three partitions in the new generation: Eden, To Survivor, and From Survivor. Their default ratio is 8:1:1. Its execution process is as follows:

  • Put the surviving objects of Eden + From Survivor into the To Survivor area;

  • Empty the Eden and From Survivor partitions;

  • From Survivor and To Survivor partition exchange, From Survivor becomes To Survivor, To Survivor becomes From Survivor.

Every time an object survives when moving from From Survivor to To Survivor, its age will be +1, and when the age reaches 15 (the default configuration is 15), it will be upgraded to the old generation. Large objects also go directly to the old generation.

When the space occupied by the old generation reaches a certain value, the global garbage collection will be triggered, and the execution algorithm of marking and sorting is generally used. The above cycles constitute the overall execution process of the entire generational garbage collection.

208. Tell me about the tools for JVM tuning?

JDK comes with many monitoring tools, all of which are located in the bin directory of JDK, the most commonly used of which are the two view monitoring tools jconsole and jvisualvm.

  • jconsole: used to monitor memory, threads and classes in the JVM; jvisualvm: JDK

  • The built-in all-round analysis tool can analyze: memory snapshot, thread snapshot, program deadlock, monitoring memory changes, gc changes, etc.

209. Under what circumstances will stack memory overflow occur?

  • The stack is private to the thread. The life cycle of the stack is the same as that of the thread. Each method will create a stack frame when it is executed, which contains information such as local variable table, operand stack, dynamic link, method exit, etc. The local variable table and Includes references to primitive data types and objects;
  • When the stack depth requested by the thread exceeds the maximum depth allowed by the virtual machine, a StackOverFlowError exception will be thrown, and this problem may occur when the method is called recursively;
  • Adjust the parameter -xss to adjust the size of the jvm stack

210. How to break the parent delegation model?

Customize the class loader, inherit the ClassLoader class, rewrite the loadClass method and the findClass method;

211. What is the difference between strong references, soft applications, weak references, and phantom references?

强引用:
强引用是我们使用最广泛的引用,如果一个对象具有强引用,那么垃圾回收期绝对不会回收它,当内存空间不足时,垃圾回收器宁愿抛出OutOfMemoryError,也不会回收具有强引用的对象;我们可以通过显示的将强引用对象置为null,让gc认为该对象不存在引用,从而来回收它;

软引用:
软应用是用来描述一些有用但不是必须的对象,在java中用SoftReference来表示,当一个对象只有软应用时,只有当内存不足时,才会回收它;
软引用可以和引用队列联合使用,如果软引用所引用的对象被垃圾回收器所回收了,虚拟机会把这个软引用加入到与之对应的引用队列中;

弱引用:
弱引用是用来描述一些可有可无的对象,在java中用WeakReference来表示,在垃圾回收时,一旦发现一个对象只具有软引用的时候,无论当前内存空间是否充足,都会回收掉该对象;
弱引用可以和引用队列联合使用,如果弱引用所引用的对象被垃圾回收了,虚拟机会将该对象的引用加入到与之关联的引用队列中;

虚引用:
虚引用就是一种可有可无的引用,无法用来表示对象的生命周期,任何时候都可能被回收,虚引用主要使用来跟踪对象被垃圾回收的活动,虚引用和软引用与弱引用的区别在于:虚引用必须和引用队列联合使用;在进行垃圾回收的时候,如果发现一个对象只有虚引用,那么就会将这个对象的引用加入到与之关联的引用队列中,程序可以通过发现一个引用队列中是否已经加入了虚引用,来了解被引用的对象是否需要被进行垃圾回收;

212. 常用的 JVM 调优的参数都有哪些?

  • -Xms2g:初始化推大小为 2g;
  • -Xmx2g:堆最大内存为 2g;
  • -XX:NewRatio=4:设置年轻的和老年代的内存比例为 1:4;
  • -XX:SurvivorRatio=8:设置新生代 Eden 和 Survivor 比例为 8:2;
  • –XX:+UseParNewGC:指定使用 ParNew + Serial Old 垃圾回收器组合;
  • -XX:+UseParallelOldGC:指定使用 ParNew + ParNew Old 垃圾回收器组合;
  • -XX:+UseConcMarkSweepGC:指定使用 CMS + Serial Old 垃圾回收器组合;
  • -XX:+PrintGC:开启打印 gc 信息;
  • -XX:+PrintGCDetails:打印 gc 详细信息。

结尾
这不止是一份面试清单,更是一种“被期望的责任”,因为有无数个待面试着,希望从这篇文章中,找出通往期望公司的“钥匙”,所以上面的每道选题都是结合我自身的经验,于千万个面试题中经过艰辛的两周,一个题一个题筛选出来再校对好答案和格式做出来的,面试的答案也是再三斟酌,生怕误人子弟是小,影响他人的“仕途”才是大过,所以如有纰漏,还请读者朋友们在评论区不吝指出。

也希望您能把这篇文章分享给更多的朋友,让它帮助更多的人。

Guess you like

Origin blog.csdn.net/dreaming317/article/details/128261140