Super detailed Summary of Java learning materials
Java classic interview questions
- Java based
-
- 1. What is the difference between JDK and JRE?
- 2. What is the difference between == and equals?
- 3. If two objects have the same hashCode(), equals() must also be true, right?
- 4. What does final do in Java?
- 5. How much is math.round (-1.5) in Java?
- 6. Is String a basic data type?
- 7. What are the classes for manipulating strings in Java? What’s the difference between them?
- Is String STR =” I “the same as String STR =new String(” I “)?
- 9. How to reverse a string?
- What are the common methods of the String class?
- 11. Must abstract classes have abstract methods?
- 12. What are the differences between ordinary classes and abstract classes?
- 13. Can abstract classes use final?
- What is the difference between an interface and an abstract class?
- 15. How many IO streams are there in Java?
- 16. What is the difference between BIO, NIO and AIO?
- 17. What are the common methods of Files?
- The container
-
- 18. What are Java containers?
- 19. What’s the difference between Collections and Collections?
- 20. What is the difference between a List, a Set and a Map?
- 21. What is the difference between HashMap and Hashtable?
- 22. How do I decide to use HashMap or TreeMap?
- 23. How does HashMap work?
- 24. How does HashSet work?
- 25. What is the difference between ArrayList and LinkedList?
- 26. How to convert an array to a List?
- 27. What is the difference between an ArrayList and a Vector?
- 28. What’s the difference between Array and ArrayList?
- 29. What is the difference between poll() and remove() in a Queue?
- 30. Which collection classes are thread-safe?
- 31. What is an Iterator?
- 32. How to use Iterator? What are the characteristics?
- 33. What is the difference between Iterator and ListIterator?
- multithreading
-
- What is the difference between parallelism and concurrency?
- 36. What is the difference between threads and processes?
- 37. What is a daemon thread?
- 38. What are the ways to create a thread?
- 39. What is the difference between runnable and callable?
- What are the states of threads?
- 41. What’s the difference between sleep() and wait()?
- What is the difference between notify() and notifyAll()?
- 43. What is the difference between run() and start() for a thread?
- 44. What are the ways to create a thread pool?
- What are the states of the thread pool?
- 46. What is the difference between submit() and execute() methods in the thread pool?
- 47. How to ensure the safety of multithreading in Java program?
- 48. What is the upgrade principle of multi-threaded lock?
- 49. What is a deadlock?
- 50. How do I prevent deadlocks?
- 51. What is ThreadLocal? What are the usage scenarios?
- Talk about the underlying implementation of synchronized.
- 53. What is the difference between synchronized and volatile?
- 54. What’s the difference between synchronized and Lock?
- What is the difference between synchronized and ReentrantLock?
- 56. How does atomic work?
- reflection
-
- 57. What is reflection?
- 58. What is Java serialization? When is serialization needed?
- 59. What is a dynamic proxy? What are the applications?
- 60. How to implement dynamic proxy?
- 61. Why use cloning?
- 62. How to implement object cloning?
- 63. What is the difference between deep copy and shallow copy?
- Java Web
-
- 64. What is the difference between a JSP and a servlet?
- 65. What built-in objects does JSP have? What are the effects?
- 66. What are the four scopes of JSP?
- 67. What is the difference between session and cookie?
- 68. How does session work?
- 69. Can session be implemented if the client disables cookies?
- 70. What is the difference between Spring MVC and Struts?
- 71. How do I avoid SQL injection?
- 72. What is an XSS attack and how can it be avoided?
- 73. What is a CSRF attack and how can it be avoided?
- abnormal
-
- Throws throws 74.
- 75. What is the difference between final, finally and Finalize?
- 76. Which part of the try-catch-finally can be omitted?
- 77. In try-catch-finally, if a catch returns, finally will be executed?
- 78. What are the common exception classes?
- network
-
- 79. What do HTTP response codes 301 and 302 represent? What’s the difference?
- 80. What’s the difference between forward and redirect?
- 81. Describe the differences between TCP and UDP.
- 82. Why does TCP require three handshakes? Why is that?
- How does TCP sticky packet come into being?
- 84. What are the OSI seven-tier models?
- 85. What are the differences between GET and POST requests?
- 86. How to achieve cross-domain?
- 87. How does JSONP work?
- Design patterns
-
- 88. Tell me about a design pattern you are familiar with.
- 89. What is the difference between a simple factory and an abstract factory?
- Spring / Spring MVC
-
- 90. Why use Spring?
- Explain what AOP is?
- Explain what ioc is.
- 93. What are the main modules of Spring?
- What are the common injection methods in Spring?
- 95. Are beans in Spring thread-safe?
- 96. How many scopes does Spring support for beans?
- 97. What are the methods for Spring to automate bean assembly?
- What are the ways in which Spring transactions are implemented?
- 99. What about Transaction isolation in Spring?
- 100. What about the Spring MVC workflow?
- 101. What components does Spring MVC have?
- 102. What does @requestMapping do?
- 103. What does @autowired do?
- Spring Boot / Spring Cloud
-
- 104. What is Spring Boot?
- 105. Why Spring Boot?
- 106. What is the Spring Boot core configuration file?
- 107. What are the types of Spring Boot configuration files? What’s the difference?
- 108. How can Spring Boot implement hot deployment?
- 109. What is the difference between JPA and Hibernate?
- 110. What is Spring Cloud?
- 111. What does the Spring Cloud circuit breaker do?
- 112. What are the core components of Spring Cloud?
- Hibernate
-
- 113. Why use Hibernate?
- 114. What is ORM Framework?
- 115. How to view printed SQL statements in The console in Hibernate?
- How many query methods does Hibernate have?
- 117. Can Hibernate entity classes be defined as final?
- 118. What is the difference between using Integer and int for mapping in Hibernate?
- 119. How does Hibernate work?
- 120. The difference between get() and load()?
- 121. What about Hibernate’s caching mechanism?
- 122. What are the states of Hibernate objects?
- What is the difference between getCurrentSession and openSession in Hibernate?
- 124. Do Hibernate entity classes have to have parameterless constructors? Why is that?
- Mybatis
-
- 125. What is the difference between #{} and ${} in mybatis?
- 126. How many pagination methods are there in Mybatis?
- 127. Advantages and disadvantages of Mybatis
- 128. What is the difference between logical paging and physical paging in Mybatis?
- 129. Does Mybatis support lazy loading? What is the principle of lazy loading?
- What about level 1 cache and level 2 cache in Mybatis?
- 131. What are the differences between Mybatis and Hibernate?
- 132. What executors do Mybatis have?
- 133. What is the implementation principle of mybatis paging plug-in?
- 134. How to write a custom plug-in for Mybatis?
- RabbitMQ
-
- 135. What are the usage scenarios for RabbitMQ?
- 136. What are the important roles of RabbitMQ?
- 137. What are the important components of RabbitMQ?
- 138. What is vhost for rabbitMQ?
- 139. How are rabbitMQ messages sent?
- 140. How does RabbitMQ ensure message stability?
- 141. How can RabbitMQ avoid message loss?
- 142. What are the conditions for successful message persistence?
- 143. What are the disadvantages of RabbitMQ persistence?
- 144. How many broadcast types are available for RabbitMQ?
- 145. How does RabbitMQ implement delayed message queuing?
- 146. What are rabbitMQ clusters for?
- 147. What are the types of RabbitMQ nodes?
- 148. What should I pay attention to when setting up rabbitMQ clusters?
- 149. Is each rabbitMQ node a full copy of the other nodes? Why is that?
- 150. What happens when the only disk node in the RabbitMQ cluster crashes?
- 151. Does RabbitMQ have a stop order for cluster nodes?
- Kafka
-
- Can Kafka be used independently of ZooKeeper? Why is that?
- 153. How many data retention strategies does Kafka have?
- 154. Kafka sets 7 days and 10 gigabytes of clean data at the same time, and on the fifth day it reaches 10 gigabytes of clean data.
- 155. What can cause Kafka to run slowly?
- 156. What should I pay attention to when using kafka clusters?
- Zookeeper
-
- 157. What is Zookeeper?
- 158. What functions does ZooKeeper have?
- 159. How many deployment modes are available for ZooKeeper?
- 160. How does ZooKeeper synchronize the status of the primary and secondary nodes?
- 161. Why have a primary node in a cluster?
- 162. There are three servers in the cluster and one node is down. Is ZooKeeper still available?
- 163. What is the notification mechanism of ZooKeeper?
- MySql
-
- 164. What are the three paradigms of databases?
- Mysql > alter table alter table alter table alter table alter table alter table alter table alter table alter table alter table alter table alter table alter table
- 166. How do I obtain the current database version?
- 167. What is ACID?
- 168. What is the difference between char and varchar?
- 169. What is the difference between float and double?
- 170. What is the difference between inner join, left join, right join in mysql?
- 171. How is the mysql index implemented?
- 172. How to verify that the mysql index meets the requirement?
- 173. What about transaction isolation of databases?
- 174. What is the common mysql engine?
- 175. What about row and table locks in mysql?
- 176. What about optimistic and pessimistic locks?
- 177. What are the methods used to troubleshoot mysql problems?
- 178. How to optimize mysql performance?
- Redis
-
- 179. What is redis? What are the usage scenarios?
- 180. What functions does Redis have?
- 181. What’s the difference between Redis and memecache?
- 182. Why is Redis single threaded?
- 183. What is cache penetration? How to solve it?
- 184. What data types are supported by Redis?
- 185. What Java clients does Redis support?
- 186. What are the differences between Jedis and Redisson?
- 187. How to ensure the consistency of cache and database data?
- 188. How many ways can REDis persist?
- 189. How does Redis implement distributed lock?
- 190. What are the defects of redis distributed locks?
- 191. How does Redis optimize memory?
- 192. What are the Redis elimination strategies?
- 193. What are the common performance issues with Redis? How to solve it?
- JVM
-
- 194. What are the main components of the JVM? And its role?
- 195. What about the JVM runtime data area?
- 196. What is the difference between stacks?
- 198. What is the parental delegation model?
- 199. What about the execution of class loading?
- 200. How to determine whether an object can be reclaimed?
- 201. What reference types are available in Java?
- 202. What garbage collection algorithms does the JVM have?
- 203. What garbage collectors does the JVM have?
- 204. What about CMS garbage collector?
- 205. What are the new generation garbage collectors and old generation garbage collectors? What’s the difference?
- 206. Describe briefly how generational garbage collector works.
- 207. What about JVM tuning tools?
- 208. What are the common JVM tuning parameters?
Java based
1. What is the difference between JDK and JRE?
JDK: Short for Java Development Kit, the Java Development Kit provides the Java Development environment and runtime environment. JRE: Short for Java Runtime Environment. It provides the required Environment for Running Java.
Specifically, the JDK actually contains the JRE, as well as the compiler javac that compiles Java source code, as well as many tools for debugging and analyzing Java programs. Simply put: if you need to run Java programs, just install the JRE, and if you need to write Java programs, install the JDK.
2. What is the difference between == and equals?
= = interpretation
The effect is different for the base type and the reference type ==, as shown below:
Basic type: compares whether the values are the same; Reference type: Compares whether references are the same;
Code examples:
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
Copy the code
Since x and y refer to the same reference, == is also true, while the new String() method overwrites the memory space, so == is false, and equals always compares values, so it is true.
Equals reading
Equals is essentially equal to ==, except that String and Integer and others have overridden the equals method to make it a value comparison. Take a look at the code below.
First, equals compares an object with the same value by default, as follows:
class Cat { public Cat(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 "); Cat c2 = new Cat(" Cat "); System.out.println(c1.equals(c2)); // falseCopy the code
The output is false to our surprise. Equals equals equals equals equals equals equals equals equals equals equals equals equals equals
public boolean equals(Object obj) {
return (this == obj);
}
Copy the code
Equals is essentially equal to ==. Why do two strings with the same value return true? The code is as follows:
String s1 = new String(" s1 "); String s2 = new String(" "); System.out.println(s1.equals(s2)); // trueCopy the code
Similarly, when we go to String equals, we find the answer as follows:
public boolean equals(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; }Copy the code
String overrides Object’s equals method, changing reference comparison to value comparison.
Summary: == is a value comparison for primitive types and a reference comparison for reference types; Equals by default is a reference comparison, but many classes have redone equals (String, Integer, etc.) as a value comparison, so in general equals compares whether or not values are equal.
3. If two objects have the same hashCode(), equals() must also be true, right?
HashCode () is the same for both objects and equals() is not necessarily true.
Code examples:
String str1 = "Call "; String str2 = ""; System. Out. Println (the String. Format (" | str2 str1: % d: % d ", str1. HashCode (), str2. HashCode ())); System.out.println(str1.equals(str2)); The result of the execution: str1:1179395 | str2:1179395 falseCopy the code
HashCode () is the same as hashCode(), but equals() is false, because in a hash table hashCode() equals the hash values of two key-value pairs. However, the hash values are equal, which does not necessarily result in the key-value pairs being equal.
4. What does final do in Java?
Classes that are final are called final classes and cannot be inherited. Final methods cannot be overridden. A final variable is called a constant, which must be initialized, after which its value cannot be changed.
5. How much is math.round (-1.5) in Java?
Is equal to -1, because the median value (0.5) is rounded to the right on the number line, so plus 0.5 is rounded up, and minus 0.5 is discarded.
6. Is String a basic data type?
Strings are not part of the base type. There are eight basic types: byte, Boolean, char, short, int, float, long, and double. Strings are objects.
7. What are the classes for manipulating strings in Java? What’s the difference between them?
Classes that operate on strings are: String, StringBuffer, StringBuilder.
The difference between String and StringBuffer and StringBuilder is that String declares an immutable object. Each operation generates a new String and then points to a new String. StringBuffer and StringBuilder can operate on existing objects, so it’s best not to use strings if you’re constantly changing the contents of strings.
The big difference between StringBuffer and StringBuilder is that StringBuffer is thread-safe and StringBuilder is non-thread-safe, but StringBuilder performs better than StringBuffer, So StringBuilder is recommended for single-threaded environments and StringBuffer is recommended for multi-threaded environments.
Is String STR =” I “the same as String STR =new String(” I”)?
No, because memory is allocated differently. String STR =” I “, which the Java virtual machine allocates to the constant pool; String STR =new String(” I “) is allocated to the heap.
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
Copy the code
What are the common methods of the String class?
IndexOf () : returns the indexOf the specified character. CharAt () : Returns the character at the specified index. Replace () : string replacement. Trim () : Removes whitespace at both ends of a string. Split () : Split string, returns a split array of strings. GetBytes () : Returns a byte array of strings. Length () : Returns the length of the string. ToLowerCase () : converts the string toLowerCase. ToUpperCase () : converts a string toUpperCase characters. Substring () : intercepts a string. Equals () : String comparison.
11. Must abstract classes have abstract methods?
No, abstract classes don’t have to have abstract methods.
Sample code:
abstract class Cat { public static void sayHi() { System.out.println("hi~"); }}Copy the code
In the code above, the abstract class does not have abstract methods but works perfectly fine.
12. What are the differences between ordinary classes and abstract classes?
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 abstract classes use final?
If an abstract class is defined as final, the class cannot be inherited. This conflicts with each other. Therefore, final cannot modify an abstract class, as shown in the following figure.
What is the difference between an interface and an abstract class?
Implementation: Subclasses of abstract classes inherit using extends; Interfaces must be implemented using IMPLEMENTS. Constructors: Abstract classes can have constructors; No interface exists. Main method: Abstract classes can have main methods and we can run them; An interface cannot have a main method. Number of implementations: A class can implement many interfaces; But only one abstract class can be inherited. Access modifiers: Methods in an interface use the public modifier by default; Methods in abstract classes can be arbitrary access modifiers.
15. How many IO streams are there in Java?
According to functions, it can be divided into: input and output.
By type: byte stream and character stream.
The difference between a byte stream and a character stream is that a byte stream transmits input and output data in bytes in 8 bits, while a character stream transmits input and output data in characters in 16 bits.
16. What is the difference between BIO, NIO and AIO?
BIO: Block IO Synchronous blocking IO is the traditional IO that we usually use. It is characterized by simple mode and convenient use, and low concurrent processing capability. NIO: New IO synchronous non-blocking IO is an upgrade of traditional IO. The client and server communicate through channels, realizing multiplexing. AIO: Asynchronous IO is an upgrade of NIO, also known as NIO2, which implements Asynchronous non-blocking I/O operations based on events and callbacks.
17. What are the common methods of Files?
Files.exists() : checks whether a file path exists. Files.createfile () : Creates a file. Files.createdirectory () : Creates a folder. Files.delete() : Deletes a file or directory. Files.copy() : copies Files. Files.move() : moves a file. Files.size() : Displays the number of Files. Files.read() : Reads Files. Files.write() : writes Files.
The container
18. What are Java containers?
Catalogue of commonly used containers:
19. What’s the difference between Collections and Collections?
Java.util. Collection is a Collection interface (a top-level interface of the Collection class). It provides generic interface methods for performing basic operations on collection objects. The Collection interface has many concrete implementations in the Java class library. The significance of Collection interface is to provide maximum unified operation mode for various specific collections, and its direct inheritance interfaces are List and Set. Collections is a utility/helper class of the collection class that provides a set of static methods for sorting, searching, and thread-safe operations on the elements in the collection.
20. What is the difference between a List, a Set and a Map?
21. What is the difference between HashMap and Hashtable?
HashMap removes the contains method from HashTable, but adds containsValue () and containsKey () methods. HashTable is synchronous, whereas HashMap is non-synchronous, making hashTable more efficient. A hashMap allows empty key values, whereas a hashTable does not.
22. How do I decide to use HashMap or TreeMap?
A HashMap is the best choice for inserting, deleting, and positioning elements into a Map. However, if you need to iterate over an ordered set of keys, TreeMap is a better choice. Depending on the size of your collection, it may be faster to add elements to the HashMap, replacing the map with TreeMap for an ordered key traversal.
23. How does HashMap work?
Overview of HashMap: HashMap is an asynchronous implementation of the Map interface based on hash tables. This implementation provides all optional mapping operations and allows null values and NULL keys. This class does not guarantee the order of the mapping, and in particular it does not guarantee that the order is constant. The data structure of HashMap: In the Java programming language, the most basic structure is two kinds, one is an array, the other is a mock pointer (reference), all data structures can be constructed with these two basic structures, HashMap is no exception. A HashMap is actually a “linked list hash” data structure, which is a combination of arrays and lists. When we put an element into a Hashmap, we first recalculate the hash value based on the hashcode of the key. The hash value is calculated to the element’s location in the array (subscript). If the array already contains other elements at that location, the elements at that location are stored as a linked list, and the new elements are added in the header. The first one goes to the end of the chain. If there is no element at that location in the array, the element is placed directly at that location in the array. In Jdk 1.8, the implementation of HashMap is optimized. When there are more than eight nodes in the list, the list will be converted to a red-black tree to improve query efficiency, from O(n) to O(logn).
24. How does HashSet work?
The underlying HashSet is implemented by HashMap. The value of a HashSet is stored on the key of a HashMap. The value of a HashMap is called PRESENT
25. What is the difference between ArrayList and LinkedList?
The most obvious difference is that the underlying data structure of ArrrayList is an array, which supports random access, while the underlying data structure of LinkedList is a two-way circular LinkedList, which does not support random access. Using subscripts to access an element, the time complexity of ArrayList is O(1) and LinkedList is O(n).
26. How to convert an array to a List?
List toArray: call the toArray method of ArrayList. Array to List: Calls the asList method of Arrays.
27. What is the difference between an ArrayList and a Vector?
Vector is synchronous, ArrayList is not. However, if you are looking to make changes to the list during iteration, you should use CopyOnWriteArrayList. ArrayList is faster than Vector because it is synchronized and does not overload. ArrayList is more general because we can easily get synchronous and read-only lists using the Collections utility class.
28. What’s the difference between Array and ArrayList?
Array can hold primitive types and objects, whereas ArrayList can only hold objects. Array is a specified size, whereas ArrayList is a fixed size. Array doesn’t offer the same functionality as ArrayList, such as addAll, removeAll, and iterator.
29. What is the difference between poll() and remove() in a Queue?
Poll () and remove() both fetch an element from the queue, but poll() returns null on failure to fetch an element, and remove() throws an exception on failure.
30. Which collection classes are thread-safe?
Vector: has one more synchronization mechanism (thread-safe) than ArrayList, which is less efficient and less recommended today. In Web applications, especially foreground pages, efficiency (page response speed) is often a priority. Statck: stack class, first in last out. Hashtable: One more thread safe than HashMap. Enumeration: Enumeration, equivalent to an iterator.
31. What is an Iterator?
An iterator is a design pattern that is an object that can iterate over and select objects in a sequence without requiring the developer to understand the underlying structure of that sequence. Iterators are often referred to as “lightweight” objects because they are inexpensive to create.
32. How to use Iterator? What are the characteristics?
The Iterator function in Java is relatively simple and can only move in one direction: (1) Use the method Iterator () to ask the container to return an Iterator. The first time Iterator’s next() method is called, it returns the first element of the sequence. Note: The iterator() method is the java.lang.Iterable interface, inherited by Collection. (2) Use next() to get the next element in the sequence. (3) Use hasNext() to check if there are any more elements in the sequence. (4) Use remove() to remove the element newly returned by the iterator. Iterator is the simplest implementation of a Java Iterator. ListIterator, designed for a List, has much more functionality, traversing a List in both directions as well as inserting and deleting elements from the List.
33. What is the difference between Iterator and ListIterator?
Iterator can be used to iterate over sets and lists, but ListIterator can only be used to iterate over lists. Iterator can traverse only forward over sets; ListIterator can traverse both forward and backward. ListIterator implements the Iterator interface and includes other functions such as adding elements, replacing elements, retrieving the previous and next element indexes, and so on.
multithreading
What is the difference between parallelism and concurrency?
Parallelism is when two or more events occur at the same time; Concurrency is when two or more events occur at the same time interval. Parallelism is multiple events on different entities, and concurrency is multiple events on the same entity. “Simultaneous” processing of multiple tasks on one processor, multiple tasks on multiple processors. Such as Hadoop distributed cluster.
So the goal of concurrent programming is to make full use of every core of the processor to achieve maximum processing performance.
36. What is the difference between threads and processes?
In short, a process is the basic unit of program execution and resource allocation. A program has at least one process and a process has at least one thread. A process has a separate memory unit during execution, while multiple threads share memory resources, reducing the number of switches and making it more efficient. A thread is an entity of a process. It is the basic unit of CPU scheduling and dispatching. It is a basic unit smaller than a program that can run independently. Multiple threads in the same process can execute concurrently.
37. What is a daemon thread?
A daemon thread, or daemon thread, is a service thread, specifically a service thread to another thread.
38. What are the ways to create a thread?
Create Thread class by inheriting Thread class
Subclass Thread and override the run method of the class. The body of the run method represents the task to be completed by the Thread. Therefore, the run() method is called the body of the execution. Creating an instance of the Thread subclass creates a Thread object. Call the start() method of the thread object to start the thread.
②. Create thread classes through the Runnable interface
Define the implementation class of the Runnable interface and override the run() method of that interface, whose method body is also the thread execution body of that thread. Create an instance of the Runnable implementation class and use this instance as the target of a Thread to create a Thread object, which is the actual Thread object. Call the start() method of the thread object to start the thread.
③ Create threads with Callable and Future
Create an implementation class for the Callable interface that implements the Call () method, which acts as the thread body and has a return value. Create an instance of the Callable implementation class that wraps the Callable object with a FutureTask class that wraps the return value of the Callable object’s call() method. Create and start a new Thread using the FutureTask object as the target of the Thread object. Call the Get () method of the FutureTask object to get the return value after the child thread completes execution.
39. What is the difference between runnable and callable?
A bit of a deep question, but also see a Java programmer to learn the breadth of knowledge.
The return value of the run() method in the Runnable interface is void, and all it does is execute the code in the run() method; The Call () method in the Callable interface, which returns a value, is a generic type that can be used in conjunction with Future and FutureTask to retrieve the result of asynchronous execution.
What are the states of threads?
Threads typically have five states: created, ready, running, blocked, and dead.
Create state. When a thread object is generated, the object’s start method is not called, which is the thread being created. Ready state. When the start method of a thread object is called, the thread is ready, but the thread scheduler has not set the thread to the current thread. The thread is also in the ready state after it runs, after it comes back from waiting or sleeping. Running status. The thread scheduler sets the thread in the ready state to the current thread, at which point the thread enters the run state and starts running the code in the run function. Blocked status. A thread is suspended while it is running, usually to wait for a certain time to occur (such as when a resource is ready) before continuing. Methods like sleep,suspend, and wait can all cause threads to block. State of death. If a thread’s run method finishes or stops, the thread dies. For dead threads, you can no longer use the start method to get them ready
41. What’s the difference between sleep() and wait()?
Sleep () : The method is a static method of Thread class, which makes the calling Thread go to sleep and give the execution opportunity to other threads. After the sleep time ends, the Thread enters the ready state and compets with other threads for CPU execution time. Because sleep() is static, it cannot change the lock of an object. When sleep() is called in a synchronized block, the thread goes to sleep, but the lock is not released, and other threads cannot access the object.
Wait () : Wait () is a method of the Object class. When a thread executes a wait method, it enters the wait pool associated with the Object and releases the lock of the Object so that other threads can access the wait. NotifyAll and notify methods are used to wake up the waiting thread
What is the difference between notify() and notifyAll()?
If a thread calls an object’s wait() method, it is in that object’s wait pool, and the threads in the wait pool do not compete for the lock on that object. When a thread invokes the notifyAll() or notify() methods of an object, the awakened thread enters the lock pool of the object, and the threads compete for the lock. That is, after notify is called, only one thread enters the lock pool from the wait pool, and notifyAll moves all threads in the wait pool to the lock pool, waiting for lock contention. A thread with a higher priority has a higher probability of competing for an object lock. If a thread does not compete for the object lock, it will remain in the lock pool and only return to the wait pool if the thread calls wait() again. The thread that contended for the object lock continues to execute until the synchronized block is finished, which releases the object lock, at which point the pool of threads continues to contend for the object lock.
43. What is the difference between run() and start() for a thread?
Each Thread completes its operations through a method run() corresponding to a particular Thread object, called the Thread body. Start a Thread by calling the start() method of the Thread class.
The start() method is used to start a thread, truly implementing multithreading. Instead of waiting for the body of the run method to finish executing, you can continue with the following code. The thread is in a ready state and is not running. The Thread class then calls the method run() to complete its running state. The method run() is called the Thread body, which contains the contents of the Thread to be executed. The run method ends and the Thread terminates. The CPU then schedules other threads.
The run() method is local to the thread, just a function in the thread, not multithreaded. If you call run() directly, it is just like calling a normal function. If you call run() directly, you have to wait for the run() method to complete before you can execute the following code. Therefore, there is only one execution path, and there is no thread characteristic at all. So use the start() method instead of the run() method for multithreaded execution.
44. What are the ways to create a thread pool?
1. NewFixedThreadPool (int nThreads)
Create a thread pool of fixed length, each time a task is submitted, one thread is created until the maximum number of threads in the pool is reached, at which point the thread size does not change, and when a thread terminates with an unexpected error, a new thread is added to the pool.
(2). NewCachedThreadPool ()
Create a cacheable thread pool that automatically recycles idle threads if the size of the thread pool exceeds processing requirements, and automatically adds new threads when demand increases. There is no limit to the size of the thread pool.
(3). NewSingleThreadExecutor ()
This is a single-threaded Executor that creates a single worker thread to execute a task, and if this thread terminates abnormally, a new one is created to replace it; It features the ability to ensure that tasks are executed sequentially according to the order in the queue.
(4). NewScheduledThreadPool (int corePoolSize)
A fixed length thread pool is created and tasks are executed in a deferred or timed manner, similar to a Timer.
What are the states of the thread pool?
Thread pools are in five states: Running, ShutDown, Stop, Tidying, and Terminated. Thread pool each state switch block diagram:
46. What is the difference between submit() and execute() methods in the thread pool?
Submit returns a value, while execute does not submit to facilitate Exception processing
47. How to ensure the safety of multithreading in Java program?
Thread safety is embodied in three aspects:
Atomicity: provides mutually exclusive access and only one thread can operate on data at a time (atomic,synchronized); Visibility: Changes made by one thread to main memory can be seen by other threads in a timely manner (synchronized,volatile); Orderliness: One thread observes the order in which instructions are executed in another thread, and the observation is often disorderly due to instruction reordering (happens-before principle).
48. What is the upgrade principle of multi-threaded lock?
In Java, there are four lock states, ranked from lowest to highest: stateless, biased, lightweight, and heavyweight, which escalate as the race progresses. Locks can be upgraded but not degraded.
Graphical process of lock upgrade:
49. What is a deadlock?
A deadlock is a phenomenon in which two or more processes are blocked during execution, either by competing for resources or by communicating with each other, and cannot proceed without external action. The system is said to be in a deadlock state or a deadlock occurs in the system. These processes that are always waiting for each other are called deadlocked processes. An error at the operating system level, it is short for process deadlock. It was first proposed by Dijkstra in 1965 while working on banker algorithms. It is one of the most difficult problems to deal with in computer operating systems and in the whole field of concurrent programming.
50. How do I prevent deadlocks?
Four necessary conditions for deadlocks are as follows: Mutually exclusive condition: A process does not allow other processes to access the allocated resource. If other processes access the resource, they can only wait until the process that occupies the resource finishes using the resource and releases the request and hold condition: Process to obtain a certain resources and make requests for other resources, could be other processes but the resource possession, it request block, but also obtain resources to keep to myself Inalienable conditions: refers to the process have been given the resources, the unfinished before use, shall not be deprived of, can only be used after waiting for their release loop conditions: It refers to a round-robin waiting resource relationship between several processes after a deadlock occurs
These four conditions are necessary for deadlocks, and they must be true whenever a deadlock occurs on the system, and no deadlock occurs unless one of these conditions is met.
Understanding the causes of deadlocks, especially the four necessary conditions for deadlocks, can best avoid, prevent, and remove deadlocks.
Therefore, in system design, process scheduling and other aspects to pay attention to how not to let the four necessary conditions set up, how to determine the reasonable allocation of resources algorithm, to avoid process permanent occupation of system resources.
Also, prevent processes from taking up resources while they are in a wait state. Therefore, the allocation of resources should be given reasonable planning.
51. What is ThreadLocal? What are the usage scenarios?
Thread-local variables are variables that are limited within a thread and are owned by the thread itself and are not shared between multiple threads. Java provides a ThreadLocal class to support thread-local variables as a way to achieve thread-safety. However, be careful when using thread-local variables in a managed environment, such as a Web server, where the life of a worker thread is longer than the life of any application variable. Java applications run the risk of memory leaks if any thread-local variables are not released after work is done.
Talk about the underlying implementation of synchronized.
Synchronized ensures that only one method or block of code can enter a critical section at any one time at runtime, and it also ensures memory visibility of shared variables.
Every object in Java can be used as a lock, which is the basis for synchronized:
Common synchronization method, lock is the current instance object static synchronization method, lock is the current class object synchronization method block, lock is the object in parentheses
53. What is the difference between synchronized and volatile?
Volatile essentially tells the JVM that the value of the current variable in the register (working memory) is indeterminate and needs to be read from main memory; Synchronized locks the current variable so that only the current thread can access it and other threads are blocked. Volatile can only be used at the variable level; Synchronized can be used at the variable, method, and class levels. Volatile only enables change visibility of variables, not atomicity. Synchronized can guarantee the change visibility and atomicity of variables. Volatile does not block threads; Synchronized can cause threads to block. Volatile variables are not optimized by the compiler; Variables of the synchronized tag can be optimized by the compiler.
54. What’s the difference between synchronized and Lock?
Synchronized is a built-in Java keyword, and Lock is a Java class at the JVM level. Synchronized cannot determine whether the Lock is obtained. Lock can determine whether the Lock is obtained. Synchronized automatically releases the lock (a thread releases the lock after executing the synchronization code; The Lock must be released manually in finally (unlock()). Otherwise, the thread is likely to deadlock. Two threads 1 and 2 that use the synchronized keyword, if the current thread 1 acquires the lock, thread 2 waits. If thread 1 is blocked, thread 2 will wait forever, while Lock does not necessarily wait. If an attempt to acquire the Lock fails, the thread can terminate without waiting forever. Synchronized locks are reentrant, uninterruptible, and non-fair, whereas Lock locks are reentrant, judgeable, and fair (both). Lock locks are suitable for synchronization problems with a lot of synchronized code, and synchronized locks are suitable for synchronization problems with a small amount of synchronized code.
What is the difference between synchronized and ReentrantLock?
Synchronized is a keyword like if, else, for, and while. ReentrantLock is a class. This is the essential difference between synchronized and while. Since ReentrantLock is a class, it provides more flexible features than synchronized. It can be inherited, can have methods, and can have a variety of class variables. ReentrantLock has more extensibility than synchronized in several aspects:
ReentrantLock allows you to set the wait time for acquiring locks, so deadlocks are avoided. ReentrantLock allows you to obtain information about various locks. ReentrantLock allows you to flexibly implement multiple notifications
Unsafe Lock (ReentrantLock) refers to the Unsafe park method, whereas synchronized refers to the Mark Word object header.
56. How does atomic work?
Atomic package basic feature is the class in a multithreaded environment, when there are multiple threads at the same time for a single (including basic types and reference types) variables, exclusive, when multiple threads on the value of the variable is updated at the same time, there is only one thread can be successful, but not the thread can to spin locks to success, keep trying, Wait until the execution succeeds.
The core methods in the Atomic family classes all call several native methods in the Unsafe class. The first thing you need to know is the Unsafe class, whose full name is: Sun.misc.Unsafe, the Unsafe class contains numerous operations on C code, including calls to direct memory allocation and atomic operations. Addressing Unsafe, sun.misc. For example, when allocating memory using unsafe, specifying areas may result in Pointers to other processes, as in C++.
reflection
57. What is reflection?
Reflection refers primarily to the ability of a program to access, detect, and modify its own state or behavior:
In the Java runtime environment, is it possible to know what properties and methods a given class has? The Java reflection mechanism provides the following functions:
Determine the class to which any object belongs at run time. Constructs an object of any class at run time. Determine which member variables and methods any class has at run time. Call a method of any object at run time.
58. What is Java serialization? When is serialization needed?
Simply put, it is to store the state of various objects in memory (i.e. instance variables, not methods), and can be saved to read out the state of the object. Although you can save object States in various ways of your own, Java gives you a mechanism for saving object states that should be better than your own, and that is serialization.
When serialization is required:
A) When you want to save the state of an object in memory to a file or database; B) when you want to use a socket to send objects over the network; C) when you want to transfer objects over RMI;
59. What is a dynamic proxy? What are the applications?
Dynamic proxy:
When you want to add some extra processing to a method in a class that implements an interface. For example, add log, add transaction and so on. You can create a proxy for this class, and the name of the proxy is to create a new class that not only contains the functionality of the original class methods, but also adds additional processing to the original class. This proxy class is not defined and is dynamically generated. It has decoupling significance, flexibility and strong expansibility.
Dynamic proxy applications:
Spring’s AOP plus transactions plus permissions plus logging
60. How to implement dynamic proxy?
You must first define an interface and have an InvocationHandler(to which you pass objects from the class that implements the interface) process the class. There is also a utility class called Proxy(commonly called Proxy because calling newInstance() produces Proxy objects, but it is just a utility class that produces Proxy objects). Using the InvocationHandler, splice the source code of the proxy class, compile it to generate the binary code of the proxy class, use the loader to load, and instantiate the proxy object, and finally return.
Copy the object
61. Why use cloning?
In order to process an object and retain the original data for subsequent operations, cloning is required. In the Java language, cloning is for an instance of a class.
62. How to implement object cloning?
There are two ways:
1). Implement Cloneable interface and override clone() method in Object class; 2). Implement Serializable interface, clone through object serialization and deserialization, can realize the real deep clone, the code is as follows:
import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; public class MyUtil { private MyUtil() { throw new AssertionError(); } @SuppressWarnings("unchecked") public static <T extends Serializable> T clone(T obj) throws Exception { ByteArrayOutputStream bout = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bout); oos.writeObject(obj); ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bin); return (T) ois.readObject(); / / description: Calling ByteArrayInputStream // or the close method of the ByteArrayOutputStream object makes no sense // These two memory-based streams can free resources as soon as the garbage collector cleans up the object, // This is different from releasing external resources (such as file streams)}}Copy the code
Here is the test code:
import java.io.Serializable; /** ** @author nnngu ** / class Person implements Serializable {private static final Long serialVersionUID = -9102017020286042305L; private String name; // private int age; Private Car Car; Public Person(String name, int age, Car Car) {this.name = name; this.age = age; this.car = car; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Car getCar() { return car; } public void setCar(Car car) { this.car = car; } @Override public String toString() { return "Person [name=" + name + ", age=" + age + ", car=" + car + "]"; @author nnngu ** / class Car implements Serializable {private static final Long serialVersionUID = -5713945027627603702L; private String brand; Private int maxSpeed; Public Car(String brand, int maxSpeed) {this.brand = brand; this.maxSpeed = maxSpeed; } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public int getMaxSpeed() { return maxSpeed; } public void setMaxSpeed(int maxSpeed) { this.maxSpeed = maxSpeed; } @Override public String toString() { return "Car [brand=" + brand + ", maxSpeed=" + maxSpeed + "]"; }} class CloneTest {public static void main(String[] args) {try {Person p1 = new Person(" ", 33, new Car(" "), 300)); Person p2 = MyUtil.clone(p1); P2.getcar ().setbrand ("BYD"); Println (p1); Person (p1); Person (p1); } catch (Exception e) { e.printStackTrace(); }}}Copy the code
Note: based on the realization of serialization and deserialization cloning is not only a deep, more important is through the generic limit, you can check out whether the Object supports serialization to clone, the inspection is done by the compiler, not throw an exception at run time, this is the solution using the Object class is obviously better than the method of clone cloned objects. It’s always better to expose problems at compile time than to leave them to run time.
63. What is the difference between deep copy and shallow copy?
Shallow copy just copy the object reference address, two object point to the same memory address, so that changes the value of the any of the other a value will be changed, that is shallow copy (example: the assign ()) deep copy is the object and the value is copied, two objects to modify any of the value of another value will not change, this is a deep copy (example: Json.parse () and json.stringify (), but this method cannot copy the function type)
Java Web
64. What is the difference between a JSP and a servlet?
JSPS, when compiled, become servlets. (JSPS are essentially servlets, and the JVM only recognizes Java classes, not JSP code. The Web container compiles JSP code into Java classes that the JVM recognizes.) Servlets are better at logical control. There are no built-in objects in servlets. Built-in objects in JSPS must be obtained from HttpServletRequest objects, HttpServletResponse objects, and HttpServlet objects. Jsp is a simplification of Servlet, using Jsp only need to complete the programmer needs to output to the client side of the content, Jsp Java script Mosaic into a class, completed by Jsp container. A Servlet, on the other hand, is a complete Java class whose Service method is used to generate a response to the client.
65. What built-in objects does JSP have? What are the effects?
JSP has nine built-in objects:
Request: Encapsulates a client request that contains parameters from a GET or POST request; Response: Encapsulates the server’s response to the client. PageContext: This object is used to get other objects; Session: The object that encapsulates the user’s session; Application: encapsulates the object of the server running environment; Out: Outputs the output stream object that the server responds to. Config: indicates the configuration object of the Web application. Page: The JSP page itself (equivalent to this in Java programs); Exception: An object that encapsulates the exception thrown by the page.
66. What are the four scopes of JSP?
The four scopes in JSP include Page, Request, Session, and Application, specifically:
Page represents the objects and properties associated with a page. Request represents objects and attributes associated with a request made by a Web 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 the objects and properties associated with a session between a user and the server. Data related to a user should be stored in the user’s own session. Application represents objects and properties associated with the entire Web application, which is essentially a global scope that spans the entire Web application and includes multiple pages, requests, and sessions.
67. What is the difference between session and cookie?
HTTP is a stateless protocol, so when the server needs to record the user status, it needs to use some mechanism to identify the specific user, which is Session. In a typical scenario like a shopping cart, when you click the order button, HTTP is stateless, so you don’t know which user is doing it, so the server creates a special Session for a particular user, identifies that user, and keeps track of that user, so it knows how many books are in the shopping cart. This Session is stored on the server and has a unique identifier. There are many ways to save sessions on the server, including memory, databases, and files. Session transfer should also be considered when clustering. In large websites, there is usually a special cluster of Session servers to store user sessions. In this case, Session information is stored in memory, and some caching services such as Memcached are used to store sessions.
How does the server identify a particular client? This is where Cookie comes in. Each TIME an HTTP request is made, the client sends a Cookie to the server. In fact, most applications use cookies to realize Session tracking. When a Session is created for the first time, the server tells the client in the HTTP protocol that it needs to record a Session ID in the Cookie, and sends this Session ID to the server for each subsequent request. I knew who you were.
Someone asked, what if cookies are disabled on the client’s browser? In this case, session tracking is typically done using a technique called URL rewriting, where each HTTP interaction is followed by a parameter such as SID = XXXXX that the server identifies the user.
In fact, cookies can also be used in some user-friendly scenarios. Imagine you log in to a website once, but the next time you log in, you don’t want to enter your account again. What do you do? This information can be written into the Cookie. When you visit the website, the script of the website page can read this information and automatically fill in the user name for you, which can be convenient for users. That’s how Cookie got its name, to give users a little sweetener.
So, to sum up: Session is a data structure stored on the server to track user status. This data can be stored in clusters, databases, files. Cookie is a mechanism for the client to save user information, which is used to record some user information and also a way to realize the Session.
68. How does session work?
A session is a file stored on the server, similar to a hash table. It contains the information we need, and we can pull it out when we need it. Similar to a large map, the key inside stores the user’s sessionid, which the user carries when sending requests to the server. Now you can pull the corresponding value out of it.
69. Can session be implemented if the client disables cookies?
Cookie and Session are generally considered to be two independent things. Session uses the scheme of maintaining state on the server side, while Cookie uses the scheme of maintaining state on the client side. But why can’t you get sessions if you disable cookies? The Session ID is used to determine the server Session corresponding to the current Session, and the Session ID is transmitted through the Cookie. If the Cookie is disabled, the Session ID is lost and the Session cannot be obtained.
Assume that the user closes the Cookie to use the Session, it can be implemented in the following ways:
Set “session.use_trans_sid = 1” in the php.ini configuration file, or enable the “-enable-trans-sid” option at compile time to enable PHP to automatically pass the session ID across pages. Manually pass the Session ID through the URL and hide the form. Save Session IDS in files, databases, etc., and call them manually during page crossing.
70. What is the difference between Spring MVC and Struts?
Different interception mechanisms
Struts2 is class-level interception. An Action is created for each request. In Spring integration, Struts2’s ActionBean injection scope is prototype mode, and the request data is injected into properties via setters and getters. In Struts2, an Action corresponds to a request and response context. Parameters can be received via properties, indicating that property parameters are shared by multiple methods. A Struts2 Action method can correspond to a URL, but its class attributes are shared by all methods, so it cannot be identified by annotations or other means. SpringMVC intercepts methods at the method level. Each method corresponds to a Request context, so the method directly is basically independent and has its own Request and response data. And each method corresponds to a URL at the same time, the transmission of parameters is directly injected into the method, is unique to the method. The results are returned to the framework via ModeMap. In Spring integration, the Controller Bean of SpringMVC defaults to the Singleton, so by default, only one Controller is created for all requests. There are no shared properties, so it is thread safe. If you want to change the default scope, Need to add the @scope annotation to modify. While Struts2 has its own Interceptor mechanism, SpringMVC uses a separate Aop approach, resulting in a larger Struts2 configuration file than SpringMVC.
The underlying framework of struts 2 different Filter (StrutsPrepareAndExecuteFilter) was adopted to realize, for SpringMVC (DispatcherServlet) is realized by using the Servlet. The Filter is initialized after the container is started; Crashed after service stopped, later than Servlet. The Servlet is initialized at call time, before the Filter is called, and destroyed when the service stops.
performance
Struts2 is class-level interception. Each request corresponds to a new instance of an Action, and all property value injections need to be loaded. SpringMVC implements zero configuration, with a singleton bean injection loaded due to SpringMVC’s method-based interception. As a result, SpringMVC is more efficient in development and performance than Struts2.
Configuration aspects Spring MVC and Spring are seamless. This project is also better than Struts2 in terms of management and security.
71. How do I avoid SQL injection?
This function is called in the JSP to check for package invalid characters in the JSP page judgment code, using regular expressions to filter incoming parameter strings
72. What is an XSS attack and how can it be avoided?
XSS attack, also known as CSS, stands for Cross Site Script attack. The principle of XSS attack is that an attacker enters malicious HTML code into a website with XSS vulnerability. When a user browses the website, the HTML code is automatically executed to achieve the purpose of attack. XSS attacks are similar to SQL injection attacks. SQL injection attacks use SQL statements as user input to query, modify, and delete data. In XSS attacks, malicious scripts are inserted to control user browsers and obtain user information. XSS is a common vulnerability in Web applications. XSS is a passive and client-side attack.
The general idea of XSS defense is to filter the input (and URL parameters) and encode the output.
73. What is a CSRF attack and how can it be avoided?
CSRF (Cross-site Request Forgery) is also known as one-click attack or session riding. Generally speaking, the attacker counterfeits the user’s browser request and sends it to the website that the user has authenticated himself to visit, so that the target website receives it and mistakenly thinks it is the user’s real operation and executes the command. Often used to steal accounts, transfer money, send false messages and so on. The attacker takes advantage of the vulnerability of the website to verify the request, the website can confirm that the request is from the user’s browser, but cannot verify whether the request is from the user’s real intention of the operation behavior.
How to avoid:
- Validate the HTTP Referer field
The Referer field in the HTTP header records the source address of the HTTP request. Typically, a request to access a security-restricted page comes from the same site, and if a hacker wants to carry out a CSRF attack on it, he can only construct the request on his own site. Therefore, you can defend against CSRF attacks by validating the Referer value.
- Use captcha
Verification codes are added to key operation pages. After receiving a request, the background checks the verification codes to defend against CSRF. But this approach is not very user friendly.
- Add token to request address and validate
The reason why CSRF attack can be successful is that the hacker can completely forge the user’s request, and all the user authentication information in the request is in the cookie, so the hacker can directly use the user’s own cookie to pass the security authentication without knowing the authentication information. The key to defending against CSRF is to put information in the request that a hacker cannot forge and that does not exist in a cookie. A randomly generated token can be added to the HTTP request as a parameter, and an interceptor can be established on the server side to verify the token. If there is no token in the request or the token content is incorrect, the request may be rejected as a CSRF attack. This is more secure than checking the Referer. Tokens can be generated after the user logs in and placed in the session, and then taken out of the session on each request and compared with the tokens in the request. The difficulty with this approach, however, is how to add tokens to the request as parameters. For GET requests, the token is appended to the request address so that the URL becomes http://url? Csrftoken = tokenvalue. For POST requests, the token is added at the end of the form, adding the token as a parameter to the request.
- Customize and validate properties in HTTP headers
This method also uses the token and validates it. Unlike the previous method, instead of placing the token in the HTTP request as a parameter, it places it in a custom attribute in the HTTP header. With the XMLHttpRequest class, you can add the CSRFToken HTTP header attribute and put the token value into all of the class requests at once. This eliminates the inconvenience of adding the token to the request in the previous method, and the XMLHttpRequest address is not logged in the browser’s address bar, and the token is not leaked to other sites through the Referer.
abnormal
Throws throws 74.
Throws throws. Throws declares all exception information that a method may throw. Throws declares exceptions but does not process them. A throw is a specific type of exception thrown.
75. What is the difference between final, finally and Finalize?
Final can modify classes, variables, and methods. A modifier class means that the class cannot be inherited, a modifier method means that the method cannot be overridden, and a modifier variable means that the variable is a constant and cannot be reassigned. Finally is usually used ina try-catch block. When handling an exception, the method finally is always executed, indicating that the block will be executed regardless of whether an exception occurs. It is used to store code that closes a resource. Finalize is a method belonging to Object class, which is the parent class of all classes. This method is generally called by garbage collector. When we call System gc() method, Finalize () is called by garbage collector to collect garbage.
76. Which part of the try-catch-finally can be omitted?
A: Catch can be omitted
The reason:
More strictly, try is only good for runtime exceptions, and try+catch is good for run-time exceptions + normal exceptions. That is, if you just try a normal exception and don’t catch it, the compilation will fail because the compiler dictates that if you catch a normal exception, you must display the declaration with a catch for further processing. Run-time exceptions are not specified this way at compile time, so a catch can be omitted, and the compiler feels comfortable adding it.
In theory, any code that the compiler looks at is likely to have a problem, so even if you try everything, it’s just a layer on top of what it normally does at runtime. But once you add a try to a piece of code, you explicitly promise the compiler to catch exceptions that the code might throw instead of throwing them up. If it is a normal exception, the compiler requires that it must be caught with a catch for further processing. If there is a runtime exception, catch and discard and +finally sweep, or add a catch catch for further processing.
The addition of finally is a “sweep” processing that takes place whether or not an exception is caught.
77. In try-catch-finally, if a catch returns, finally will be executed?
A: It will be executed before return.
Code Example 1:
/* * Java interview question -- Will the code in finally execute if there is a return statement ina catch? */ public class FinallyDemo2 { public static void main(String[] args) { System.out.println(getInt()); } public static int getInt() { int a = 10; try { System.out.println(a / 0); a = 20; } catch (ArithmeticException e) { a = 30; return a; /* * return a return 30 instead of a; The return path forms a *. But it finds finally after it, so it continues with finally, a=40 * goes back to the previous path again, and returns 30. Once the return path is formed, a here is no longer an A variable. The constant 30 */} finally {a = 40; } // return a; }}Copy the code
Result: 30
Code Example 2:
package com.java_02; /* * Java interview question -- Will the code in finally execute if there is a return statement ina catch? */ public class FinallyDemo2 { public static void main(String[] args) { System.out.println(getInt()); } public static int getInt() { int a = 10; try { System.out.println(a / 0); a = 20; } catch (ArithmeticException e) { a = 30; return a; /* * return a return 30 instead of a; The return path forms a *. But it finds finally after it, so it continues with finally, a=40 * goes back to the previous path again, and returns 30. Once the return path is formed, a here is no longer an A variable. The constant 30 */} finally {a = 40; return a; } // return a; // return a; }}Copy the code
Result: 40
78. What are the common exception classes?
NullPointerException: Thrown when an application attempts to access an empty object. SQLException: An exception that provides information about a database access error or other error. IndexOutOfBoundsException: indicates a sort index (such as an array, a string, or vector) thrown when beyond range. NumberFormatException: Thrown when an application tries to convert a string to a numeric type, but the string cannot be converted to a proper format. FileNotFoundException: Thrown when an attempt to open a file represented by the specified pathname fails. IOException: Throws an I/O exception when it occurs. This class is a generic class for exceptions generated by failed or interrupted I/O operations. ClassCastException: Thrown when an attempt is made to cast an object into a subclass that is not an instance. ArrayStoreException: An exception thrown when attempting to store an object of the wrong type into an array of objects. IllegalArgumentException: An exception thrown to indicate that an invalid or incorrect argument has been passed to a method. ArithmeticException: Throws the exception when the arithmetic condition of the exception is present. For example, an instance of this class is thrown when an integer is “divided by zero”. NegativeArraySizeException: if the application is trying to create an array with negative size, the exception is thrown. NoSuchMethodException: Thrown when a particular method cannot be found. SecurityException: An exception thrown by the security manager to indicate a security violation. UnsupportedOperationException: when does not support the requested operation, throw the exception. RuntimeExceptionRuntimeException: are those that may be in the normal operation of the Java virtual machine exceptions thrown during the period of the superclass.
network
79. What do HTTP response codes 301 and 302 represent? What’s the difference?
A: 301,302 are HTTP state codes that represent a URL transfer.
The difference between:
301 redirect: 301 stands for Permanently Moved. Redirect: 302 stands for Temporarily Moved (Temporarily Moved).
80. What’s the difference between forward and redirect?
Forward and Redirect represent two request forwarding modes: direct and indirect.
In Forward mode, the client and browser only send a request once. A Servlet, HTML, JSP, or other information resource responds to the request by a second information resource. In request object, the saved object is shared by each information resource.
Redirect refers to two HTTP requests. The server responds to the first request by directing the browser to another URL.
Take A popular example: direct forwarding is equivalent to: “A borrows money from B, B says no, B borrows money from C, and the message will be passed to A if it borrows or fails”; Indirect forwarding is equivalent to: “A borrows money from B, B says no, and A borrows money from C”.
81. Describe the differences between TCP and UDP.
TCP connection-oriented (for example, dial up to establish a connection before making a phone call); UDP is connectionless, that is, no connection is required before sending data. TCP provides reliable services. That is to say, data transmitted through the TCP connection is error-free, not lost, not repeated, and in order to arrive; UDP does its best to deliver, i.e. reliable delivery is not guaranteed. Tcp realizes reliable transmission through checksum, retransmission control, serial number identification, sliding window and acknowledgement. For example, when the packet is lost, the sequence control can also be carried out for the subcontracting out of order. UDP has better real-time, higher work efficiency than TCP, suitable for high-speed transmission and real-time communication or broadcast communication. Each TCP connection can be point-to-point only. UDP supports one-to-one, one-to-many, many-to-one and many-to-many interactive communication. TCP requires more system resources, while UDP requires less.
82. Why does TCP require three handshakes? Why is that?
To ensure reliable data transmission, both parties of the TCP protocol must maintain a serial number to identify which packets have been received. The three-way handshake is a necessary step for communication parties to inform each other of the start sequence number and confirm that the other party has received the start sequence number.
In the case of two handshakes, at most only the initial sequence number of the connection initiator can be confirmed, and the sequence number selected by the other party cannot be confirmed.
How does TCP sticky packet come into being?
①. Sticky packets are generated by the sender
The client and server that use THE TCP protocol to transmit data often maintain a long connection state (there is no sticky packet for sending data once a connection). The two sides can transmit data continuously when the connection is constantly open. However, when the number of packets sent is too small, TCP by default enables the Nagle algorithm to merge these smaller packets and send them (buffer data sending is a heap pressure process). This merge takes place in the send buffer, which means the data is sent out in a sticky packet state.
②. Sticky packets are generated on the receiver
When the receiver uses TCP protocol to receive data, the process is as follows: data to the receiver, from the bottom of the network model to the transmission layer, the transmission layer TCP protocol processing is to put it into the receiving buffer, and then the application layer to actively obtain (C language recv, read and other functions); The problem is that the data reading function we call in the program can’t take the data out of the buffer in time, and the next data comes and part of it is put into the end of the buffer, and when we read the data, it is a sticky packet. (Data loading speed > data loading speed of the application layer)
84. What are the OSI seven-tier models?
Application layer: An interface between network services and end users. Presentation layer: data representation, security, compression. Session layer: establishes, manages, and terminates sessions. Transport layer: defines the protocol port numbers for transmitting data, as well as flow control and error-checking. Network layer: logical address is addressed to realize path selection between different networks. Data link layer: establish logical connection, hardware address addressing, error checking and other functions. Physical layer: Establishes, maintains, and disconnects physical connections.
85. What are the differences between GET and POST requests?
GET is harmless when the browser falls back, while POST resubmits the request. The URL generated by GET can be bookmarked, but not by POST. GET requests are actively cached by browsers, whereas POST requests are not, unless set manually. GET requests can only be url encoded, while POST supports multiple encoding methods. GET request parameters are retained in browser history, while parameters in POST are not. GET requests pass parameters in the URL with length limits, whereas POST does not. GET accepts only ASCII characters for the data type of the argument, while POST has no restrictions. GET is less secure than POST because parameters are exposed directly to the URL and therefore cannot be used to pass sensitive information. The GET argument is passed through the URL, and the POST is placed in the Request body.
86. How to achieve cross-domain?
Mode 1: The ping or script label of the image is cross-domain
Pings are often used to track the number of times a user clicks on a page or is exposed to a dynamic AD. Script tags can get data from other sources, which is what JSONP relies on.
Mode 2: JSONP cross-domain
JSONP (JSON with Padding) is a “usage mode” of JSON that allows web pages to request data from other domains. According to the XmlHttpRequest object affected by the same origin policy, and exploited
Method 3: CORS
Cross-origin Resource Sharing (CORS) is a specification of browser technology. It provides a method for Web services to send sandbox scripts from different domains to avoid the same Origin policy of browsers and ensure secure cross-domain data transfer. Modern browsers use CORS in API containers such as XMLHttpRequest to reduce HTTP request risk sources. Unlike JSONP, CORS supports HTTP requirements in addition to GET requirements. The server generally needs to add one or more of the following response headers:
Access-Control-Allow-Origin: *Access-Control-Allow-Methods: POST, GET, OPTIONS
Access-Control-Allow-Headers: X-PINGOTHER, Content-TypeAccess-Control-Max-Age: 86400
By default, cross-domain requests do not carry Cookie information. To carry Cookie information, set the following parameters:
Access-control-allow-credentials: true // Ajax sets withCredentials to true
Method 4: window.name+iframe
Window.name works by loading a cross-domain HTML file in iframe (general dynamic create I). The HTML file then assigns the string content passed to the requester to window.name. The requester can then retrieve the window.name value as a response.
Cross-domain capability of iframe tags; The ability of the window.name property value to persist after the document is refreshed (and the maximum allowed is about 2M).
Each iframe has a window wrapped around it, and this window is a child of top Window. The contentWindow property returns the element’s Window object. You can use the Window object to access the iframe document and its internal DOM.
<! -- The following ports are represented by port 10000: domainA 10001: domainB --> <! -- localhost:10000 --> <script> var iframe = document.createElement('iframe'); iframe.style.display = 'none'; Var state = 0; / / prevent page refresh infinite iframe. Onload = function () {if (state = = = 1) {the console. The log (JSON. Parse (iframe. ContentWindow. Name)); / / remove create iframe iframe. ContentWindow. Document. Write (' '); iframe.contentWindow.close(); document.body.removeChild(iframe); } else if(state === 0) { state = 1; // Load complete, point to current domain, // Blocked a frame with origin "http://localhost:10000" from accessing a cross-origin frame. iframe.contentWindow.location = 'http://localhost:10000/proxy.html'; }}; iframe.src = 'http://localhost:10001'; document.body.appendChild(iframe); </script> <! -- localhost:10001 --> <! DOCTYPE html> ... <script> window.name = JSON.stringify({a: 1, b: 2}); </script> </html>Copy the code
Method 5: window.postmessage ()
New HTML5 feature that can be used to send messages to all other Window objects. It should be noted that we must ensure that all scripts are executed before sending MessageEvent. If it is called during function execution, subsequent functions will timeout and cannot be executed.
The following code implements cross-domain storage localStorage
<! -- The following ports are represented by port 10000: domainA 10001: domainB --> <! -- localhost:10000 --> <iframe src="http://localhost:10001/msg.html" name="myPostMessage" style="display:none;" > </iframe> <script> function main() { LSsetItem('test', 'Test: ' + new Date()); LSgetItem('test', function(value) { console.log('value: ' + value); }); LSremoveItem('test'); } var callbacks = {}; window.addEventListener('message', function(event) { if (event.source === frames['myPostMessage']) { console.log(event) var data = /^#localStorage#(\d+)(null)? #([\S\s]*)/.exec(event.data); if (data) { if (callbacks[data[1]]) { callbacks[data[1]](data[2] === 'null' ? null : data[3]); } delete callbacks[data[1]]; } } }, false); var domain = '*'; Function LSsetItem(key, value) {var obj = {setItem: key, value: value}; frames['myPostMessage'].postMessage(JSON.stringify(obj), domain); Function LSgetItem(key, callback) {var identifier = new Date().getTime(); var obj = { identifier: identifier, getItem: key }; callbacks[identifier] = callback; frames['myPostMessage'].postMessage(JSON.stringify(obj), domain); } function LSremoveItem(key) {var obj = {removeItem: key}; frames['myPostMessage'].postMessage(JSON.stringify(obj), domain); } </script> <! -- localhost:10001 --> <script> window.addEventListener('message', function(event) { console.log('Receiver debugging', event); if (event.origin == 'http://localhost:10000') { var data = JSON.parse(event.data); if ('setItem' in data) { localStorage.setItem(data.setItem, data.value); } else if ('getItem' in data) { var gotItem = localStorage.getItem(data.getItem); event.source.postMessage( '#localStorage#' + data.identifier + (gotItem === null ? 'null#' : '#' + gotItem), event.origin ); } else if ('removeItem' in data) { localStorage.removeItem(data.removeItem); } } }, false); </script>Copy the code
Note that Safari will return an error:
Blocked a frame with origin “http://localhost:10001” from accessing a frame with origin “http://localhost:10000“. Protocols, domains, and ports must match.
To avoid this error, disable cross-domain restrictions in Safari by checking the Development menu ==>. Or you can only implement it as a server-side dump, since Safari only supports CORS cross-domain requests by default.
Method 6: Modify document.domain across subdomains
Prerequisite: Both domain names must belong to the same base domain name! And the protocol used, the port must be consistent, otherwise document.domain can not be used for cross-domain, so only cross subdomain
In the root domain scope, it is possible to set the value of the domain property to its upper domain. For example, in the aaa.xxx.com domain, you can set domain to xxx.com but cannot set domain to XXX.org or com. Two domains exist: aaa.xxx.com and bbB.xxx.com. The page embedded in BBB under AAA cannot operate JS of BBB under AAA because its document.name is inconsistent. Document. name = ‘xxx.com’; Set consistency to achieve mutual access.
Method 7: WebSocket
WebSocket Protocol is a new protocol for HTML5. It implements full duplex browser-server communication while allowing cross-domain communication, and is a great implementation of Server Push technology. For related articles, see WebSocket, websocket-sockjs
Note that WebSocket objects do not support DOM level 2 event listeners and must define each event individually using DOM level 0 syntax.
Mode 8: Agent
The same origin policy is restricted on the browser side and can be resolved on the server side
DomainA client (browser) ==> DomainA server ==> DomainB server ==> DomainA client (browser)
87. How does JSONP work?
Jsonp (json+padding) is used to dynamically create a script tag, using the SRC attribute of the script tag to retrieve javascript scripts in any domain. Through this feature (or vulnerability), the server does not return the JSON format, but returns a javascript code that calls a function. The call is made in SRC, which is cross-domain.
Design patterns
88. Tell me about a design pattern you are familiar with.
The singleton pattern
To put it simply, there is only one instance of a class in an application, and you can’t go to new because constructors are private and usually get their instances through the getInstance() method.
The return value of getInstance() is a reference to an object, not a new instance, so don’t mistake it for multiple objects. The singleton pattern is also easy to implement, so just look at the demo
public class Singleton {
private static Singleton singleton;
private Singleton() {
}
public static Singleton getInstance() { if (singleton == null) { singleton = new Singleton(); } return singleton; }}
As is my custom, I’m going to comment it all out in case you don’t understand it, but this code is so simple that I didn’t comment it, so if you don’t understand a few lines of code, you can go to sleep and read my blog when you wake up and maybe you’ll understand it.
The above is the most basic method, also known as lazy writing (thread unsafe). Here are a few more singletons:
Lazy writing (thread-safe)
public class Singleton { private static Singleton instance; private Singleton (){} public static synchronized Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; }}Copy the code
Hanhan style
public class Singleton { private static Singleton instance = new Singleton(); private Singleton (){} public static Singleton getInstance() { return instance; }}Copy the code
Static inner class
public class Singleton { private static class SingletonHolder { private static final Singleton INSTANCE = new Singleton(); } private Singleton (){} public static final Singleton getInstance() { return SingletonHolder.INSTANCE; }}Copy the code
The enumeration
public enum Singleton {
INSTANCE;
public void whateverMethod() {
}
}
Copy the code
This approach, championed by Effective Java author Josh Bloch, not only avoids multithreaded synchronization problems, but also prevents deserialization from recreating new objects, which is a strong barrier. However, since the enum feature was added in 1.5, It feels strange to write in this way. Double check lock
public class Singleton { private volatile static Singleton singleton; private Singleton (){} public static Singleton getSingleton() { if (singleton == null) { synchronized (Singleton.class) { if (singleton == null) { singleton = new Singleton(); } } } return singleton; }}Copy the code
Conclusion: I personally prefer static inner class writing and hungry Chinese writing. In fact, these two methods can handle most cases. There are other ways to write it, but it depends on your business needs.
Observer model
A one-to-many dependency between objects in which all dependent objects are notified and automatically updated when an object’s state changes.
Observer pattern UML diagrams
People who can’t understand the picture come here with a small bench to give you an example: Suppose there are three people, Mei (female, 22), Xiao Wang and Xiao Li. Xiao Mei is very beautiful. Xiao Wang and Xiao Li are two programmers who keep an eye on xiao Mei’s every move. One day, Mei said, “Who will accompany me to play games?” This sentence was heard by Xiao Wang and Xiao Li, the result was very happy, Dally, in a short time, Xiao Wang rushed to the door of Xiao Mei, here, Xiao Mei is the observer, Xiao Wang and Xiao Li are the observers, the observer sent a message, and then the observers process accordingly, see the code:
Public interface Person {void getMessage(String s); public interface Person {void getMessage(String s); }Copy the code
This interface is equivalent to the phone numbers of Xiao Wang and Xiao Li. When Xiao Mei sends a notice, she will call getMessage. Dialing the phone is the call interface
Public class implements Person {private String name = "implements "; Public LaoWang() {} @override public void getMessage(String s) {system.out.println (name + "); }} public implements Person {private String name = "implements "; Public LaoLi() {} @override public void getMessage(String s) {system.out.println (String s); }}Copy the code
The code is very simple, let’s look at mei’s code:
public class XiaoMei { List<Person> list = new ArrayList<Person>(); public XiaoMei(){ } public void addPerson(Person person){ list.add(person); } public void notifyPerson() {for(Person Person :list){notifyPerson() {Person. Whoever comes first can play games with me!" ); }}}Copy the code
Let’s write a test class to see if this is true
public class Test { public static void main(String[] args) { XiaoMei xiao_mei = new XiaoMei(); LaoWang lao_wang = new LaoWang(); LaoLi lao_li = new LaoLi(); // Xiao Wang and Xiao Li registered xiao_mei.addperson (lao_wang); xiao_mei.addPerson(lao_li); // Xiao Mei sends notifications to Xiao Wang and Xiao Li. Xiao_mei.notifyperson (); }}Copy the code
Perfect ~
Decorator pattern
The existing business logic is further encapsulated to add additional functions. For example, THE IO flow in Java uses decorator mode. When users use it, they can assemble it arbitrarily to achieve their desired effect. For example, I want to eat a sandwich. First, I need a big sausage. I like to eat cream. So how do we write the code? First, we need to write a Food class that all other foods inherit from. Look at the code:
public class Food {
private String food_name;
public Food() {
}
public Food(String food_name) {
this.food_name = food_name;
}
public String make() {
return food_name;
};
}
Copy the code
The code is so simple that I won’t explain it, and then we’ll write some subclasses to inherit it:
Public class Bread extends Food {private Food basic_food; public Bread(Food basic_food) { this.basic_food = basic_food; } public String make() {return basic_food. Make ()+"+ bread "; }} public extends Food {private Food basic_food; public Cream(Food basic_food) { this.basic_food = basic_food; } public String make() {return basic_food. Make ()+"+ butter "; }} public class Vegetable extends Food {private Food basic_food; public Vegetable(Food basic_food) { this.basic_food = basic_food; } public String make() {return basic_food. Make ()+"+ vegetable "; }}Copy the code
The constructor passes in a parameter of type Food, and then adds some logic to the make method. If you still don’t understand why this is the case, just look at my Test class
public class Test { public static void main(String[] args) { Food food = new Bread(new Vegetable(new Cream(new The Food (" sausage ")))); System.out.println(food.make()); }}Copy the code
See no one layer encapsulation, away from you, we see: the most I new a sausage inside, outside the sausage I wrapped with a layer of cream, the cream of the outside and I add a layer of vegetables, bread, is the most I put outside is very image, ha ha ~ this design pattern is just like a real life touch, understand? So let’s look at the results
The results
One sandwich is ready
Adapter mode
Connecting two very different things together, like a transformer in real life. Suppose a mobile phone charger needs a voltage of 20V, but the normal voltage is 220V, this time need a transformer, 220V voltage into 20V voltage, so that the transformer will be 20V voltage and mobile phone.
public class Test { public static void main(String[] args) { Phone phone = new Phone(); VoltageAdapter adapter = new VoltageAdapter(); phone.setAdapter(adapter); phone.charge(); Class Phone {public static final int V = 220; // Normal voltage 220v, is a constant private VoltageAdapter adapter; Public void charge() {adapter.changevoltage (); } public void setAdapter(VoltageAdapter adapter) { this.adapter = adapter; Public void changeVoltage() {system.out.println (" charging..."); ); Println (" original voltage: "+ Phone.V + "V"); Println (" voltage after transformer conversion :" + (phle.v-200) + "V"); }}Copy the code
Factory Pattern Simple factory pattern: One abstract interface, implementation classes for multiple abstract interfaces, and one factory class for instantiating the abstract interface
// abstract class Car {public void run(); public void stop(); } // Class Benz implements Car {public void run() {system.out.println ("Benz implements Car... ); } public void stop() {system.out.println ("Benz stopped... ); }} class Ford implements Car {public void run() {system.out.println ("Ford implements Car... ); } public void stop() {system.out.println ("Ford stopped... ); Public static Car getCarInstance(String type) {Car c = null; if ("Benz".equals(type)) { c = new Benz(); } if ("Ford".equals(type)) { c = new Ford(); } return c; } } public class Test { public static void main(String[] args) { Car c = Factory.getCarInstance("Benz"); if (c ! = null) { c.run(); c.stop(); } else {system.out.println (" can't make this car... ") ); }}}Copy the code
Factory method Pattern: There are four roles: Abstract Factory pattern, Concrete factory pattern, Abstract product pattern, and Concrete product pattern. Instead of instantiating a concrete product by a factory class, the product is instantiated by a subclass of the abstract factory
Public interface Moveable {void run(); Public class Plane implements Moveable {@override public void run() {system.out.println (" Plane....") ); } } public class Broom implements Moveable { @Override public void run() { System.out.println("broom....." ); }} Public Abstract Class VehicleFactory {abstract Moveable create(); } public class PlaneFactory extends VehicleFactory {public Moveable create() {return new Plane(); } } public class BroomFactory extends VehicleFactory { public Moveable create() { return new Broom(); Public class Test {public static void main(String[] args) {VehicleFactory factory = new BroomFactory(); Moveable m = factory.create(); m.run(); }}Copy the code
Abstract Factory pattern: Unlike the factory method pattern, where the factory produces a single product, the abstract factory pattern produces multiple products
Public Abstract class AbstractFactory {public Abstract Vehicle createVehicle(); public abstract Weapon createWeapon(); public abstract Food createFood(); } // Concrete factory class, where Food,Vehicle, Weapon are abstract classes, public class DefaultFactory extends AbstractFactory{ @Override public Food createFood() { return new Apple(); } @Override public Vehicle createVehicle() { return new Car(); } @Override public Weapon createWeapon() { return new AK47(); Public class Test {public static void main(String[] args) {AbstractFactory f = new DefaultFactory(); Vehicle v = f.createVehicle(); v.run(); Weapon w = f.createWeapon(); w.shoot(); Food a = f.createFood(); a.printName(); }}Copy the code
Proxy mode
There are two types, static proxy and dynamic proxy. Let’s talk about static agents. I’m not going to talk about a lot of theoretical stuff, and even if I did, you wouldn’t understand it. What real role, abstract role, proxy role, delegate role… It’s a mess. I can’t read it. When I was learning the agent mode, I went to the Internet and looked up a lot of information. When I opened the links, they were basically for you to analyze what roles there were. There were a lot of theories, which seemed very laborious. Let’s not talk about anything. Let’s talk about real life. (Note: I’m not denying theoretical knowledge here, I just think that sometimes theoretical knowledge is hard to understand, you are here to learn, not to nitpick.) After a certain age, we have to get married, and it is a very troublesome thing to get married (including those who are pushed by their parents). Rich family may look for master of ceremonies to preside over the wedding, appear lively, foreign atmosphere ~ well, now the business of wedding celebration company came, we only need to give money, wedding celebration company can help us arrange a whole set of wedding process. The process looks something like this: the family urge marriage – > the families of men and women both parties agreed to marry the day of the zodiac – > looking for a company of wedding – > at the appointed time for the wedding ceremony – > after marriage Wedding how the company intends to make the wedding program, after finished the wedding wedding company will do, we know nothing… Don’t worry, it’s not a black agent, we just give people the money, they will do the job for us. So, the wedding agency here is the proxy role, now you see what the proxy role is.
See the code implementation:
Public interface ProxyInterface {// Marry (); // Public interface ProxyInterface {// Marry (); Void eat(); void eat(); //void shit(); }Copy the code
Civilized society, acting to have a meal, acting shit what I will not write, social weathering ~ ~ ~ can understand good, we look at the code of the wedding company:
public class WeddingCompany implements ProxyInterface { private ProxyInterface proxyInterface; public WeddingCompany(ProxyInterface proxyInterface) { this.proxyInterface = proxyInterface; } @override public void marry() {system.out.println (" we are married "); System.out.println(" We are making preparations for marriage "); System.out.println("...") ); System.out.println(" Gift purchase...") ); System.out.println("...") ); System.out.println(" I can get married "); proxyInterface.marry(); System.out.println(" After the marriage, we need to do follow-up processing, you can go home, the rest of our company to do "); }}Copy the code
See, the wedding company needs to do a lot of things, let’s look at the marriage family code:
Public class NormalHome implements ProxyInterface{@override public void marry() {system.out.println (" we are married ~ "); }}Copy the code
This has been very obvious, the marriage family only need to get married, and the wedding company to take care of everything, before and after the things are the wedding company to do, I heard that now the wedding company is very profitable, this is the reason, the work is much, can not make money? Let’s look at the test class code:
public class Test { public static void main(String[] args) { ProxyInterface proxyInterface = new WeddingCompany(new NormalHome()); proxyInterface.marry(); }}Copy the code
The running results are as follows:
89. What is the difference between a simple factory and an abstract factory?
Simple Factory model:
The pattern itself is simple and can be used in simpler business situations. Typically used for small projects or where specific products rarely extend (so that the factory class doesn’t change as often).
It consists of three roles:
Factory roles: This is the core of this model, which contains certain business logic and judgment logic. Specific factory products are generated according to different logic. Take the Driver class in this example. Abstract product roles: These are typically inherited superclasses or interfaces implemented by the concrete product. Implemented by an interface or abstract class. Take the Car interface in this example. Concrete product roles: The objects created by the factory class are instances of this role. It is implemented in Java by a concrete class, such as the Benz, Bmw classes in the example.
To use the class diagram to clearly show the relationship between them:
Abstract Factory Pattern: Let’s start with what a product family is: a family of functionally related products located in different product hierarchies.
BmwCar and BenzCar in the figure are two product trees (product hierarchy); BenzSportsCar and BmwSportsCar as shown in the figure are a product family. They can all fit into the sports car family, so the function is related. Similarly BmwBussinessCar and BenzBusinessCar are also a product family.
It differs from the factory method pattern, so to speak, in the level of complexity required to create objects. And the abstract factory pattern is the most abstract and generic of the three. The purpose of the abstract factory pattern is to provide clients with an interface to create product objects in multiple product families.
In addition, using the abstract factory pattern requires the following conditions:
There are multiple product families in the system, and the system can only consume one of the products that belong to the same product family for its use.
Let’s take a look at the roles of the abstract factory pattern (identical to the factory approach) :
Abstract Factory role: This is the core of the factory method pattern and is application-independent. Is an interface that a specific factory role must implement or a parent class that must inherit. In Java it is implemented by abstract classes or interfaces. Concrete factory role: It contains code related to specific business logic. Objects called by the application to create corresponding product-specific objects. In Java it is implemented by concrete classes. Abstract product role: It is the parent class or interface that the concrete product inherits. In Java, there are usually abstract classes or interfaces. Specific product roles: Objects created by specific factory roles are instances of this role. Implemented in Java by concrete classes.
Spring / Spring MVC
90. Why use Spring?
1. Introduction
Purpose: To solve the complexity of enterprise application development features: use basic Javabeans instead of EJBs, and provide more enterprise application functionality: any Java application
In simple terms, Spring is a lightweight Inversion of Control (IoC) and AOP oriented container framework.
2. Light weight
Spring is lightweight in terms of size and overhead. The full Spring framework can be distributed in a JAR file with a size of just over 1MB. And the processing overhead required by Spring is trivial. In addition, Spring is non-intrusive: Typically, objects in Spring applications do not depend on Spring specific classes.
3. Inversion of control
Spring promotes loose coupling through a technique called inversion of control (IoC). When IoC is applied, other objects that an object depends on are passed in passively, rather than being created or found by the object itself. You can think of IoC as the opposite of JNDI — instead of an object looking up a dependency from the container, the container actively passes the dependency to the object at initialization without waiting for the object to request it.
Step 4 Face the section
Spring provides rich support for faceted programming, allowing cohesive development by separating application business logic from system-level services such as auditing and transaction management. Application objects just do what they’re supposed to do — complete the business logic — and that’s it. They are not responsible for (or even aware of) other system-level concerns, such as logging or transaction support.
5. A container
Spring includes and manages the configuration and life cycle of application objects. It is a container in the sense that you can configure how each of your beans is created — based on a configurable prototype, Your bean can create a single instance or generate a new instance every time it is needed — and how they relate to each other. However, Spring should not be confused with traditional heavyweight EJB containers, which are often large and unwieldy and difficult to use.
Framework of 6.
Spring can configure and compose simple components into complex applications. In Spring, application objects are combined declaratively, typically in an XML file. Spring also provides a lot of basic functionality (transaction management, persistence framework integration, and so on), leaving the development of application logic up to you.
All of these Spring features enable you to write cleaner, more manageable, and more testable code. They also provide basic support for various modules in Spring.
Explain what AOP is?
AOP (aspect-oriented Programming, aspect-oriented Programming), can be said to be OOP (Object-oriented Programming, object-oriented Programming) complement and perfect. OOP introduces concepts such as encapsulation, inheritance, and polymorphism to build an object hierarchy that simulates a collection of common behaviors. OOP is helpless when we need to introduce common behavior to discrete objects. That is, OOP allows you to define top-to-bottom relationships, but not left-to-right relationships. For example, the logging function. Logging code tends to be spread horizontally across all object hierarchies, regardless of the core functionality of the object to which it is spread. The same is true for other types of code, such as security, exception handling, and transparency persistence. This scattering of extraneous code is called cross-cutting code, and in OOP design it leads to a lot of code duplication, which is not conducive to reuse of modules.
AOP, on the other hand, uses a technique called “crosscutting” to peel apart the insides of wrapped objects and encapsulate common behavior that affects multiple classes into a reusable module called “Aspect,” or Aspect. The so-called “aspect”, simply speaking, is to encapsulate the logic or responsibility that has nothing to do with business, but is called by business modules together, so as to reduce the repetitive code of the system, reduce the degree of coupling between modules, and facilitate the future operability and maintainability. AOP represents a horizontal relationship, if the “object” is a hollow cylinder, which encapsulates the properties and behavior of the object; Aspect-oriented programming, then, is like a sharp knife, cutting open these hollow cylinders to get information inside them. And the cut surface is the so-called “aspect”. Then, with a masterful hand, it restored the cut surfaces without leaving a trace.
Using “crosscutting” techniques, AOP divides a software system into two parts: core concerns and crosscutting concerns. The main flow of business processing is the core concern, and the less relevant part is the crosscutting concern. One of the things about crosscutting concerns is that they often occur at multiple points of the core concern, and they are basically similar everywhere. Such as permission authentication, logging, and transaction processing. Aop’s role is to separate the various concerns in a system, separating core concerns from crosscutting concerns. As Adam Magee, senior solution architect at Avanade, says, the core idea of AOP is to “separate the business logic in your application from the generic services that support it.”
Explain what ioc is.
IOC is an Inversion of Control, which most books translate as “Inversion of Control.”
The concept of IOC was first introduced in 1996 by Michael Mattson in an article exploring object-oriented frameworks. For the basic idea of object-oriented design and programming, we have talked a lot, in front of the needless, is simply the complex system is decomposed into mutual cooperation object, the object class by encapsulating, internal implementation external is transparent, thus reducing the complexity of problem solving, flexible and can be reused and expanded.
IOC theory puts forward a general idea like this: to achieve decoupling between dependent objects with the help of a “third party”. The diagram below:
You see, due to the introduction of the middle position of the “third party”, namely the IOC container, makes A, B, C, D the four objects without coupling, gear transmission between all rely on the “third party”, all turned over control of all objects to “third party” the IOC container, so the IOC container is the key to the core of the whole system, It acts as a kind of “glue” that binds all the objects in the system together. Without this “glue”, objects lose contact with each other, which is why some people refer to the IOC container as the “glue”. Let’s do another experiment: remove the IOC container in the middle of the image above and look at the system again:
The picture we’re looking at right now is all we need to do to implement the whole system. At this point, objects A, B, C, AND D are no longer coupled to each other, so that when you implement A, you do not need to consider B, C, and D at all, and the dependency between objects has been reduced to the lowest degree. So what a wonderful thing it would be for system development if an IOC container could be implemented, and everyone involved could just implement their own classes, no relation to anyone else!
Why is inversion of control (IOC) so called? Let’s compare:
Before the software system introduced IOC container, as shown in Figure 1, object A depends on object B, so when object A is initialized or running to A certain point, it must take the initiative to create object B or use the already created object B. Whether you create or use object B, you have control.
After the introduction of IOC container into the software system, this situation completely changes. As shown in Figure 3, due to the addition of IOC container, object A and object B lose direct contact. Therefore, when object A runs and needs object B, IOC container will take the initiative to create an object B and inject it into the place where object A needs it.
The process by which object A acquires dependent object B is changed from active to passive, and control is reversed, hence the name “inversion of control”.
93. What are the main modules of Spring?
The Spring framework has so far integrated more than 20 modules. These modules are divided into core containers, data access/integration, Web, AOP (faceted programming), tools, messaging, and test modules as shown below.
What are the common injection methods in Spring?
Spring implements IOC (Inversion of Control) through DI (dependency injection). There are three main injection methods commonly used:
Constructor injection Setters inject annotation-based injection
95. Are beans in Spring thread-safe?
Whether the beans in the Spring container are thread-safe or not, the container itself does not provide a thread-safe policy for beans, so it can be said that the beans in the Spring container do not have thread-safe features, but the specific scope of beans should be combined to study.
96. How many scopes does Spring support for beans?
When you create a Bean instance through the Spring container, you can not only complete the instantiation of the Bean instance, but also specify a specific scope for the Bean. Spring supports the following five scopes:
Singleton: singleton pattern. In the entire Spring IoC container, the Bean defined using singleton will have only one instance prototype: In prototype mode, each time a prototype-defined Bean is retrieved from the container’s getBean method, a new Bean instance request is generated: For each HTTP request, a new instance of the Bean defined using request will be created, meaning that a different Bean instance will be created for each HTTP request. This scope is valid only if Spring is used in a Web application session: for each HTTP session, a new instance is generated using the session-defined Bean milk. Again, this scope is valid only if Spring is used in a Web application globalSession: for each global HTTP Session, a new instance is generated for the Bean defined using the Session. Typically, this is valid only when the portlet context is used. Again, this scope is only valid if Spring is used in a Web application
Singleton and Prototype are two commonly used scopes. For singleton-scoped beans, the same instance will be obtained each time the Bean is requested. The container is responsible for tracking the state of the Bean instance and maintaining the lifecycle behavior of the Bean instance. If a Bean is set to the Prototype scope, Spring creates a new Bean instance each time the program requests a Bean with that ID and returns it to the program. In this case, the Spring container simply creates the Bean instance using the new keyword, and once it has been created, the container does not track the instance nor maintain the state of the Bean instance.
Spring uses the Singleton scope by default if the Bean’s scope is not specified. Java When creating a Java instance, you need to apply for memory. When an instance is destroyed, garbage collection needs to be done, which adds overhead to the system. As a result, the prototype scoped Bean is expensive to create and destroy. Instances of singleton-scoped beans, once created, can be reused. Therefore, avoid setting beans to the Prototype scope unless necessary.
97. What are the methods for Spring to automate bean assembly?
The Spring container is responsible for creating the beans in the application and coordinating the relationships between these objects by ID. As developers, we need to tell Spring which beans to create and how to assemble them together.
There are two ways to assemble beans in Spring:
Implicit bean discovery mechanisms and auto-assembly are configured for display in Java code or XML
Of course, these methods can also be used together.
What are the ways in which Spring transactions are implemented?
Programmatic transaction management is the only option for POJO-based applications. We need to call beginTransaction(), COMMIT (), rollback() and other transaction management-related methods in our code, which is called programmatic transaction management. Based on TransactionProxyFactoryBean declarative transaction management @ the declarative transaction management of Transactional aspectj-based AOP configuration issues
99. What about Transaction isolation in Spring?
The transaction isolation level refers to the degree to which data changes made by one transaction are isolated from those made by another parallel transaction. When multiple transactions access the same data simultaneously, the following problems may occur if the necessary isolation mechanisms are not in place:
Dirty read: a transaction reads uncommitted update data from another transaction. Phantom read: For example, the first transaction modifies the data in a table, such as the modification involves “all rows” in the table. At the same time, the second transaction also modifies the data in the table by inserting a “new row” into the table. Then, as if in an illusion, a user operating on the first transaction will discover that there are still unmodified rows in the table. Unrepeatable reads: For example, if two identical SELECT statements are executed in the same transaction, but no DDL statements are executed in the same transaction, the results are inconsistent. This is called unrepeatable reads.
100. What about the Spring MVC workflow?
Spring MVC runtime flow chart:
Spring running process description:
- The user sends a request to the server, which is captured by the Spring front-end control Servelt DispatcherServlet.
- The DispatcherServlet parses the request URL to get the request resource Identifier (URI). Then, according to the URI, HandlerMapping is called to obtain all the related objects (including the Handler object and the interceptor corresponding to the Handler object) configured by the Handler. Finally, HandlerExecutionChain object is returned.
- The DispatcherServlet selects an appropriate HandlerAdapter based on the Handler obtained. (Note: If the HandlerAdapter is successfully obtained, execution of the interceptor’s preHandler(…) begins at this point.) Methods)
- Extract the model data from the Request, populate the Handler entry parameter, and start Handler (Controller). Depending on your configuration, Spring will do some extra work for you during the entry process to populate the Handler:
HttpMessageConveter: Converts the request message (such as Json and XML data) to an object, and converts the object to the specified response information. Data Conversion: Converts the request message. Data conversion, such as String to Integer or Double, radical: Formats the request message. Data validation, such as converting a string to a formatted number or a formatted date: Verifies the validity of the data (length, format, etc.) and stores the validation result in BindingResult or Error
- When Handler completes execution, a ModelAndView object is returned to the DispatcherServlet;
- Based on the returned ModelAndView, select a suitable ViewResolver (must be a ViewResolver registered in the Spring container) and return it to the DispatcherServlet.
- ViewResolver combines Model and View to render the View;
- Render results are returned to the client.
101. What components does Spring MVC have?
The core components of Spring MVC:
DispatcherServlet: central Controller that forwards requests to specific control class Controller: Controller that handles requests HandlerMapping: ModelAndView: the data returned by the service layer and the encapsulation class of the view layer ViewResolver: the ViewResolver resolves the specific view Interceptors: Interceptor, which intercepts the request we define and then does the processing
102. What does @requestMapping do?
RequestMapping is an annotation to handle request address mapping, which can be used on a class or method. Used on a class, this address is used as the parent path for all methods in the class that respond to requests.
RequestMapping annotations have six attributes, which we’ll break down into three categories.
The value and method:
Value: Specifies the actual address of the request, which can be the URI Template pattern (described below). Method: Specifies the request method type, such as GET, POST, PUT, and DELETE.
Consumes, produces
Consumes: Specifies the content-types that handle requests, for example, application/ JSON or text/ HTML. Produces: Specifies the content type returned only if the specified type is in the (Accept) type in the Request header.
Params, headers
Params: Specifies that the request must contain some parameter values for this method to process. Headers: Specifies that the request must contain some specified header value before the method can process the request.
103. What does @autowired do?
blog.csdn.net/u013257679/article/details/52295106
Spring Boot / Spring Cloud
104. What is Spring Boot?
In the big family of Spring framework, there are many derivative frameworks, such as Spring, SpringMvc framework, etc. The core content of Spring is inversion of control (IOC) and dependency injection (DI). The so-called inversion of control is not a technology, but an idea. Operationally created in a Spring configuration file, dependency injection means that the Spring container provides resources for an object in the application, such as reference objects, constant data, and so on.
SpringBoot is a framework, a new programming specification, his generation simplifies the use of the framework, the so-called simplification refers to the simplification of the Spring many frameworks required a large number of and tedious configuration files, so SpringBoot is a framework to serve the framework, the scope of service is simplified configuration files.
105. Why Spring Boot?
Spring Boot Makes coding easy Spring Boot makes configuration easy Spring Boot makes deployment easy Spring Boot makes monitoring easy Spring’s shortcomings
106. What is the Spring Boot core configuration file?
Spring Boot provides two common configuration files:
Properties file YML file
107. What are the types of Spring Boot configuration files? What’s the difference?
Spring Boot provides two common configuration files, properties files and YML files. Compared to the properties file, the YML file is younger and has a lot of bugs. Yml uses whitespace to determine hierarchy, which makes configuration files structurally clear, but also breaks hierarchy with tiny whitespace.
108. How can Spring Boot implement hot deployment?
SpringBoot hot deployment can be implemented in two ways:
① Use Spring Loaded
Add the following code to the project:
<build> <plugins> <plugin> <! GroupId </groupId> <artifactId> Spring-boot-maven-plugin </artifactId> <dependencies> <! Spring hot deployment --> <! -- The dependency can't be downloaded here. --> <dependency> <groupId>org. springFramework </groupId> <artifactId>springloaded</artifactId> <version>1.2.6.RELEASE</version> </dependency> </dependencies> </dependencies> </plugins> </build>Copy the code
After adding, you need to use MVN command to run:
Find Edit configurations in your IDEA first and do the following :(click the “+” in the top left corner and then select maven to bring up the right pane. Type in the directive shown in the red underlined area. You can name the directive (here named MvnSpringBootRun).
Click save and the IDEA project will appear in the running part. Click the green arrow to run
(2). Use the spring – the boot – devtools
Add dependencies to project POM files:
<! <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> </dependency>Copy the code
Then: using shift + CTRL + Alt + “/” the shortcut key (IDEA) choose “Registry” and then check the compiler. The automake. Allow. The when. App. Running
109. What is the difference between JPA and Hibernate?
The JPA Java Persistence API, a standard ORM interface for Java EE 5, is also part of the EJB3 specification. Hibernate, a popular ORM framework today, is an implementation of JPA, but its function is a superset of JPA. The relationship between JPA and Hibernate can be simply understood as JPA is the standard interface and Hibernate is the implementation. So how does Hibernate implement this relationship with JPA? Hibernate is mainly implemented through three components, Hibernate – Annotation, Hibernate – EntityManager and Hibernate – Core. Hibernate -annotation is the basis for Hibernate to support annotation configuration. It includes standard JPA annotations as well as Hibernate’s own special annotations. Hibernate -core is the core implementation of Hibernate and provides all the core functions of Hibernate. Hibernate-entity Manager implements standard JPA and can be regarded as an adapter between Hibernate-Core and JPA. It does not directly provide ORM functions, but encapsulates Hibernate-Core and makes Hibernate conform to JPA specifications.
110. What is Spring Cloud?
Literally, Spring Cloud is a framework dedicated to distributed systems and Cloud services.
Spring Cloud is a new member of the entire Spring family and a logical outgrowth of the recent boom in Cloud services.
Spring Cloud provides developers with tools to quickly build common patterns in distributed systems, such as:
Configuration Management service Registration and Discovery Circuit breaker Intelligent Routing Service Invocation Load balancing Micro proxy control bus one-time token Global lock Leadership election Distributed session Cluster status Distributed message……
Using Spring Cloud developers can implement services and applications that implement these patterns right out of the box. These services can run in any environment, including distributed environments, developers’ own laptops, and a variety of hosting platforms.
111. What does the Spring Cloud circuit breaker do?
Hystrix is used in Spring Cloud to implement circuit breakers, which prevent an application from trying to perform an operation multiple times that is likely to fail, allowing it to continue without waiting for recovery or wasting CPU cycles when it is certain that the failure is persistent. Breaker mode also enables the application to detect whether the fault has been resolved, and if the problem appears to have been corrected, the application can try to invoke an operation.
Circuit breakers add stability and flexibility to a system, providing stability while the system recovers from failure and minimizing the impact of this failure on performance. It helps to quickly reject requests for an operation that is likely to fail, rather than waiting for the operation to time out (or not return) to keep the system’s response time. If the breaker raises the time of each state change event, this information can be used to monitor the health of components of the system protected by the breaker, or to alert administrators when the breaker trips to be in the open state.
112. What are the core components of Spring Cloud?
Service discovery — Netflix Eureka
A RESTful service that locates mid-tier services running in an AWS Region. It consists of two components: Eureka server and Eureka client. The Eureka server serves as the service registry server. The Eureka client is a Java client designed to simplify interactions with servers, act as a polling load balancer, and provide failover support for services. Netflix uses a separate client in its production environment that provides weighted load balancing based on traffic, resource utilization, and error status.
2. Customer side load balancing — Netflix Ribbon
The Ribbon provides client-side software load balancing algorithms. The Ribbon client component provides a comprehensive set of configuration options, such as connection timeout, retry, retry algorithm, and more. The Ribbon comes with pluggable, customizable load balancing components.
③ Circuit breaker — Netflix Hystrix
A circuit breaker prevents an application from trying multiple times to perform an operation that is likely to fail, allowing it to continue without waiting for recovery or wasting CPU cycles when it determines that the failure is persistent. Breaker mode also enables the application to detect whether the fault has been resolved. If the problem appears to have been corrected, the application can try to invoke the action.
4. Service gateway — Netflix Zuul
Nginx-like, reverse proxy functionality, but Netflix has added some of its own features to work with other components.
⑤. Distributed configuration — Spring Cloud Config
This is still static and needs to work with The Spring Cloud Bus for dynamic configuration updates.
Hibernate
113. Why use Hibernate?
The code of JDBC access database is encapsulated, which greatly simplifies the tedious repetitive code of data access layer. Hibernate is a mainstream persistence framework based on JDBC and an excellent ORM implementation. Hibernate uses Java reflection rather than bytecode enhancers to achieve transparency. Hibernate performs very well because it is a lightweight framework. The flexibility of mapping is excellent. It supports a variety of relational databases, from one-to-one to many-to-many complex relationships.
114. What is ORM Framework?
Object-relational Mapping (ORM), the object-oriented development method is the mainstream development method in today’s enterprise application development environment, Relational database is the mainstream data storage system for permanent storage of data in enterprise application environment. Objects and relational data are two representations of business entities, which are represented as objects in memory and relational data in a database. There are associations and inheritance relationships between objects in memory, but in database, relational data cannot directly express many-to-many associations and inheritance relationships. Therefore, object-relational mapping (ORM) systems generally exist in the form of middleware, mainly to achieve the mapping of program objects to relational database data.
115. How to view printed SQL statements in The console in Hibernate?
Reference: blog.csdn.net/Randy_Wang_/article/details/79460306
How many query methods does Hibernate have?
HQL Query QUERY SQL query conditions
HQL: Hibernate Query Language. Query = session.createQuery(" From Customer where name =?") ); Query. SetParameter (0, "old master "); Query.list(); QBC: Query By Criteria.(Conditional Query) Criteria = session.createcriteria (customer.class); Criteria. Add (Restrictions. Eq ("name", "sister ")); List<Customer> list = criteria.list(); SQL: SQLQuery query = session.createSQLQuery("select * from customer"); List<Object[]> list = query.list(); SQLQuery query = session.createSQLQuery("select * from customer"); query.addEntity(Customer.class); List<Customer> list = query.list();Copy the code
Hql: Specific category 1. Attribute query 2. Parameter query and named parameter query 3. Associated query 4
The difference between HQL and SQL HQL is object-oriented query operations, while SQL is structured query language (SQL), which is oriented to database table structure
117. Can Hibernate entity classes be defined as final?
It is possible to define Hibernate’s entity classes as final, but this is not a good idea. Because Hibernate uses proxy patterns to improve performance in the case of deferred association, if you define your entity class as final, Hibernate can no longer use proxies because Java doesn’t allow extensions to final classes, thus limiting the means to improve performance. However, if your persistent class implements an interface in which all public methods defined in the entity class are declared, you can avoid the aforementioned adverse consequences.
118. What is the difference between using Integer and int for mapping in Hibernate?
In Hibernate, if an OID is defined as an Integer type, Hibernate can determine whether an object is temporary based on whether its value is null. If an OID is defined as an int, it also needs to set its unsaved-value property to 0 in the HBM mapping file.
119. How does Hibernate work?
Hibernate works:
Configuration config = new Configuration().configure(); / / read and parse the hibernate. CFG. XML configuration files By hibernate. CFG. The read and parse the XML mapping information through SessionFactory sf = config. BuildSessionFactory (); SessionFactory Session = sf.openSession(); // Open Sesssion Transaction tx = session.beginTransaction(); Tx.mit (); Transation persistent operate (); Session closes SesstionFactory
120. The difference between get() and load()?
Load () generates no SQL lazy loading when no other attributes of the object are used. Get () also generates SQL immediate loading when no other attributes of the object are used
121. What about Hibernate’s caching mechanism?
The cache in Hibernate is divided into level 1 cache and level 2 cache.
Level 1 caches are session-level caches that are transaction-wide and built-in and cannot be unloaded. The level 2 cache is the SesionFactory cache and is valid from the start to the end of the application. This parameter is optional. Level-2 cache is disabled by default and must be manually enabled. After the database is saved, a copy is cached in memory. If the database is updated, it needs to be updated synchronously.
What kind of data is appropriate to store in the second-level cache?
Rarely modified data Post last reply time frequently queried data e-commerce site not very important data, allowing occasional concurrent data to occur data constant data that will not be accessed concurrently
Extension: Hibernate’s second-level cache does not support distributed caching by default. Use memcahe, Redis, and other central caches instead of secondary caches.
122. What are the states of Hibernate objects?
Hibernate objects have three states:
Transient: The object is new, but its ID is not set, other values are set. Persistent: Call save(), saveOrUpdate(), which becomes Persistent and has id. Detached: After session close(), become Detached.
What is the difference between getCurrentSession and openSession in Hibernate?
OpenSession is to open a new session object, and a new session is opened each time it is used. If it is used for several times in a row, the obtained session is not the same object, and the close method should be called to close the session after using it.
GetCurrentSession getCurrentSession getCurrentSession getCurrentSession getCurrentSession getCurrentSession getCurrentSession getCurrentSession getCurrentSession getCurrentSession getCurrentSession getCurrentSession getCurrentSession getCurrentSession getCurrentSession So that’s one of the differences from openSession. In a nutshell, getCurrentSession is: if it’s already in use, use the old one, if it’s not, build a new one.
Note: In real development, getCurrentSession is used more often because it is usually the same transaction (i.e. using a database), so openSession is not used in general or openSession is an older set of interfaces.
124. Do Hibernate entity classes have to have parameterless constructors? Why is that?
You must, because the Hibernate framework calls the default constructor to construct the instance object, the newInstance method of the Class Class, which creates the instance object by calling the default constructor.
Another reminder, if you did not provide any constructor, the virtual opportunity automatically provide a default constructor (no constructor), but if you offer the other constructor with parameters, the virtual machine will no longer provide a default constructor for you, then you must manually write in code, no arguments constructor or new Xxxx () will be an error, So the default constructor is not required, only if there are multiple constructors, where “must” means “must be written manually.”
Mybatis
125. What is the difference between #{} and ${} in mybatis?
KaTeX Parse Error: Expected ‘EOF’, got ‘#’ at position 21:… String replacement; SQL > select * from #̲{}; ${} = ${}; Using #{} can effectively prevent SQL injection and improve system security.
126. How many pagination methods are there in Mybatis?
Array pages SQL page interceptor pages RowBounds pages
127. Advantages and disadvantages of Mybatis
Mybaits advantages: (1) based on SQL statement programming, quite flexible, will not cause any impact on the existing design of the application or database, SQL written in XML, remove the COUPLING of SQL and program code, easy to unified management; Provides XML tags that support writing dynamic SQL statements and can be reused. (2) compared with JDBC, reduce more than 50% of the code, eliminate a lot of JDBC redundant code, do not need to manually switch the connection; (3) very good compatibility with a variety of databases (because MyBatis uses JDBC to connect to the database, so as long as JDBC support database MyBatis support). (4) Good integration with Spring; (5) Provide mapping labels to support ORM field relational mapping between objects and databases; Provides object-relational mapping labels to support object-relational component maintenance.
Disadvantages of MyBatis framework: (1) The workload of WRITING SQL statements is large, especially when there are many fields and many associated tables, so there are certain requirements for developers to write SQL statements. (2) SQL statements rely on the database, resulting in poor database portability, can not be replaced at will database. MyBatis framework applicable occasions: (1) MyBatis focus on SQL itself, is a flexible enough DAO layer solution. (2) MyBatis will be a good choice for projects with high performance requirements or more variable requirements, such as Internet projects.
128. What is the difference between logical paging and physical paging in Mybatis?
Physical pages are not necessarily faster than logical pages, and logical pages are not necessarily faster than physical pages. Physical paging is always better than logical paging: there is no need to impose pressure on the application side that belongs to the database side, even if there is an advantage in speed, but other performance advantages more than make up for it.
129. Does Mybatis support lazy loading? What is the principle of lazy loading?
Mybatis only supports lazy loading of association associative objects and collection associative objects. Association refers to one-to-one and collection refers to one-to-many queries. In Mybatis configuration file, you can configure whether to enable lazy-loading lazyLoadingEnabled = true | false.
The principle is that CGLIB is used to create a proxy object for the target object. When the target method is called, the interceptor method is entered, such as a.geb ().getName(). The interceptor invoke() method finds that A.geb () is null. A. setb (); a.getName (); a.getname (); a.getb (); a.getname (); This is the basic principle of lazy loading.
Of course, not only Mybatis, almost all including Hibernate, support lazy loading principle is the same.
What about level 1 cache and level 2 cache in Mybatis?
Level 1 Cache: A HashMap local Cache based on PerpetualCache, with storage scope of Session. When a Session is flushed or closed, all caches in that Session are cleared, enabling Level 1 Cache by default.
Level 2 caches have the same mechanism as Level 1 caches, with PerpetualCache and HashMap storage by default, but with Mapper(Namespace) storage scope and customizable storage source, such as Ehcache. Level 2 caching is not enabled by default. To enable level 2 caching, use the Level 2 cache attribute class to implement the Serializable interface (which can be used to store the state of objects), which can be configured in its mapping file.
If a C/U/D operation is performed on a Session (level 1) or Namespaces (level 2), all caches in the select area will be cleared by default.
131. What are the differences between Mybatis and Hibernate?
(1) Unlike Hibernate, Mybatis is not a complete ORM framework, because Mybatis requires programmers to write their own Sql statements.
(2) Mybatis directly writes the original SQL, which can strictly control the PERFORMANCE of SQL execution and has high flexibility. It is very suitable for software development with low requirements on relational data model, because such software needs to change frequently and output results rapidly once the requirements change. However, the premise of flexibility is that Mybatis cannot achieve database independence. If you need to implement software supporting a variety of databases, you need to customize multiple sets of SQL mapping files, and the workload is heavy.
(3) Hibernate object/relational mapping ability is strong, database independence is good, for software with high requirements of relational model, if Hibernate development can save a lot of code, improve efficiency.
132. What executors do Mybatis have?
Mybatis has three basic executors:
SimpleExecutor: Every time an Update or select is performed, a Statement object is opened and the Statement object is closed immediately. ReuseExecutor: Performs update or select, searches for a Statement object using the SQL as its key, uses it if it exists, and creates it if it does not exist. After the Statement object is used, it is stored in the Map for future use. In short, the Statement object is reused. BatchExecutor: Update (no SELECT, JDBC batch does not support SELECT), add all SQL to the batch (addBatch()), and wait for execution (executeBatch()), which caches multiple Statement objects. Each Statement object is addBatch() and waits for the executeBatch() batch to be executed one by one. Same as JDBC batch processing.
133. What is the implementation principle of mybatis paging plug-in?
The basic principle of the paging plug-in is to use the plug-in interface provided by Mybatis to implement a custom plug-in to intercept the SQL to be executed in the interception method of the plug-in, and then rewrite the SQL to add the corresponding physical paging statement and physical paging parameters according to the dialect.
134. How to write a custom plug-in for Mybatis?
From: blog.csdn.net/qq_30051265/article/details/80266434
Mybatis intercepts four Mybatis objects (Executor, StatementHandler, ParameterHandler, ResultSetHandler) in the following ways: StatementHandler: intercepts the processing of Sql syntax builds ParameterHandler: intercepts the processing of parameters ResultSetHandler: intercepts the processing of result sets
Mybatis custom plug-in must implement the Interceptor interface:
public interface Interceptor {
Object intercept(Invocation invocation) throws Throwable;
Object plugin(Object target);
void setProperties(Properties properties);
}
Copy the code
Plugin method: generate dynamic proxy object according to signatureMap setProperties method: setProperties property custom plug-in demo:
// ExamplePlugin.java @Intercepts({@Signature( type= Executor.class, method = "update", args = {MappedStatement.class,Object.class})}) public class ExamplePlugin implements Interceptor { public Object intercept(Invocation invocation) throws Throwable { Object target = invocation.getTarget(); Method Method = Invocation. GetMethod (); Object[] args = Invocation. GetArgs (); // Method parameters // do something...... Method executes the code block Object result = Invocation.proceed() before intercepting; // do something ....... Method executes a code block after intercepting return result; } public Object plugin(Object target) { return Plugin.wrap(target, this); } public void setProperties(Properties properties) { } }Copy the code
An @intercepts can be configured with multiple @signatures. The parameters in @signature are defined as follows: Type: intercepting class. Method: intercepts the Executor update method. Args: indicates method parameters.
RabbitMQ
135. What are the usage scenarios for RabbitMQ?
①. For asynchronous communication across systems, message queues can be used wherever asynchronous interaction is required. For example, in addition to making phone calls (synchronous), we also need to send text messages and E-mail (asynchronous) communication methods.
②. Coupling between multiple applications, because messages are platform – and language-independent and semantically no longer function calls, is better suited as a loosely coupled interface between multiple applications. Message queue-based coupling does not require both sender and receiver to be online at the same time. In enterprise application integration (EAI), file transfer, shared databases, message queues, and remote procedure calls can all be used as integration methods.
③. For the synchronous variation steps within the application, such as order processing, the front-end application can put the order information into the queue, and the back-end application can obtain the message processing from the queue in turn. A large number of orders at peak time can be backlogged in the queue and processed slowly. Because synchronization usually means blocking, and blocking a large number of threads can degrade computer performance.
(4). The message-driven architecture (EDA), the system is decomposed into the message queue, and news producers and news consumers, a process can according to need to split into several phases (stages), phase connection with queue up, the result of the previous Stage processing into the queue, after a phase get messages from the queue to continue processing.
⑤. Applications need more flexible coupling, such as publish and subscribe, for example, routing rules can be specified.
⑥. Cross-lan, even cross-city communication (CDN industry), such as Beijing machine room and Guangzhou machine room application communication.
136. What are the important roles of RabbitMQ?
The important roles in RabbitMQ are: producer, consumer, and agent:
Producer: The creator of the message, responsible for creating and pushing data to the message server; Consumer: The recipient of a message, used to process data and acknowledge messages; Proxy: this is RabbitMQ itself, used to act as a “Courier”. It does not produce messages itself, only as a “Courier”.
137. What are the important components of RabbitMQ?
ConnectionFactory: A manager used in application code to establish a connection between the application and Rabbit. Channel: The Channel used by the message push. Exchange: Used to receive and distribute messages. Queue: Used to store messages from producers. RoutingKey: Used to assign producer data to the switch. BindingKey: Used to bind exchange messages to queues.
138. What is vhost for rabbitMQ?
A vhost is a virtual broker, that is, a mini-RabbitMQ server. They all have their own queue, exchange, binding, etc., but most importantly, they have their own permission system, which can control users in the vhost range. Of course, from RabbitMQ’s global perspective, vhosts can be used as a means of isolating different permissions (a typical example is that different applications can run on different vhosts).
139. How are rabbitMQ messages sent?
A TCP connection is created between the client and rabbit Server. Once TCP is opened and authenticated (authentication is the username and password you send to the Rabbit server), Your client and RabbitMQ create an AMQP channel. A channel is a virtual connection created over “real” TCP. Amqp commands are sent over the channel and each channel has a unique ID. Subscription queues are all done through this channel.
140. How does RabbitMQ ensure message stability?
Provides transaction functionality. By setting channel to Confirm mode.
141. How can RabbitMQ avoid message loss?
Message Persistence ACK acknowledgement mechanism Sets the cluster mirroring mode message compensation mechanism
142. What are the conditions for successful message persistence?
Declare that queue must be durable and durable to true. Message push deliveryMode must be persistent and deliveryMode must be 2 (persistent). The message has arrived at the persistent exchange. The message has reached the persistence queue.
All 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 by using disk rather than memory storage. SSDS can be used to mitigate throughput issues.
144. How many broadcast types are available for RabbitMQ?
Three broadcast modes:
Fanout: All queues bound to this exchange can receive messages (pure broadcast, recipients bound to RabbitMQ can receive messages); Direct: the unique queue determined by the routingKey and exchange can receive messages; Topic: All queues bind to a routingKey that matches a routingKey(which in this case can be an expression) can receive messages;
145. How does RabbitMQ implement delayed message queuing?
After the message expires, it enters the dead letter exchange and is forwarded to the delay consumption queue by the exchange to realize the delay function. Use the Rabbitmq-delayed -message-exchange plug-in for delay.
146. What are rabbitMQ clusters for?
Clusters are used for the following two purposes:
High availability: when a server fails, the entire RabbitMQ service can continue. High volume: The cluster can carry more message volumes.
147. What are the types of RabbitMQ nodes?
Disk node: Messages are stored to disk. Memory node: Messages are stored in memory. Messages are lost when the server is restarted. The performance is higher than that of disks.
148. What should I pay attention to when setting up rabbitMQ clusters?
Nodes are connected using -link. This attribute cannot be ignored. The value of Erlang cookie used by all nodes must be the same. This value is equivalent to the function of “secret key” for authentication of all nodes. The entire cluster must contain one disk node.
149. Is each rabbitMQ node a full copy of the other nodes? Why is that?
No, for two reasons:
Storage space considerations: If each node has a full copy of all queues, the new node does not add storage space, but adds more redundant data. Performance considerations: If every message needs to be fully copied to every cluster node, the new node does not improve the ability to process messages, at best maintaining the same or worse performance as a single node.
150. What happens when the only disk node in the RabbitMQ cluster crashes?
If the disk node with the only disk crashes, the following operations cannot be performed:
You cannot create queues you cannot create switches you cannot create bindings you cannot add users you cannot change permissions You cannot add or delete cluster nodes
The cluster can keep running when the only disk node crashes, but you can’t change anything.
151. Does RabbitMQ have a stop order for cluster nodes?
RabbitMQ requires that the cluster be stopped in the order in which the memory nodes should be shut down first and the disk nodes last. If the order is reversed, messages may be lost.
Kafka
Can Kafka be used independently of ZooKeeper? Why is that?
Kafka cannot be used independently of ZooKeeper because Kafka uses ZooKeeper to manage and coordinate kafka node servers.
153. How many data retention strategies does Kafka have?
Kafka has two data retention strategies: retention by expiration time and retention by the size of stored messages.
154. Kafka sets 7 days and 10 gigabytes of clean data at the same time, and on the fifth day it reaches 10 gigabytes of clean data.
At this point Kafka will perform a data purge, which will be performed regardless of the time and size of the purge.
155. What can cause Kafka to run slowly?
CPU performance bottleneck Disk read/write bottleneck Network bottleneck
156. What should I pay attention to when using kafka clusters?
It is better not to have more clusters than 7, because the more nodes, the longer the message replication takes and the lower the throughput of the whole group. Set the number of clusters to an odd number because more than half of the failed clusters will become unusable. Set it to an odd number for higher fault tolerance.
Zookeeper
157. What is Zookeeper?
Zookeeper is a distributed, open source distributed application coordination service. It is an open source implementation of Google Chubby and an important component of Hadoop and hbase. It provides consistency services for distributed applications, including configuration and maintenance, domain name service, distributed synchronization, and group service.
158. What functions does ZooKeeper have?
Cluster management: Monitors node status and running requests. Primary node election: After the primary node fails, a new primary node can be elected from the standby node. Primary node election refers to the election process. Zookeeper can help complete this process. Distributed lock: ZooKeeper provides two types of locks: exclusive lock and shared lock. An exclusive lock means that only one thread can use a resource at a time. A shared lock means that read locks are shared. Read and write locks are mutually exclusive, that is, multiple threads can read the same resource at the same time. Zookeeper controls distributed locks. Naming service: In distributed systems, client applications can obtain information such as the address and provider of a resource or service by using a named naming service.
159. How many deployment modes are available for ZooKeeper?
Zookeeper can be deployed in three modes:
Single-node deployment: Runs on one cluster. Cluster deployment: Multiple clusters run. Pseudo-cluster deployment: One cluster starts multiple ZooKeeper instances.
160. How does ZooKeeper synchronize the status of the primary and secondary nodes?
At the core of ZooKeeper is atomic broadcasting, which ensures synchronization between servers. The protocol that implements this is called the ZAB protocol. Zab supports two modes: recovery mode (master selection) and broadcast mode (synchronization). Zab goes into recovery mode when the service starts or after the leader crashes, and the recovery mode ends when the leader is elected and most servers have completed state synchronization with the Leader. State synchronization ensures that the leader and Server have the same system state.
161. Why have a primary node in a cluster?
In a distributed environment, some business logic needs to be executed by only one machine in the cluster, and the results can be shared by other machines. This can greatly reduce double computation and improve performance, so the primary node is needed.
162. There are three servers in the cluster and one node is down. Is ZooKeeper still available?
Can continue to use, singular servers as long as more than half of the servers are not down can continue to use.
163. What is the notification mechanism of ZooKeeper?
The client will set up a Watcher event for a ZNode. When the ZNode changes, the client will receive a Notification from ZooKeeper. Then the client can make business changes according to the zNode changes.
MySql
164. What are the three paradigms of databases?
First normal Form: Emphasizes atomicity of columns, that is, each column of a database table is an indivisible atomic data item. Second normal Form: Requires that the attributes of the entity depend entirely on the primary key. Complete dependency means that there cannot be attributes that depend on only part of the primary key. Third normal form: any non-primary property does not depend on any other non-primary property.
Mysql > alter table alter table alter table alter table alter table alter table alter table alter table alter table alter table alter table alter table alter table
If the table type is MyISAM, then the id is 18. If the table type is InnoDB, the id is 15.
InnoDB tables only record the maximum ID of the self-increment primary key in memory, so the maximum ID will be lost after restarting.
166. How do I obtain the current database version?
Use select version() to get the current MySQL database version.
167. What is ACID?
Atomicity: All operations in a transaction, either complete or not complete, do not end at some intermediate stage. If a transaction fails during execution, it will be rolled back to the state before the transaction began, as if the transaction had never been executed. That is, transactions are indivisible and irreducible. Consistency: The integrity of the database is not compromised before and after a transaction. This means that the data written must fully comply with all preset constraints, triggers, cascading rollback, and so on. Isolation: The ability of a database to allow multiple concurrent transactions to read, write, and modify its data at the same time. Isolation prevents data inconsistencies due to cross-execution when multiple transactions are executed concurrently. Transaction isolation can be divided into different levels, including Read uncommitted, Read Committed, Repeatable Read, and Serializable. “Durability” : After a transaction ends, modifications to data are permanent and not lost even if system failures.
168. What is the difference between char and varchar?
Char (n) : Fixed-length types, such as subscribe char(10). When you type “ABC”, they still take up 10 bytes. The other seven are empty bytes. Chat advantages: high efficiency; Disadvantages: Takes up space; Application scenario: Char is suitable for storing the MD5 value of a password with a fixed length. Varchar (n) : Variable length. The value stored is the number of bytes taken up by each value plus the number of bytes used to record its length. Therefore, it is appropriate to consider Varcahr in terms of space; Char is appropriate in terms of efficiency, but there is a tradeoff between the two.
169. What is the difference between float and double?
Float can store up to 8 decimal digits and take up 4 bytes in memory. A double can hold up to 16 decimal digits and occupy 8 bytes of memory.
170. What is the difference between inner join, left join, right join in mysql?
Inner join keywords: inner join; Left join: left join; Right join: right join.
The inner link is to display the matched associated data; The left link shows 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 particular lookup algorithm and that points to the data in a way that enables efficient lookup of the data.
Specifically, indexes in MySQL are implemented differently by different data engines, but the indexes of the current mainstream database engines are implemented by B+ tree. The search efficiency of B+ tree can reach the performance of dichotomy, and the complete data structure can be found after the data region is found, and the performance of all indexes is also better.
172. How to verify that the mysql index meets the requirement?
Use Explain to see how SQL executes queries to see if your index meets your requirements.
Explain syntax: explain select * from table where type=1
173. What about transaction isolation of databases?
MySQL transaction isolation was added in the mysql.ini configuration file. At the end of the file: transaction- ISOLATION = REPEATABLE-READ
Available configuration values: read-uncommitted, read-committed, REPEATABLE-READ, SERIALIZABLE.
Read-uncommitted: Indicates that reads are not committed, at the lowest isolation level, and can be READ by other transactions (magic, dirty, and unrepeatable reads occur) before a transaction is committed. Read-committed: A transaction can only be READ by other transactions after it is COMMITTED (causing illusorable and unrepeatable reads). REPEATABLE-READ: REPEATABLE READ. The default level ensures that the value of the same data READ for many times is consistent with the content at the beginning of the transaction. Data not committed by other transactions is forbidden to be READ (resulting in phantom READ). SERIALIZABLE: The most expensive and reliable isolation level that can prevent dirty reads, unrepeatable reads, and phantom reads.
Dirty read: Indicates that one transaction can read data that has not yet been committed in another transaction. For example, A transaction may attempt to insert record A before the transaction commits, and then another transaction may attempt to read record A.
Non-repeatable read: the same data is read multiple times in a transaction.
Phantom read: When multiple queries within the same transaction return different result sets. For example, the same transaction A has N records in the first query, but n+1 records in the second query under equal conditions. This is like hallucination. Phantom reading occurs when another transaction adds or deletes or modifies data in the result set of the first transaction. When the data content of the same record is modified, all data rows become more or less.
174. What is the common mysql engine?
InnoDB engine: The InnoDB engine provides acid transaction support, row-level locking and foreign key constraints, and is designed for database systems with large data volumes. When MySQL is running, InnoDB creates a buffer pool in memory to buffer data and indexes. However, this engine does not support full-text search and is slow to start. It does not save the number of rows in a table. Therefore, when performing select count(*) from table, you need to scan the entire table. Because of the small granularity of locks, write operations do not lock the entire table. Therefore, using locks in scenarios with high concurrency can improve efficiency.
MyIASM engine: the default engine for MySQL, but does not support transactions, row-level locks and foreign keys. Therefore, when inserting and updating statements, that is, when writing, the table needs to be locked, resulting in a loss of efficiency. Unlike InnoDB, MyIASM saves the number of rows in a table, so when you select count(*) from a table, you can read the saved values directly without scanning the entire table. Therefore, MyIASM can be used as the database engine of choice if the tables are being read far more than written, and transaction support is not required.
175. What about row and table locks in mysql?
MyISAM only supports table locks, InnoDB supports table locks and row locks, default row locks.
Table lock: low overhead, fast lock, no deadlock. Large lock granularity has the highest probability of lock conflict and the lowest concurrency. Row-level locking: expensive, slow, and deadlocks. The lock force is small, the probability of lock conflict is small, and the concurrency is the highest.
176. What about optimistic and pessimistic locks?
Optimistic lock: Every time I go to get data, I will not lock it because I think others will not change it, but I will judge whether others have updated the data in the meantime before submitting the update. Pessimistic lock: Every time you try to get data, you assume that someone else will change it, so every time you try to get data, you lock it, so that someone else will block it until the lock is released.
Add a version field to the table, and the value of each successful change increases by 1. In this way, each time you change the version of the database, check whether the version you have is consistent with the current version of the database. If the version is inconsistent, do not change it.
177. What are the methods used to troubleshoot mysql problems?
Run the show processList command to view all current connection information. Query SQL statement execution plans using the Explain command. Enable the slow query log function to view the SQL that is slowly queried.
178. How to optimize mysql performance?
Create an index for the search field. Avoid select * and list the fields you want to query. Vertical split table. Select the correct storage engine
Redis
179. What is redis? What are the usage scenarios?
Redis is an open source, network-enabled, memory-based and persistent logging, key-value database written in ANSI C, and provides multiple language apis.
Redis application scenarios: High concurrent data Read/write Massive data read/write data with high scalability requirements
180. What functions does Redis have?
Data caching function Distributed lock function data persistence support transaction support message queuing
181. What’s the difference between Redis and memecache?
All of memcached’s values are simple strings, and redis, as an alternative, supports richer data types redis is much faster than Memcached and redis can persist its data
182. Why is Redis single threaded?
Since CPU is not the bottleneck of Redis, the bottleneck of Redis is most likely machine memory or network bandwidth. Since single threading is easy to implement and the CPU is not a bottleneck, it makes sense to adopt a single threaded solution.
About Redis performance, the official website also has, ordinary notebook easily handle hundreds of thousands of requests per second.
And single-threaded doesn’t mean slow. Nginx and NodeJS are both examples of high-performance single-threaded performance.
183. What is cache penetration? How to solve it?
Cache penetration: The system queries data that does not exist. If the cache does not match, the system queries the data from the database. If no data is found, the system does not write the data into the cache.
Solution: The simplest and most crude way If a query returns empty data (either nonexistent or a system failure), we cache the empty result, but its expiration time is short, no more than five minutes.
184. What data types are supported by Redis?
String, list, hash, set, zset.
185. What Java clients does Redis support?
Redisson, Jedis, lettuce, etc. Redisson is officially recommended.
186. What are the differences between Jedis and Redisson?
Jedis is the client of the Java implementation of Redis, and its API provides comprehensive support for Redis commands.
Redisson implements distributed and extensible Java data structures. Compared with Jedis, Redisson has relatively simple functions. It does not support string manipulation, sorting, transaction, pipeline, partitioning and other Redis features. The goal of Redisson is to promote a separation of focus from Redisso that users can focus more on processing business logic.
187. How to ensure the consistency of cache and database data?
Set the cache expiration time appropriately. Update Redis synchronously when adding, changing, and deleting databases. Transaction mechanism can be used to ensure data consistency.
188. How many ways can REDis persist?
Redis persists in two ways, or two strategies:
Redis Database (RDB) : Specifies the interval at which a snapshot of your data can be stored. AOF (Append Only File) : Each received write command is appended to the File using the write function.
189. How does Redis implement distributed lock?
Redis distributed lock is actually in the system to occupy a “pit”, other programs also want to occupy the “pit”, occupy a successful can continue to execute, failed can only give up or later retry.
A trap is usually occupied by a program using the setnx(Set if not exists) instruction.
190. What are the defects of redis distributed locks?
Redis distributed lock does not solve the problem of timeout. Distributed lock has a timeout period, and the program execution will have problems if the timeout period of the lock is exceeded.
191. How does Redis optimize memory?
Use hashes whenever possible. Hashes use very little memory, so you should abstract your data model into a hash as much as possible.
For example, if you have a user object in your Web system, do not set a separate key for the user’s name, last name, email address, and password. Instead, store all of the user’s information in a hash table.
192. What are the Redis elimination strategies?
Volatile – lRU: Selects the least recently used expires data from a set with an expiration date (server.db [I].expires). Volatile – TTL: Selects expired data from a set (server.db [I].expires) to be discarded. Volatile -random: Selects any data from a set with an expiration date (server.db [I].expires) to be discarded. Allkeys-lru: Culls the least recently used data from the dataset (server.db [I].dict). Allkeys-random: Random selection of data from a dataset (server.db [I].dict). No-enviction: Data expulsion is prohibited.
193. What are the common performance issues with Redis? How to solve it?
When the primary server writes a memory snapshot, the main process is blocked. When a large number of snapshots are taken, the performance is greatly affected and services are interrupted intermittently. Therefore, do not write a memory snapshot on the primary server. Redis master/slave replication performance problem, in order to master/slave replication speed and connection stability, the master/slave library had better be in the same LAN.
JVM
194. What are the main components of the JVM? And its role?
The Runtime Data Area of the ClassLoader is the Native Interface of the Execution Engine.
What components do: The Java code is converted into bytecode by the ClassLoader, and the bytecode is loaded into memory by the Runtime Data Area. Bytecode files are only a set of instructions for the JVM, and cannot be directly delivered to the underlying operating system for execution. Therefore, a specific command parser Execution Engine is required to translate the bytecode into the underlying system instructions and then send them to the CPU for Execution. In this process, the Native Interface of other languages is called to realize the function of the entire program.
195. What about the JVM runtime data area?
Program counter virtual machine stack local method stack stack method area
Some regions exist with the start of a virtual machine process, and some regions are created and destroyed depending on the start and end of a user process.
196. What is the difference between stacks?
- Stack memory stores local variables and heap memory stores entities;
- Stack memory is updated faster than heap memory because local variables have a short lifetime;
- Variables stored in stack memory are released as soon as their life cycle ends, while entities stored in heap memory are collected irregularly by the garbage collection mechanism.
- What are queues and stacks? What’s the difference? Queues and stacks are used to prestore data. Queues allow first-in, first-out retrieval of elements, but there are exceptions where the Deque interface allows retrieval of elements from both ends. A stack is similar to a queue, but it runs last-in, first-out retrieval of elements.
198. What is the parental delegation model?
Class loaders before introducing the parental delegation model. For any class, uniqueness within the JVM needs to be established both by the classloader that loads it and by the class itself. Each classloader has a separate class namespace. The classloader simply loads a class file into JVM memory with the specified fully qualified name and then converts it into a class object.
Class loader classification:
Bootstrap ClassLoader, which is part of the VM itself, loads libraries in the Java_HOME/lib/ directory or in the path specified by the -xbootclasspath parameter and recognized by the VM. “> < span style=” box-sizing: border-box; -webkit-tap-highlight-color: transparent; text-size-adjust: none; -webkit-font-smoothing: antialiased; outline: 0px ! Important.” All libraries in the >\lib\ext directory or in the path specified by the java.ext.dirs system variable;
Application ClassLoader. The class loader is responsible for loading specified libraries on the user’s classpath, and we can use this class loader directly. In general, if we don’t have a custom class loader this is the default.
Parental delegation model: If a class loader receives a request for a class load, it first does not load the class itself. Instead, it delegates the request to the parent class loader, at each level, so that all load requests are sent to the top level of the starting class loader. The child loader attempts to load the class only if the parent load cannot complete the load request (it did not find the required class in its search scope).
199. What about the execution of class loading?
Class loading consists of the following five steps:
Load: according to the search path to find the corresponding class file and import; Check: Check the correctness of the loaded class file; Preparation: allocate memory space for static variables in a class; Resolution: The process by which the virtual machine replaces symbolic references in a constant pool with direct references. A symbolic reference is understood as an identifier, whereas a direct reference points directly to an address in memory. Initialization: Performs initialization on static variables and static code blocks.
200. How to determine whether an object can be reclaimed?
There are two ways to judge:
Reference counter: Creates a reference count for each object, which is +1 when an object is referenced, -1 when a reference is released, and can be reclaimed when the counter is 0. It has a disadvantage that it does not solve the problem of circular references; Reachability analysis: Search down from GC Roots, the path taken by the search is called the reference chain. When an object is not connected to GC Roots by any reference chain, the object is proven to be recyclable.
201. What reference types are available in Java?
Strong reference Soft reference Weak reference Virtual reference (ghost reference/phantom reference)
202. What garbage collection algorithms does the JVM have?
Mark-clear algorithm Mark-tidy algorithm Copy algorithm generation algorithm
203. What garbage collectors does the JVM have?
Serial: The original single-threaded Serial garbage collector. Serial Old: An older version of the Serial garbage collector, which is also single-threaded, can be an alternative to the CMS garbage collector. ParNew: is the multithreaded version of Serial. Parallel and ParNew collectors are similarly multithreaded, but Parallel is a throughput first collector that can sacrifice wait time for system throughput. Parallel Old is the older version of Parallel, Parallel uses the copy memory reclamation algorithm, Parallel Old uses the mark-collation memory reclamation algorithm. CMS: A collector whose goal is to achieve minimum pause times, ideal for B/S systems. G1: A GC implementation that takes into account both throughput and pause times and is the default GC option in JDK 9 onwards.
204. What about CMS garbage collector?
CMS, short for Concurrent mark-sweep, is a garbage collector that achieves the shortest collection pause time at the expense of throughput. This garbage collector is ideal for applications that require fast server response. Specify the use of the CMS garbage collector by adding “-xx :+UseConcMarkSweepGC” to the start JVM argument.
CMS uses the mark-clear algorithm to achieve, so a large number of memory fragments will be generated during GC. When the remaining memory cannot meet the program running requirements, the system will suffer Concurrent Mode Failure. The Serial Old collector is used by the temporary CMS for garbage removal, where performance is reduced.
205. What are the new generation garbage collectors and old generation garbage collectors? What’s the difference?
Serial, ParNew, Parallel Avenge, Serial Old, Parallel Old, CMS Collector: G1
The new generation garbage collector generally adopts replication algorithm. The advantage of replication algorithm is high efficiency, but the disadvantage is low memory utilization. Old-time recyclers generally use a mark-collation algorithm for garbage collection.
206. Describe briefly how generational garbage collector works.
The generation collector has two partitions: old generation and new generation. The default space of the new generation is 1/3 of the total space, and the default space of the old generation is 2/3.
The new generation uses the replication algorithm, and 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 Eden + From Survivor into To Survivor zone; Clear Eden and From Survivor partitions; Swap From Survivor and To Survivor partitions, From Survivor To Survivor, To Survivor To Survivor From Survivor.
An object that survives every move From Survivor To Survivor is aged +1 and is upgraded To the old generation when age reaches 15 (the default is 15). Large objects also go directly to old generation.
The old generation triggers global garbage collection when the footprint reaches a certain value, usually using a mark-up execution algorithm. These iterations constitute the entire implementation process of generational garbage collection.
207. What about JVM tuning tools?
The JDK comes with many monitoring tools, which are located in the BIN directory of the JDK. The two most commonly used view monitoring tools are JConsole and JVisualVM.
Jconsole: For monitoring memory, threads, classes, etc in the JVM Jvisualvm: The JDK comes with a versatile analysis tool, can analyze: memory snapshot, thread snapshot, program deadlock, monitoring memory changes, GC changes, etc.
208. What are the common JVM tuning parameters?
-xMS2G: Indicates that the initial push size is 2g. -XMX2G: The maximum heap memory is 2g. -xx :NewRatio=4: Sets the memory ratio between the young and old ages to 1:4. -xx :SurvivorRatio=8: Set the Eden and Survivor ratio of the new generation to 8:2. – XX:+UseParNewGC: specifies the use of ParNew + Serial Old garbage collector combination; -xx :+UseParallelOldGC: Specifies the use of ParNew + ParNew Old garbage collector combination; -xx :+UseConcMarkSweepGC: specifies the use of CMS + Serial Old garbage collector combination; -xx :+PrintGC: Enables gc information printing. -xx :+PrintGCDetails: Prints GC details.