Java Fundamentals, containers, multithreading, reflection, object copy, Java Web, exceptions, networks, design patterns, Spring/Spring MVC, etc. And detailed analysis. No topic are explained in detail, the article is too long, we must be patient to finish reading oh.

First, Java foundation

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)); // trueCopy 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 c2 = new 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("Wang");
String s2 = new String("Wang");
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 = "Important";
System.out.println(String.format("| str2 str1: % d: % d", str1.hashCode(),str2.hashCode()));
System.out.println(str1.equals(str2));Copy the code

Results of execution:

Str1:1179395 | str2:1179395falseCopy 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 “) will be 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()); // gfedcbaCopy 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.

Second, 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 implementation of a HashSet is a HashMap
  • The value of the HashSet is stored on the key of the HashMap
  • The value of a HashMap is 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:

Iterator () requires 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.

Three, multi-threading

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?

  • The received parameters are different
  • Submit returns a value, but execute does not
  • Submit facilitates Exception handling

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:

  • Mutually exclusive: 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 releases the resource
  • Request and hold conditions: after a process has obtained a certain resource, it makes a request for another resource, but the resource may be occupied by another process. The request is blocked, but the obtained resource is held
  • Inalienable conditions: Resources acquired by a process cannot be taken away before they are used and can only be released after they are used
  • Loop waiting condition: after a process is deadlocked, several processes form a round-ending waiting resource relationship

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:

  • For normal synchronization methods, the lock is the current instance object
  • Statically synchronized methods where the lock is the class object of the current class
  • Synchronized method block, lock is the object inside 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 prevents deadlocks by setting the wait time for acquiring locks
  • ReentrantLock can obtain information about various locks
  • ReentrantLock provides flexibility for 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++.

Four, reflection

57. What is reflection?

Reflection refers primarily to the ability of a program to access, detect, and modify its own state or behavior

The Java reflection:

In the Java runtime environment, is it possible to know what properties and methods a given class has? For any object, can call any of its methods

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的AOP
  • Add the transaction
  • Add permissions
  • Add the log

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.

5. Object copy

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: It makes no sense to call the close method of ByteArrayInputStream or ByteArrayOutputStream object.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 StringgetName() {
 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 StringgetBrand() {
 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 + "]"; }}Copy the code


class CloneTest {
 
 public static void main(String[] args) {
 try {
 Person p1 = new Person("Guo jing", 33, new Car("Benz", 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?

  • The shallow copy simply copies the reference address of the object. Both objects refer to the same memory address, so changing any value of one of these objects will change the other value. This is called the shallow copy (example: assign()).
  • Parse () and json.stringify (), but this method does not copy function types.

Six, Java Web

64. What is the difference between a JSP and a servlet?

  1. JSPS, when compiled, become servlets. (JSPS are essentially servlets, and the JVM only recognizes Java classes, not JSP code. The Web container compiles the JSP code into Java classes that the JVM recognizes.)
  2. JSPS are better at page presentation and servlets are better at logical control.
  3. There are no built-in objects in servlets. Built-in objects in JSPS must be obtained from HttpServletRequest objects, HttpServletResponse objects, and HttpServlet objects.
  4. 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:

  1. Set “session.use_trans_sid = 1” in the php.ini configuration file, or enable the “–enable-trans-sid” option at compile time to have PHP automatically pass the session ID across pages.
  2. Manually pass the Session ID through the URL and hide the form.
  3. 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.

  • Underlying framework differences

Struts 2 using the Filter (StrutsPrepareAndExecuteFilter) implementation, 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

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?

  1. PreparedStatement (simple and effective method)
  2. Use regular expressions to filter incoming parameters
  3. String filtering
  4. This function is called in the JSP to check for package invalid characters
  5. JSP page judge code

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:

1. Verify 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.

2. Use the verification code

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.

3. Add the token to the request address and verify it

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, add <input type=”hidden” name=” csrFToken “value=” tokenValue “/> at the end of the form to add the token as a parameter to the request.

4. 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.

Seven, 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 questions if there is a catchreturnWill the code in finally still execute? */public class FinallyDemo2 { public static void main(String[] args) { System.out.println(getInt()); } public static intgetInt() { int a = 10; try { System.out.println(a / 0); a = 20; } catch (ArithmeticException e) { a = 30; returna; / * *returnA at this point in the program, this is notreturnA butreturn30; The return path forms a * but it finds that finally is followed by finally, so it continues to execute finally. A =40 * returns to the previous path again and continuesreturnFinally {a = 40;} finally {a = 40; } / /return a; }}Copy the code

Result: 30

Code Example 2:

package com.java_02; /* * Java interview questions if there is a catchreturnWill the code in finally still execute? */public class FinallyDemo2 { public static void main(String[] args) { System.out.println(getInt()); } public static intgetInt() { int a = 10; try { System.out.println(a / 0); a = 20; } catch (ArithmeticException e) { a = 30; returna; / * *returnA at this point in the program, this is notreturnA butreturn30; The return path forms a * but it finds that finally is followed by finally, so it continues to execute finally. A =40 * returns to the previous path again and continuesreturnFinally {a = 40;} finally {a = 40;returna; // If so, a new return path is formed, since only one path can be passedreturnReturn, so it just returns 40}//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.

Eight, the 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.

Here’s a colloquial 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?

  1. Application layer: An interface between network services and end users.
  2. Presentation layer: data representation, security, compression.
  3. Session layer: establishes, manages, and terminates sessions.
  4. Transport layer: defines the protocol port numbers for transmitting data, as well as flow control and error-checking.
  5. Network layer: logical address is addressed to realize path selection between different networks.
  6. Data link layer: establish logical connection, hardware address addressing, error checking and other functions.
  7. 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, which is subject to the same origin policy, web pages can get JSON data dynamically generated from other sources using the open policy of <script> elements, which is known as JSONP. The data captured with JSONP is not JSON, but rather arbitrary JavaScript that is run with a JavaScript interpreter rather than parsed with a JSON parser. All JSONP Get requests sent by Chrome are of js type, not XHR.

Disadvantages:

  • Only Get requests can be used
  • Unable to register event listeners such as SUCCESS and error, it is not easy to determine whether a JSONP request failed
  • JSONP is executed from code loaded in other domains and is vulnerable to cross-site request forgery, so its security cannot be guaranteed

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, OPTIONSAccess-Control-Allow-Headers: X-PINGOTHER, Content-TypeAccess-Control-Max-Age: 86400Copy the code

By default, cross-domain requests do not carry Cookie information. To carry Cookie information, set the following parameters:

"Access-Control-Allow-Credentials": true/ / Ajax Settings"withCredentials": trueCopy the code

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 Window object of the <iframe> element. 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 the page from being refreshed indefinitely iframe.onload =function() { if(state === 1) { console.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; // Blocked a frame with origin refers to the current domain and prevents errors (proxy.html is a blank page)"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 the domain to “xxx.com” but not “xxx.com porn-free PORNO videos” 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)

Source: blog.csdn.net/ligang2585116/article/details/73072868

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.

9. Design mode

88. Tell me about a design pattern you are familiar with.

Reference: summary of commonly used design patterns, super detailed!

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:

  1. There are multiple product families in the system, and the system can only consume one of them at a time
  2. The use of products belonging to the same product family.

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

  • Objective: To solve the complexity of enterprise application development
  • Features: Use basic Javabeans instead of EJBs, and provide more enterprise application functionality
  • Scope: 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.

More info: Spring Tutorials – HowToDoInJava

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:

  1. Constructor injection
  2. Setter injection
  3. 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, there will be only one instance of a Bean defined using a Singleton in the entire Spring IoC container
  • Prototype: In prototype mode, each time a Prototype-defined Bean is fetched through the container’s getBean method, a new instance of the Bean is generated
  • Request: For each HTTP request, a new instance of the Bean defined using Request is created, meaning that a different Bean instance is 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 Bean milk defined by the session. Again, this scope is only valid if Spring is used in a Web application
  • Globalsession: For each global HTTP Session, a new instance of a Bean defined using the Session is generated. 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 autowiring
  • Display configuration in Java code or XML

Of course, these methods can also be used together.

What are the ways in which Spring transactions are implemented?

  1. 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.
  2. Based on the TransactionProxyFactoryBean declarative transaction management
  3. Transactional Transactional Transactional management
  4. Configure transactions based on Aspectj AOP

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:

1. The user sends a request to the server, which is captured by Spring front-end control Servelt DispatcherServlet.

2. DispatcherServlet parses the request URL and obtains 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.

3. The DispatcherServlet selects an appropriate HandlerAdapter according to the obtained Handler. (Note: If the HandlerAdapter is successfully obtained, execution of the interceptor’s preHandler(…) begins at this point.) Methods)

4. Extract the model data from the Request, fill in the Handler input parameter, and run 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 or XML data) into an object, which is converted into the specified response information
  • Data transformation: Data transformation of the request message. Such as String to Integer, Double, and so on
  • Data root: Data formatting of the request message. For example, converting a string to a formatted number or a formatted date
  • Data validation: Verifies the validity of data (length, format, etc.) and stores the validation results in BindingResult or Error

5. Handler returns a ModelAndView object to DispatcherServlet after execution.

6. According to the returned ModelAndView, select a suitable ViewResolver (must be a ViewResolver registered in Spring container) and return it to DispatcherServlet;

7. ViewResolver combines Model and View to render the View;

8. Return the rendering result to the client.

101. What components does Spring MVC have?

The core components of Spring MVC:

  1. DispatcherServlet: Central controller that forwards requests to specific control classes
  2. Controller: The Controller that processes requests
  3. HandlerMapping: A mapping handler that maps the mapping policy that the CPU forwards to the controller
  4. ModelAndView: Encapsulates the data returned by the service layer and the view layer
  5. ViewResolver: a ViewResolver that resolves specific views
  6. Interceptors: Interceptors, which intercept the requests we define and do 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?

How to Use @autowired

Conclusion:

For 2019 100 classic interview questions summary and analysis, to give you in the future interview on the road a little help, more exciting articles and interview questions please pay attention to: wechat public number: Java programmers gathering



350 Online interviews

Interview questions for 2019