JavaOOP

What are Java data structures?

  • Linear list (ArrayList)
  • LinkedList
  • The Stack (Stack)
  • Queue
  • Figure (Map)
  • A Tree (Tree)

There are several data types in Java

Eight kinds of four type

  • Integer: byte, short, int, long
  • Floating point: float, double
  • Character type: char
  • Boolean: Boolean

String STR =”aaa”, same as String STR =new String(“aaa”)

  • Instead, the first literal declaration string is taken from the constant pool, created if it doesn’t have one, reused if it does, and then taken from the pool for reuse when it also declares aaa. The second one, created using new, will not be placed in the constant pool, so it will not be reused.

What is the difference between String, StringBu o ffffer and StringBuilder?

  • A String is a read-only String. It is not a basic data type, but an object. Its underlying layer is a final array of char characters.
  • StringBu o ffffer and StringBuilder both inherit from the AbstractStringBulder class, and both classes are used for string operations.
  • StringBu o ff o ffer is thread-safe, whereas StringBuilder is non-thread-safe, so StringBuilder is more efficient than StringBu o ff o ffer. Methods of the StringBu o ff o ffer class are mostly appended to the synchronized keyword.

What is the difference between abstract classes and interfaces?

  • An abstract class

    • You need to use the abstract keyword definition, which can have abstract methods and instance methods. Abstract methods have no method body and require subclass implementation.
    • A class that contains abstract methods must be abstract
    • Abstractions can only be inherited, not instantiated
  • interface

    • The methods of the interface are all abstract methods, and the properties are constants
    • The interface could not be instantiated
    • Interfaces can only be implemented, and the class implementing the interface must implement all of the abstract methods, unless the class is abstract. You can choose to implement some of the abstract methods and let subclasses implement the rest
    • Interfaces can be multiple inherited

With equals(), why do we need hashCode()

  • Java collections have two classes, List and Set. List is ordered and repeatable, while Set is unordered but not repeatable. The Set guarantees that the only way to determine whether an object’s equals() is the same as an existing element at insert time, but calling equals() would be inefficient if there were more elements. Therefore, hashCode() was added to calculate a hash value based on the memory address of the element object. When comparing, hashCode is compared first. HashCode is very efficient, and when the hashCode of the element is the same, then call equals() to compare.

This section describes the Java strong, weak, soft, and virtual references

  • Strong references, strong references occur OOM rather than reclaim when out of memory.
  • A SoftReference is wrapped with a SoftReference reference. If the memory is insufficient, the reference will be reclaimed.
  • Weak references, wrapped around a reference with WeakReference, are reclaimed as soon as the JVM garbage collection finds it.
  • A virtual reference is reclaimed in the same way as a weak reference, but it is placed in the ReferenceQueue queue before being reclaimed, and a virtual reference declaration must be passed to the ReferenceQueue queue. Because of this mechanism, virtual references are mostly used to handle references before they are destroyed.

How many ways can Java create objects?

There are four:

  • The new keyword
  • By reflex mechanism
  • Using the Clone mechanism
  • Through serialization and deserialization mechanisms

What is the difference between shallow copy and deep copy?

For example, if an object has a List, shallow copy and deep copy will have different effects.

  • Shallow copy: only the outer object is copied. The List referenced by it is not copied, so the original object and the List object of the copied object are the same.
  • Deep copy, the outer object is copied, all the objects that it references are copied, so the copied object, the List object that it references is the new one.

final, finalize() and finally, what is the difference?

  • final
    • Variables marked by the final keyword are constants
    • Classes marked by the final keyword are not inheritable
    • Methods marked with the final keyword cannot be overwritten
  • fi nalize
    • The finalize() method, which is defined on the Object class and is used for retrieving objects that are called back, is similar to the destructor in C++ and can be used for processing objects before they are destroyed, but is not recommended because of the risk of memory overflow caused by special processing after GC.
  • fi nally
    • finally is used to identify code blocks, often in conjunction with a try, which is executed before a return, and the code ina finally block is bound to execute whether or not an exception occurs in the try block.

How do I prevent SQL injection in JDBC

  • Use the PreparedStatement class instead of the Statement class.

Java collections, generics

What’s the difference between ArrayList and LinkedList?

  • The bottom layer of an ArrayList uses arrays, and its queries use indexes, so it is efficient. But adding and deleting elements is slow, because they require rearranging the array, such as removing the middle element, by moving the following element forward.
  • LinkedList uses a LinkedList at the bottom level. To add or delete elements, only the front and back nodes of elements need to be modified, so the efficiency is high, but the query efficiency is poor.

Difference between HashMap and HashTable

  • Different inheritance
    • HashMap is derived from AbstractMap class, and Hashtable is derived from Dictionary class.
  • Support for NULL is different
    • Hashtable, key, and value cannot be null
    • For HashMap, the key can be null, but there can only be one such key, and the value of multiple keys can be null
  • Thread safety
    • Hashtable is thread-safe, and each of its methods has the synchronized keyword, so it can be used in multithreaded environments.
    • HashMap is not thread-safe, but it is more efficient than Hashtable, plus most scenarios are single-threaded. In a multi-threaded environment, ConcurrentHashMap is recommended because it uses segwise locking and does not lock the entire data.

The difference between Collections and Collections

  • Collection is the parent interface of a Collection. The child interfaces include List and Set.
  • Collections is a utility class for the collection class, providing a number of static methods for operations on Collections, searching, sorting, and thread-safe wrapping.

List, Set, Map

  • List, ordered, repeatable
  • Set, unordered, non-repeatable
  • Map, unordered, key-value pair storage, non-repeatable Key, repeatable Value

What’s the difference between Array and ArrayList?

  • Both Array and ArrayList are used to store data. The bottom layer of ArrayList is implemented using Array, but it expands Array’s capacity and functions.

Talk about the List interface and its implementation class

  • The List interface is a subinterface of the Collection interface. The implementation classes of the List interface are ordered and repeatable. The List interface implementation classes are ArrayList, Vector, and LinkedList.
  • The implementation class
    • ArrayList, which is implemented through arrays, supports index lookups, so it supports random access to elements. The disadvantage is that when adding and deleting elements, the array needs to be copied and moved, which is relatively high cost, so it is suitable for random access, not suitable for insertion and deletion.
    • Vector, the same as ArrayList, is implemented through arrays, but its methods are synchronized lock, so it can be accessed in a multi-threaded environment, avoid the inconsistent problem caused by concurrent reads and writes to the collection at the same time, but synchronization requires performance overhead, so its efficiency is lower than ArrayList.
    • LinkedList, which is implemented with a LinkedList at the bottom, is very suitable for dynamic insertion and deletion of elements, but the efficiency of random access and traversal is relatively low. In addition, it implements a Deque interface, so it has methods to operate the header and tail elements, so it can be used as a stack and queue.

Talk about the Set interface and its implementation classes

  • The Set interface is also a subinterface of the Collection interface. The implementation classes of the Set interface are not repeatable. The implementation classes of the Set interface are HashSet, TreeSet, LinkedHashSet. The non-repeatable feature of a Set is to compare elements by calling hashCode(). If they are identical, equals() is called to compare them.
  • The implementation class
    • HashSet. The underlying implementation is a Hash table. The non-repeatable feature is to compare elements by calling hashCode(). If they are identical, equals() is called to compare them.
    • The underlying implementation of TreeSet is a binary tree that sorts elements as they are inserted. It requires the comparison of inserted elements to implement the Comparable interface, duplicates the compareTo() function, or passes in a custom Comparator object when creating a TreeSet. Otherwise it will throw at runtime Java. Lang. ClassCastException type of exception.
    • LinkedHashSet, the underlying use of LinkedHashMap, but it uses only the unique feature of the Key in the Map to ensure that it is not repeatable.

Talk about the Map collection and its implementation classes

  • Map interface, a collection class interface specifically used to implement key-value pair operations. Its implementation classes are HashMap, HashTable, TreeMap, and LinkedHashMap.
  • The implementation class
    • HashMap, the underlying implementation of the Hash table, which determines the location of the storage through the hashCode of the element, so it has fast query speed, but the order of its traversal is uncertain. A HashMap allows only one key to be null, but multiple key values can be null. HashMap is non-thread-safe, so concurrent writes to a HashMap in a multithreaded environment are inconsistent. The Collections synchronizedMap() method wraps HashMap to make it thread-safe. Or use ConcurrentHashMap.
      • Before JDK1.8, the underlying implementation of HashMap is Hash table and linked list. When Hash conflicts occur, elements in the same position will be stored in a linked list. However, when there are many elements, the query will be traversed by the linked list, which is inefficient.
      • In JDK1.8, the underlying implementation of HashMap is Hash table and linked list \ red-black tree. When the number of linked list elements exceeds 8, the linked list is converted to red-black tree to avoid traversal and optimize query efficiency.
    • HashTable is thread-safe. Each of its methods has the synchronized keyword, so it can be used in multi-threaded environments.
    • The underlying implementation of TreeMap is a binary tree that can sort elements when they are added. It requires that elements implement the Comparable interface, override the compareTo() function, or pass in a custom Comparator object when creating a TreeMap. Otherwise it will throw at runtime Java. Lang. ClassCastException type of exception.
    • LinkedHashMap, which is a subclass of HashMap, preserves the insertion order, whereas other Map implementation classes are unordered.

What are generics? What is generic erasure?

  • Generics can abstract types and reuse them to support different types, such as the container class ArrayList. ArrayList can store different elements through generics, and Array elements after generics are concrete types instead of objects, avoiding the trouble of type conversion, and the compilation will report errors. Avoids type casting errors that can occur with type casting.
  • Generic erasure, because Java generics are implemented at compile time, generics information does not exist in the generated Java bytecode, so the generics information, when the compiler compiles, will remove the generic information, this process is generic erasure. So any generic information attached to the List is invisible to the JVM and is of type Object to it.

Java exception interview question

What are the types of Java exceptions?

  • Compile time exception
  • Runtime exception

This section describes the Java exception handling mechanism

  • To catch exceptions, use try-catch-finally
  • Throws exceptions. Throws throws the throws keyword

If you customize an exception

  • Inheriting an Exception class, run-time inheriting RuntimeException and compile-time inheriting Exception.

Try-catch-finally, try has a return, finally is executed?

  • Execution, finally, is executed before a return, regardless of whether there is an exception in the try. In addition, if a finally return is executed before the return of the try, the return in the try will not be executed.

Relationship between Excption and Error

  • Excption and Error are subclasses of Throwable.
  • Excption has run-time and compile-time exceptions, both of which can be caught and handled.
    • Common compile-time exceptions include: IOException, FileNotFoundException, and SQLException. These exceptions must be handled in the code; otherwise, an error will be reported during compilation.
    • Common are: a runtime exception ClassCastException, IndexOutOfBoundsException, NullPointerException
  • Errors, like runtime exceptions, are not checked for by the compiler. An error occurs when resources are insufficient, constraints fail, or other conditions occur that prevent another program from continuing. The program itself cannot fix these errors. A common subclass is OutOfMemoryError

IO and NIO in Java

Java IO flows are divided into several types

  • According to the flow direction, the flow can be divided into input flow and output flow
  • According to the unit of operation, it can be divided into byte stream and character stream
  • Flows can be divided into node flows and processing flows according to their roles

There are more than 40 classes in the Java IO stream, all derived from the following four abstract base classes:

  • InputStream\Reader, the base class for all input streams, InputStream for character input streams, Reader for character input streams.
  • OutputStream\Writer, the base class for all output streams. OutputStream is a byte OutputStream, and Writer is a character OutputStream.

What is the difference between IO and NIO in Java?

  • NIO is called New IO. Introduced in JDK1.4, NIO and IO serve the same purpose and function, but are implemented in different ways. NIO is much more efficient than IO because it uses blocks and IO is Byte. Java provides two sets of NIOS, one for files and one for network programming.

What are the common IO classes?

  • byte
    • FileInputSteam, FileOutputStream
    • BufferInputStream, BufferedOutputSream
  • character
    • FileReader, FileWriter
    • BufferReader, BufferedWriter
  • Object serialization
    • ObjectInputStream, ObjectOutputSream

What is Java NIO

  • NIO has three main core parts: channels o ffer(channels), Bu o ffer(buffers) and Selector.
  • While traditional IO operates on byte streams and character streams, NIO operates on Channel and Bu o ffer(buffers), where data is always read into, or written from, channels. Selector is used to listen for events on multiple channels (e.g., a connection is opened, data is arrived). Thus, a single thread can listen on multiple data channels.
  • The first big difference between NIO and traditional IO is that WHILE IO is stream-oriented, NIO is buffer-oriented.

What is NIO’s Channel

  • Channel, generally translated as Channel. A Channel is about the same level as a Stream in IO. A Stream is one-way, such as InputStream and OutputStream, while a Channel is two-way. It can be used for both read and write operations.
  • The main implementation class of a Channel in NIO
    • FileChannel (file operation)
    • DatagramChannel (UDP operation)
    • SocketChannel (TCP client)
    • ServerSocketChannel (TCP Server)

What is NIO Bu o ffer

  • Bu o ffer o ffer, for its name, a buffer is actually a container for a contiguous array. Channel provides channels for reading data from files o ffer from networks, but data read or written must be via Bu o ffer.
  • The process of sending data from a client to a server, which then receives the data. When clients send data, they must deposit it in Bu o ffer and then write its contents to the channel. The server side that receives data must read it into Bu o ffer via channels and then take it out of Bu o ffer for processing.
  • In NIO Bu o ffer is a top-level parent class o ffer, which is an abstract class. The common subclasses Bu o ffer are
    • ByteBu ff er
    • ShortBu ff er
    • IntBu ff er
    • LongBu ff er
    • FloatBu ff er
    • DoubleBu ff er
    • CharBu ff er

What is a Selector for NIO

  • The Selector class is the core class of NIO. The Selector class can detect whether an event has occurred on multiple registered channels. If an event has occurred, the Selector class can obtain the event and then handle the corresponding response for each event. In this way, you can manage multiple channels, and thus multiple connections, with just one thread. This allows functions to be called only when a connection actually has an read or write event, greatly reducing system overhead, eliminating the need to create a thread for each connection, maintaining multiple threads, and avoiding the overhead of context switching between multiple threads.

Java reflection interview questions

Does Java reflection create objects more efficiently or does New create objects more efficiently

  • Creating objects using new is efficient. Through reflection, first look for class resources, using the class loader to create, the process is cumbersome, so the efficiency is low

The role of Java reflection

  • The reflection mechanism is that, at runtime, all properties and methods of any class can be known; For any object, you can call any of its methods. In Java, given the name of a class, all information about the class can be obtained through reflection.

Where does reflection come in

For example: load MySQL driver class, such as Hibernate, MyBatis and other frameworks will be used.

/ / load the MySQL Driver Class. Class.forname ('. Com. MySQL. JDBC Driver. The Class ');Copy the code

Pros and cons of reflection mechanisms

  • advantages
    • Ability to dynamically retrieve instances of classes at runtime for increased flexibility
    • Combined with dynamic compilation
  • disadvantages
    • With reflection, the performance is low and the bytecode needs to be parsed, parsing the objects in memory
    • Relatively insecure, breaking encapsulation (because private methods and properties can be obtained through reflection)
  • The solution
    • By setAccessible(true), turn off JDK security checks to speed up reflection
    • After the first reflection, there will be a cache, and the next reflection will be much faster
    • Refl ectASM tool classes that generate bytecode in a way to speed up reflection

Java notes interview questions

What are annotations?

  • Annotations are a way and method provided by Java to associate information and metadata with elements in a metaprogram. An Annatation is an interface that allows a program to use reflection to get an Annotation object for an element in a given program, and then use that Annotation object to get metadata information from the Annotation.

What are the four standard meta-annotations?

  • @target, the range of objects modified
    • @target specifies the range of objects that the Annotation decorates: Annotations can be used for packages, types (classes, interfaces, enumerations, Annotation types), type members (methods, constructors, member variables, enumerated values), method parameters, and local variables (such as loop variables, catch parameters). Target is used in the Annotation type declaration to clarify the target it modifies
  • @Retention defines the length of time that is retained
    • Retention defines the length of time that the Annotation is retained: represents the level at which the Annotation information needs to be retained, and is used to describe the Annotation’s life cycle (i.e., the range in which the described Annotation is valid). The value (RetentionPoicy) is as follows:
      • SOURCE: valid in the SOURCE file (i.e. retained in the SOURCE file)
      • CLASS: valid in a CLASS file (i.e., CLASS reserved)
      • RUNTIME: valid at RUNTIME (i.e., reserved at RUNTIME)
  • Inherited indicates that an annotated type is Inherited
    • An @Inherited meta-annotation is a markup annotation. @Inherited indicates that an annotated type is Inherited. If an annotation type with the @Inherited annotation is applied to a class, the annotation will be applied to a subclass of that class.

Java multithreading, and hair questions

There are several ways to implement multithreading in Java

There are four ways

  • Thread class inheritance
  • Implement the Runnable interface
  • Implement the Callable interface to create Thread threads through the FutureTask wrapper
  • Implement multithreading with returns using ExecutorService, Callable, and Future (that is, manage the three ways with ExecutorService)

How do I stop a running thread

  • Using the exit flag, the thread exits normally, terminating when the run() method completes
  • Use the stop method to force termination, but this is not recommended as it may result in inconsistent data for thread operations
  • Use the interrupt method to interrupt the thread and catch InterruptedException

What is volatile? Can order be guaranteed?

  • Once shared variables (member variables of a class, static member variables of a class) are volatile, two layers of semantics exist
    • The shared variable is visible to different threads, meaning that one thread makes changes to the value of the variable immediately visible to the other threads. The volatile keyword forces the changes to be synchronized to main memory.
    • Forbid instruction rearrangement, forbid the compiler to optimize the code order, avoid multiple initialization in the singleton Double Check, ensure orderliness.
  • Note that volatile does not guarantee atomicity.

What is the difference between the start() and run() methods in Thread?

  • The start() method is used to start the newly created thread, and the run() method is called inside start(), which does not have the same effect as calling run() directly. When you call the run() method, it will only be called in the original thread. No new thread will be started, so the start() method will start a new thread.

What is the difference between Synchronized and ReentrantLock in Java?

  • The similarities

    • Both synchronous way there are many similarities, they are all locked mode synchronization, and synchronous blocking type, that is to say, as if a thread got a lock object, entered the synchronized block, other threads to access this synchronized block must be blocked on the outside of the synchronized block waiting, and thread blocking and awakens the price is relatively high.
  • The difference between

    • For Synchronized, it is a Java language keyword that is mutually exclusive at the native syntax level and requires JVM implementation.
    • ReentrantLock is an API level mutex provided after JDK 1.5, which requires lock() and UNLOCK () methods combined with try/finally statement blocks to complete.
    • Synchronized is compiled and forms the bytecode instructions monitorenter and Monitorexit, respectively, before and after the Synchronized block. When monitorenter is executed, it first tries to acquire the object lock. If the object is not locked or the current thread already owns the object lock, increments the lock counter by one. Accordingly, monitorexit decrement the lock counter by one. When it reaches zero, the lock is released. If the object lock fails to be acquired, the current thread blocks until the object lock is released by another thread.
  • Already features

    • The wait can be interrupted. When the thread holding the lock does not release it for a long time, the thread waiting can choose to give up the wait, which is equivalent to avoiding deadlock in terms of Synchronized.
    • Synchronized lock is an unfair lock. The default constructor of ReentrantLock is to create an unfair lock. It can be set to true, but the performance of a fair lock is not very good.
    • The lock binds multiple conditions, and a ReentrantLock object can bind pairs of objects at the same time.

What is the difference between SynchronizedMap and ConcurrentHashMap?

  • SynchronizedMap(), like Hashtable, synchronizes the entire map when all map methods are called. The ConcurrentHashMap implementation is more elaborate, locking all the buckets in the map. So, as long as one thread accesses the map, other threads cannot enter the map, but if one thread accesses a bucket of ConcurrentHashMap, other threads can still perform certain operations on the map.
  • ConcurrentHashMap, therefore, in terms of performance and security, obviously than Collections. SynchronizedMap () more advantage. At the same time, synchronous operations are precisely controlled to the bucket so that ConcurrentModifi cationExceptions are not thrown if other threads try to make data modifications to the map even while traversing the map.

What is the difference between submit() and execute() methods in Java thread pools?

Both methods can submit tasks to a thread pool.

  • The execute() method, which returns void, returns no value after the task is executed, and is defined in the Executor interface.
  • The submit() method, which returns a Future object holding the results of the computation, is defined in the ExecutorService interface, which extends the Executor interface.

Talk about what you know about synchronized

  • The synchronized keyword addresses the synchronization of access to resources between multiple threads. The synchronized keyword ensures that only one thread can execute a method or code block modified by it at any time.
  • In earlier versions of Java, synchronized was a heavyweight Lock that was inefficient because the monitor Lock relied on the underlying operating system’s Mutex Lock, and Java threads were mapped onto the operating system’s native threads.
  • If you want to suspend or wake up a thread, the operating system needs to help complete it. When the operating system realizes the switch between threads, it needs to transform from the user state to the kernel state, which requires a relatively long time and a relatively high time cost, which is why the efficiency of early synchronized is low.
  • Java has improved synchronized from the JVM level since Java 6, so synchronized lock efficiency is now well optimized. JDK1.6 introduces a number of optimizations to lock implementation, such as spin locking, adaptive spin locking, lock elimination, lock coarser, biased locking, lightweight locking and other techniques to reduce the overhead of locking operations.

What does the volatile keyword do?

  • Once a shared variable (a member variable of a class, or a static member variable of a class) is volatile, two layers of semantics are in place: visibility is guaranteed for different threads operating on the variable; if one thread changes the value of a variable, the new value is immediately visible to other threads.
  • Command reordering is disabled.
    • 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, and does not guarantee 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.

Briefly explain your understanding of thread pools

  • Reduce resource consumption. Reduce the cost of thread creation and destruction by reusing created threads.
  • Improve response speed. When a task arrives, it can be executed immediately without waiting for the thread to be created.
  • Improve thread manageability. Threads are scarce resources. If they are created without limit, they will not only consume system resources, but also reduce system stability. Thread pools can be used for unified allocation, tuning, and monitoring.

Thread life cycle

  • NEW State (NEW)
    • When a program creates a thread using the new keyword, the thread is in the new state, where the JVM allocates memory and initializes the values of its member variables.
  • RUNNABLE state
    • When the thread object calls the start() method, the thread is in the ready state. The Java virtual machine creates a method call stack and a program counter for it to wait for the schedule to run.
  • RUNNING Status
    • If a thread in the ready state acquires the CPU and begins executing the thread body of the run() method, it is running.
  • The state of being BLOCKED
    • A blocked state is when a thread gives up CPU usage for some reason, giving up CPU timeslice and temporarily stops running. Until the thread enters the runnable state, it has no chance to get the CPU timeslice again and go to the running state.
      • There are three types of obstruction
        • Wait -> Wait column), the running thread executes the O.wait () method, and the JVM puts the thread to waitting Queue.
        • Lock -> lock pool. When a thread that is running acquires a lock on an object that is being held by another thread, the JVM places that thread in the lock pool.
        • Sleep (long ms) or t.join() methods, or when an I/O request is made, the JVM puts the running Thread in the blocked state. When the sleep() state times out, when the join() wait thread terminates or times out, or when I/O processing is complete, the thread returns to the runnable state.
  • Thread DEAD
    • A thread ends in one of three ways, and then dies.
      • The run() or call() method completes, and the thread terminates normally.
      • The thread throws an uncaught Exception or Error, and the thread ends abnormally.
      • Call stop to stop. Terminate the thread by calling its stop() method directly – this method is usually deadlocked and is not recommended.

What is optimism lock?

  • Optimistic locking is a kind of optimistic thought that reading more than writing less, meet low likelihood of concurrent write, every time to fetch the data that other people will not change, so will not lock, but at the time of update will assess the during that time, people have to update the data, at the time of writing in a first read the current version number, and then lock operation (compared with the previous version number, Update if it is the same, and repeat if it fails.
  • Optimistic locking in Java is basically implemented through CAS operation, which is an updated atomic operation. The CAS operation compares the current value with the passed value. If the current value is the same as the passed value, it will be updated, otherwise it will fail.

What is pessimism lock?

  • Pessimistic locking is the pessimistic thinking, that is, the likelihood of concurrent write is high, every time to get the data will think that others will modify the data, so every time the data will be locked, so that others want to read and write the data will block until the lock. Pessimistic lock in Java is Synchronized. In AQS framework, CAS optimistic lock is first tried to obtain the lock. If it fails to obtain the lock, it will be converted to pessimistic lock, such as RetreenLock.

What are reentrant locks (recursive locks)

  • This article is about reentrantlocks in the broad sense, not reentrantLocks in JAVA alone. A reentrant lock, also known as a recursive lock, means that after the outer function of the same thread acquires the lock, the inner recursive function still has the code to acquire the lock, but is not affected. ReentrantLock and synchronized are both reentrant locks in JAVA environments.

Fair and unfair locks

  • Fair Lock
    • Before locking, check whether there are queued threads. The queued threads are preferentially queued. First come, first served.
  • Nonfair Lock
    • When the lock is added, it does not consider the queuing problem, and directly tries to obtain the lock. If the lock cannot be obtained, it will automatically wait at the end of the queue
  • contrast
    • The performance of an unfair lock is 5 to 10 times higher than that of a fair lock, because a fair lock requires the maintenance of a queue with multiple cores.
    • Synchronized is an unfair lock in Java, and the default lock() method of ReentrantLock uses an unfair lock.

The difference between Executor and Executors in Java?

  • Different methods of the Executors tool class created different thread pools according to our requirements to meet business requirements.
  • The Executor interface object can perform our threading tasks.
  • The ExecutorService interface extends and inherits the Executor interface, providing additional methods for obtaining the status of tasks executed and the return value of tasks. Custom thread pools can be created using ThreadPoolExecutor.
  • The Future represents the result of an asynchronous calculation, which provides a way to check that the calculation is complete while waiting for it to complete, and to get the result of the calculation using the get() method.

MySQL interview questions

What is a database engine?

  • Database storage engine is the bottom software organization of database. Database management system (DBMS) uses data engine to create, query, update and delete data. Different storage engines provide different storage mechanisms, indexing techniques, locking levels, and other functions. Different storage engines can be used to obtain specific functions. Many different database management systems now support many different data engines.
  • Storage engines include: 1. MyIsam, 2. InnoDB, 3. Memory, 4. Archive, 5.

What is InnoDB’s underlying data structure? What scenarios are applicable?

  • The underlying data structure of InnoDB is B+ tree, and each node of the B+ tree corresponds to a page of InnoDB. The size of page is fixed, usually set to 16K. Non-leaf nodes only have key values, while leaf nodes contain data.
  • Applicable scenario
    • Frequently updated tables are suitable for handling multiple concurrent update requests.
    • Support transactions.
    • Recovery from disasters (via bin-log, etc.)
    • Foreign key constraints (only it supports foreign key constraints)
    • Support for automatic increment of column attributes (auto_INCREMENT)

What are the advantages and disadvantages of MyIASM?

  • MyIASM is the default MySQL engine
  • advantages
    • ISAM performs reads quickly and does not consume large amounts of memory and storage resources.
  • disadvantages
    • Transactions are not supported.
    • Table-level locking, which does not support row-level locking and foreign keys, is less efficient when an INSERT or UPDATE data operation requires locking the entire table.

Differences between InnoDB and MyISAM

  • InnoDB supports transactions. MyISAM does not support transactions. InnoDB adds transactions to each SQL statement by default and commits them automatically.
  • InnoDB supports foreign keys, MyISAM does not. Converting an InnoDB table containing foreign keys to MyISAM will fail.
  • InnoDB is a clustered index, data files and indexes are bound together, must have a primary key, through the primary key query is very efficient. MyISAM is a non-clustered index, where data files and indexes are separated.
  • InnoDB does not store the exact number of rows in a table. Select count(*) from a table requires a full table scan. MyISAM uses a variable to store InnoDB.
  • InnoDB does not support full-text indexing, while MyISAM does, so MyISAM queries are more efficient.

What is an index? How many indexes are there? The more indexes, the better?

  • Index is a method to speed up the retrieval of data in a table. The index of a database is similar to the index of a book. In a book, users can quickly find the information they need without flipping through the whole book.
  • There are 4 different indexes in MySQL
    • The primary key index
    • The only index
    • Normal index
    • The full text indexing
  • The more indexes, the better, creating indexes also needs to consume resources, one is to increase the storage space of the database, and the other is to insert and delete table data, it takes more time to maintain the index.

Common Indexing principles

  • A field is unique, and creating a unique index makes it faster to determine a record through the index.
  • Fields that often need to be sorted, grouped, and syndicated are indexed.
  • Indexes fields that are commonly used as query criteria.
  • Delete indexes that are no longer used or rarely used.
  • Index columns cannot participate in the calculation. Queries with functions do not participate in the index.
  • Left-most prefix matching rule.

What are the three paradigms of databases?

  • In the first normal form, the columns are not separable
  • In the second normal form, rows have uniquely differentiated fields with primary key constraints
  • In the third normal form, non-primary attributes of a table cannot depend on non-primary foreign key constraints of other tables

What are database transactions?

  • A TRANSACTION is a series of operations that are performed as a single logical unit of work and are submitted to the system as a whole, and either all or none of them are executed.
  • A transaction is an indivisible unit of work logic. A transaction must have the following four properties, referred to as ACID properties
    • Atomicity
      • A transaction is a complete operation. The steps of a transaction are indivisible (atomic); All or none.
    • Consistency
      • When the transaction completes, the data must be in a consistent state.
    • Isolation
      • All concurrent transactions that modify data are isolated from each other, which means that a transaction must be independent and it should not depend on or affect other transactions in any way.
    • They want to be permanent.
      • After a transaction completes, its changes to the database are kept permanent, and the transaction log can keep the transaction permanent.

SQL optimization

  • Do not use SELECT * in queries
  • Minimize subqueries and use associated queries (left Join, right Join, inner Join) instead
  • Reduce the use of IN or NOT IN and use exists, NOT EXISTS, or associative query statements instead
  • Or queries should be replaced with union or union all (union all is better when confirming that there is no duplicate data or eliminating duplicate data)
  • Use in where clauses should be avoided! = or <> otherwise the engine will abandon the index for a full table scan.
  • Avoid null values for fields in the WHERE clause, which will cause the engine to abandon the index and perform a full table scan, as in: Select id from t where num is null select id from t where num is null select id from t where num = 0

Difference between DROP, DELETE, and TRUNCate

  • Delete and TRUNCate delete only the data of the table but not the structure of the table.
  • Delete Deletes a record without deleting the table structure. The DELETE statement can add WHERE. The deletion operation is recorded in the log and can be rolled back.
  • Truncate Deletes records and does not delete table structures. The TRUNCate statement cannot add WHERE. The deletion operation is not recorded in logs, cannot be rolled back, and triggers are not activated.
  • Drop deletes records and structures and does not activate triggers.
  • In terms of delete speed, drop > TRUNCate > DELETE

What is inner join, left outer join, right outer join?

  • Inner Join: Matches associated records in two tables. (Discard unrelated parts in 2 tables)
  • Left Outer Join (Left Outer Join) : In addition to matching the associated records in the two tables, the remaining records in the Left table will be matched. Unmatched fields in the right table will be represented by NULL. (matches the left record, or NULL if no record matches the right table)
  • Right Outer Join: In addition to matching the associated records in the two tables, the remaining records in the Right table will be matched. Unmatched fields in the left table will be represented by NULL. (matches the right record, or NULL if no record in the left table matches it)

What are the problems associated with concurrent transactions?

  • Dirty read. When a transaction reads data, modifies it, but does not commit it to the database, and another transaction also reads and consumes the data, the data read by the other transaction is “Dirty data”. The processing based on “Dirty data” may be incorrect.
  • Lost to modify, when one transaction reads data, another transaction also reads data, the first transaction changes data, the second transaction also changes data, so the first transaction is Lost because of “Lost to modify”, such as transaction 1 read data A=20, Transaction 2 also reads A=20, transaction 1 changes A=A1, transaction 2 also changes A= a-1, the final result is A=19, transaction 1 changes are lost.
  • Unrepeatableread: a transaction reads one data for several times. Before the transaction ends, another transaction also accesses the data. If the second transaction modifies the data, the data read by the first transaction may be different, so it becomes Unrepeatableread.
  • Phantom read, similar to unrepeatable reads, occurs when one transaction reads several rows of data, and then another transaction inserts some data. In subsequent queries, the first transaction finds more data that was not there before, as if it was an illusion.

The difference between unrepeatable and phantom reads

  • Non-repeatable reads focus on modification. For example, when a record is read multiple times, the value of a column of the record is changed.
  • The focus of illusionary reading is to add or subtract, such as reading multiple times and finding that records have increased or decreased.

What are the transaction isolation levels? What is the default isolation level for MySQL?

The SQL standard defines four isolation levels

  • Read-uncommitted: The lowest isolation level that allows UNCOMMITTED data changes to be READ, potentially resulting in dirty, illusory, or unrepeatable reads.

  • Read-committed: Allows concurrent transactions to READ data that has been COMMITTED, preventing dirty reads, but magic or unrepeatable reads can still occur.

  • REPEATABLE-READ: Multiple reads of the same field give the same result, unless the data is modified by the transaction itself. This can prevent dirty and unrepeatable reads, but phantom reads are still possible.

  • SERIALIZABLE: Highest isolation level, fully subject to ACID isolation level. All transactions are executed one by one so that interference between transactions is completely impossible. That is, this level prevents dirty reads, unrepeatable reads, and phantom reads.

  • MySQL InnoDB storage engine supports isolation level REPEATABLE READ by default, we can SELECT @@tx_ISOLATION; Command to view.

Note that MySQL InnoDB uses next-key Lock algorithm in REPEATABLE READ isolation level to avoid phantom reads. MySQL InnoDB uses next-key Lock algorithm in REPEATABLE READ isolation level to avoid phantom reads. REPEATABLE-READ level also meets the isolation requirements of SERIALIZABLE level. Most database isolation levels are read-committed, because the higher the level, the more locks the transaction requests have.

How to optimize large tables?

  • Limit the scope of the query data, such as order history, to control the query for orders within a month.
  • Read, write separation, master library copy write, from the library responsible for reading.
  • Vertical partition. For example, a user table contains both user login information and basic user information. You can split the user table into two tables, that is, divide the data columns into multiple tables.
  • Horizontal partitioning, which keeps the table structure unchanged, can support very large amounts of data by dividing data into different tables or libraries using a strategy such as year, month, table per year, or table per month. Horizontal partition can only solve the problem of large amount of data stored in a single table, but because the data is still on a machine, it does not have any significance to provide concurrency, so horizontal partition is the best repository.

How to deal with the primary key ID after the database is divided into different tables

The id of each table is accumulated from 1. This is not correct. We need a globally unique ID to support this.

  • UUID, too long, and unordered, inefficient query, comparison used to generate file names, etc.
  • Each database sets different step sizes to generate non-repeated ids. This method generates ids in order, but requires independent deployment of database instances, high cost, and performance bottlenecks.
  • Using Redis to generate ID, good performance, flexible and convenient, does not rely on the database, but the introduction of new components resulting in more complex system, reduced availability, more complex coding, increased system cost.
  • Twitter snowflake algorithm.
  • Leaf distributed ID generation system of Meituan, Leaf is an open source distributed ID generator of Meituan, which can ensure global uniqueness, trend increasing, monotonic increasing, information security, but also relies on relational database, Zookeeper and other middleware.

What types of locks are available in MySQL?

  • Table lock: low overhead, fast lock; No deadlocks occur; The lock granularity is large, and the probability of lock conflict is high and the concurrency is low.
  • Page lock: the overhead and lock time are between table lock and row lock. Deadlocks occur; The locking granularity is between table locks and row locks, and the concurrency is average
  • Row-level lock: expensive, slow lock; Deadlocks occur; The lock granularity is the lowest, the probability of lock conflict is the lowest, and the concurrency is the highest.

What’s the difference between NOW() and CURRENT_DATE()?

  • The NOW() command is used to display the current year, month, date, hour, minute, and second.
  • CURRENT_DATE() displays only the current year, month, and date.

Optimization strategies for locking

  • Reading and writing separation
  • Subsection locking
  • Reduces the duration of lock holding
  • Multiple threads should acquire resources in the same order as far as possible. The granularity of locks should not be too refined, otherwise threads may lock and release too many times, which is not as efficient as adding a large lock at a time.

The underlying implementation principles and optimizations of indexes

  • The bottom layer is a B+ tree, an optimized B+ tree.
  • InnoDB recommends using the default primary key increment as the primary index for most tables by adding a pointer to the next leaf.

What is the purpose of the index?

  • Fast access to specific information in data tables to improve retrieval speed.
  • Accelerating joins between tables and using grouping and sorting clauses for data retrieval can significantly reduce grouping and sorting time in queries.
  • Create unique indexes to ensure the uniqueness of each row in a database table.

What are the negative effects of indexes on database systems?

  • Creating and maintaining indexes takes time, which increases with the volume of data; Indexes take up physical space. Not only tables take up data space, but each index takes up physical space. Indexes are maintained dynamically when tables are added, deleted, or modified, which slows down data maintenance.

What are the principles for indexing data tables?

  • Build indexes on the most frequently used fields to narrow the query.
  • Build indexes on frequently used fields that need to be sorted.

When is it inappropriate to build an index?

  • Indexes are not appropriate for columns that are rarely involved in a query or that have a lot of duplicate values.
  • For some special data types, such as text fields, indexes are not appropriate.

When does an index fail

  • LIKE statements beginning with “%”, fuzzy match
  • The index is not used before OR after the OR statement
  • Implicit conversion of data type (vARCHar may be automatically converted to int if not quoted)

How to optimize MySQL in practice

  • SQL statement and index optimization
  • Optimization of database table structure
  • Optimization of system configuration
  • Hardware optimization

Methods to optimize the database

  • Select the most applicable field attributes, minimize the width of the defined field, and set the field as NOT NULL as possible. For example, it is better to use ENUM enumeration for ‘province’ and ‘gender’
  • Use joins instead of subqueries
  • Instead of manually created temporary tables, use unions
  • Transaction processing
  • Lock tables and optimize transaction processing
  • Apply foreign key, optimize lock table
  • indexing
  • Optimized query statement

MySQL > select key (s), primary key (s), unique index (s), and joint index (s)

  • Indexes are special files (indexes on InnoDB tables are part of the table space) that contain Pointers to all the records in the table.
  • The only job of a plain INDEX (an INDEX defined by the KEY or INDEX keyword) is to speed up access to data.
  • Normal indexes allow indexed data columns to contain duplicate values. If you can determine that a column will contain only values that differ from each other, you should define it as a UNIQUE index when creating an index for that column using the keyword UNIQUE. In other words, a unique index guarantees the uniqueness of the data record.
  • A PRIMARY KEY is a special unique index. Only one PRIMARY KEY can be defined in a table. A PRIMARY KEY is used to uniquely identify a record.
  • An INDEX can cover multiple data columns, such as the INDEX(columnA, columnB) INDEX, which is a federated INDEX.
  • Indexes can greatly improve the speed of querying data, but slow down the speed of inserting, deleting, and updating tables because of the need to manipulate index files while performing these writes.

What is the cause of SQL injection vulnerability? How to prevent it?

  • The cause of SQL injection: During the process of program development, the client can submit some SQL statements through the global variables POST and GET for normal execution without paying attention to the standard writing of SQL statements and filtering of special characters.

  • A way to prevent SQL injection

    • Enable the magic_QUOtes_GPC and magic_QUOtes_Runtime Settings in the configuration file to use addslashes for SQL statement conversion
    • Do not omit double and single quotation marks when writing Sql statements.
    • Filter out some keywords in SQL statements: UPDATE, INSERT, delete, select, *.
    • Improve the database table and field naming skills, some important fields according to the characteristics of the program named, not easy to guess.

Redis interview questions

Redis data type?

  • Redis supports five data types: string, hash, list, set, and Zsetsorted set.

What are the benefits of using Redis?

  • Fast because the data is in memory, similar to a HashMap, which has the advantage of O1 time complexity for both lookup and operation).
  • Supports rich data types, such as String, list, set, Zset, and Hash.
  • Transactions are supported, and operations are atomic, meaning that changes to data are either all or none.
  • Rich features: can be used for cache, message, by key set expiration time, will be automatically deleted after expiration.

What advantages does Redis have over Memcached?

  • Instead of Memcached, where all values are simple strings, Redis supports richer data classes.
  • Redis is much faster than Memcached.
  • Redis can persist its data.

What are the differences between Memcache and Redis?

  • Storage mode: Memecache Stores all data in the memory. After a power failure, the data will hang. The data cannot exceed the memory size. Redis is partially stored on hard disk to ensure data persistence.
  • Data support types: Memcache support for data types is relatively simple. Redis has complex data types.
  • Use different underlying models: the underlying implementation methods and application protocols used to communicate with clients are different. Redis directly built the VM mechanism itself, because normal system calls to system functions would waste a certain amount of time moving and requesting.

Is Redis single process single thread?

  • Redis is single-process single-thread, Redis uses queue technology to change concurrent access into serial access, eliminating the overhead of traditional database serial control.

Redis persistence mechanism

  • RDB is the default Redis persistence mode. Memory data is saved as a snapshot to a binary file on a hard disk at a specified period of time. The data file to be generated is dump. RDB. The save parameter in the file is used to define the Snapshot period. (A snapshot can be either a copy or a replica of the data it represents.)

  • AOF: Redis appends every received Write command to the end of the file using the Write function, similar to MySQL’s binlog. When Redis restarts, it reconstructs the contents of the entire database in memory by re-executing the write commands saved in the file. When both methods are enabled, Redis preferentially selects AOF for data recovery.

What is cache avalanche, cache penetration, cache warm-up, cache update, cache degradation, and how to resolve it

Cache avalanche

  • define

    • We can simply understood as: due to the existing cache invalidation, new cache before the period (for example: adopt the same when we set the cache expiration time, at the same time a large area of flat deposit expired), all should have access to the cache request to query the database, and cause great pressure to the database CPU and memory, serious can cause database downtime. The whole system collapses in a chain reaction.
  • The solution

    • Most system designers consider locking (the most common solution) or queuing to ensure that there are not too many threads reading or writing to the database at once, thus avoiding a large number of concurrent requests falling on the underlying storage system in the event of a failure. Another simple solution is to spread out cache expiration times.

The cache to penetrate

  • define

    • Cache penetration is when the user queries for data that is not present in the database and certainly not present in the cache. As a result, the user will not find the query in the cache, and will have to query the database again each time, and then return null (equivalent to two useless queries). This allows the request to bypass the cache and go directly to the database, which is a common cache hit ratio issue.
  • The solution

    • The most common is to use a Bloom filter, hash all possible data into a large enough bitmap, a non-existent data will be intercepted by the bitmap, thus avoiding the query pressure on the underlying storage system. Alternatively, there is a more crude approach. If a query returns null data (either nonexistent or a system failure), we still cache the null result, but its expiration time is short, no more than five minutes. The simplest way to do this is to store the default values directly in the cache so that the second time you fetch the values in the cache, you don’t have to continue accessing the database.

Cache warming

  • define

    • Cache preheating this should be a relatively common concept, I believe many friends should be easy to understand, cache preheating is the system online, the relevant cache data directly loaded to the cache system. This avoids the problem of first querying the database and then caching the data when the user requests it! Users directly query cached data that has been preheated in advance!
  • The solution

    • Write a cache refresh page directly, manual operation when online.
    • The amount of data is small and can be loaded automatically at project startup.
    • Periodically refresh the cache.

The cache update

  • define

    • In addition to the cache invalidation policies provided by the cache server (Redis has 6 policies to choose from by default), we can also customize the cache invalidation policies according to the specific business requirements. There are two common policies.
  • The solution

    • Periodically clear expired caches.
    • ) When there is a user request, and then determine whether the cache used by this request is expired, expired to the underlying system to get new data and update the cache.
  • The advantages and disadvantages

    • Both have their advantages and disadvantages. The disadvantage of the first is that maintaining a large number of cached keys is quite troublesome.
    • The second disadvantage is that every time the user requests come over to determine the cache invalidation, logic is relatively complex! You can weigh which solution to use according to your own application scenario

Cache the drop

  • define

    • When traffic surges, service problems (such as slow or unresponsive response times) occur, or non-core services affect the performance of the core process, you still need to ensure that the service is still available, even at the expense of the service. The system can automatically degrade according to some key data, or manually degrade by configuring switches.
    • The ultimate goal of a downgrade is to ensure that the core service is available, even if it is lossy. And some services can’t be downgraded (add to cart, checkout).
  • Refer to Log Level Settings

    • General: For example, if some services occasionally time out due to network jitter or online services, they can be automatically degraded.
    • ) Warning: If the success rate of some services fluctuates within a period of time (for example, between 95 and 100%), the service can be automatically or manually degraded and an alarm is sent.
    • Error: For example, the availability rate is below 90%, or the database connection pool is overwhelmed, or the traffic suddenly increases to the maximum threshold that the system can handle, at this point, the system can be automatically demoted or manually demoted.
    • Critical error: For example, the data is wrong due to special reasons, and an emergency manual downgrade is required. The purpose of service degradation is to prevent the Redis service failure from causing an avalanche of database problems. Therefore, for unimportant cached data, a service degradation strategy can be adopted. For example, a common practice is that Redis fails to check the database, but directly returns the default value to the user.

Why is single-threaded Redis so fast

  • Pure memory operation.
  • Single threaded operation, avoiding frequent context switches.
  • A non-blocking I/O multiplexing mechanism is used.

Redis data types and usage scenarios for each data type

  • String. The most common set/get operation, value can be either a String or a number. Generally do some complex counting function of the cache.
  • The hash. Here value stores a structured object, and it is convenient to manipulate a field within it. Bloggers use this data structure to store user information when they do single sign-on. CookieId is taken as the key and 30 minutes is set as the cache expiration time, which can well simulate the effect similar to session.
  • The list. Using the List data structure, you can do simple message queue functions. In addition, there is another, can use lrange command, do based on redis paging function, excellent performance, good user experience. I also use a scene, very appropriate – take market information. It’s also a producer and consumer scenario. List can be a good way to complete the queuing, first-in, first-out principle.
  • The set. Because a set is a collection of non-repeating values. So you can do global deduplication function. Why not use a Set that comes with the JVM? Because our system is generally a cluster department, using the JVM’s own Set, more trouble, do a global to redo, a public service, too much trouble. In addition, it is the use of intersection, union, difference set and other operations, can calculate common preferences, all preferences, their own unique preferences and other functions.
  • Sorted set. Sorted set has a weight parameter score. The elements in the set can be sorted according to score. You can do ranking application, take TOP N operation

What is the persistence mechanism of Redis? What are their strengths and weaknesses?

Redis provides two persistence mechanisms, RDB and AOF

  • Redis DataBase (RDB) persistence mode: The semi-persistent mode records all key/value pairs of the Redis DataBase in the mode of data set snapshot. The data is written to a temporary file ata certain point in time. After the persistence, the temporary file is used to replace the last persistent file to achieve data recovery.

    • advantages
      • There is only one file dump. RDB for persistence.
      • Good DISASTER recovery, a file can be saved to a secure disk.
      • To maximize performance, fork the child process to complete the write operation and let the main process continue processing the command, so IO maximization. A separate child process is used for persistence, and the main process does not perform any IO operations, ensuring the high performance of Redis. When the data set is large, the startup efficiency is higher than that of AOF.
    • disadvantages
      • Data security is low. RDB is persisted for a period of time. If REDis fails during the persistence, data will be lost. So this approach is more suitable when data requirements are not rigorous.
  • AOF (Append-only file) persistence mode: all command line records are fully persisted and stored as AOF files in the format of redis command request protocol.

    • advantages
      • Data security, aOF persistence can be configured with appendfsync property, always, every command operation is recorded to the AOF file once.
      • If you write files in Append mode, you can use the redis-check-aof tool to solve data consistency problems even if the server breaks down during the process.
      • Rewrite pattern of THE AOF mechanism. It is possible to delete some of the AOF files (such as flushall) before they are rewrite (merge commands when the file is too large)
    • disadvantages
      • AOF files are larger than RDB files, and the recovery speed is slow.
      • When the data set is large, it is less efficient than RDB startup.

How to understand Redis transactions?

  • A transaction is a single isolated operation: all commands in the transaction are serialized and executed sequentially. The transaction is not interrupted by command requests from other clients.
  • A transaction is an atomic operation: all or none of the commands in a transaction are executed.

Spring interview questions

What is the Spring IOC container?

  • At the heart of the Spring framework is the Spring container. Containers create objects, assemble them together, configure them, and manage their full life cycle. The Spring container uses dependency injection to manage the components that make up an application. The container receives instructions for instantiating, configuring, and assembling objects by reading the provided configuration metadata. This metadata can be provided through XML, Java annotations, or Java code.

What is dependency injection?

  • In dependency injection, you don’t have to create objects, but you must describe how to create them. Rather than wiring components and services together directly in code, you describe which components in the configuration file require which services. The IoC container assembles them together.

How many ways can dependency injection be accomplished?

  • In general, dependency injection can be done in one of three ways
    • Constructor injection
    • Setter injection
    • Interface injection

What are the benefits of IOC?

  • Loose coupling of dependencies
  • Supports delay initialization and immediate initialization
  • Facilitate the testing of test cases in the test framework

How many scopes does Spring have?

  • Singleton, Singleton.
  • Prototype, multiple examples, regenerates an instance injection for each call.
  • Request, a Web project, creates an instance for each Http Request.
  • Session, a Web project, creates an instance for each Http Session.
  • GlobalSession, which is only useful in Portal applications, creates an instance for each Global Http Session.

What are the ways in which Spring automatically assembles beans?

  • Xml
    • ByName, find setter methods in the class, remove the set prefix, lower case, and use that name to find Bean instances in the container with that name as id.
    • You must ensure that there is only one instance of the type, otherwise Spring will not know which to inject and will report an error.
  • annotations
    • @autowired, which identifies a container instance injection on constructors, member methods, parameters, and member variables based on the variable type. Class instances must be unique.
    • @autowired + @qualifier. If there are multiple instances, add the @Qualifier annotation to specify the class instance with the specified ID for injection.
    • @resource, equivalent to the way @autowired + @Qualifier is combined into an annotation above.

What are the ways Spring transactions are implemented?

  • Through get DataSourceTransactionManager, programmatic transaction, manually open things, things, and things rollback operation.
  • Declarative thing
    • By declaring transaction agent factory TransactionProxyFactoryBean Bean specify the transaction manager Bean Bean and need the agent’s goals, so in the spring container will have a goal, a proxy Bean Bean You can use this bean to enhance things to the target bean.
    • The Transactional annotation, which is configured in the Spring XML configuration file to start Transactional annotations, can be added to specified functions.
    • Aspectj AOP is used to configure transactions, set pointcuts, and specify transaction properties, which specify transaction managers.

Talk about Spring’s transaction isolation level

Spring transaction isolation level has one more default than database transaction isolation level.

  • ISOLATION_DEFAULT (the default), which is a PlatfromTransactionManager default isolation level, using the database to the default transaction isolation level. The other four correspond to JDBC isolation levels.
  • ISOLATION_READ_UNCOMMITTED. This is the lowest isolation level for a transaction and allows another transaction to see the uncommitted data of that transaction. This isolation level produces dirty reads, unrepeatable reads, and phantom reads.
  • ISOLATION_READ_COMMITTED (read Committed) ensures that data modified by one transaction can only be read by another transaction, and that another transaction cannot read uncommitted data. This transaction isolation level avoids dirty reads, but unrepeatable and phantom reads may occur.
  • ISOLATION_REPEATABLE_READ (repeatable read). This transaction isolation level prevents dirty reads, unrepeatable reads, but phantom reads may occur. In addition to guaranteeing that one transaction cannot read uncommitted data from another transaction, it also guarantees non-repeatable reads.
  • ISOLATION_SERIALIZABLE This is the most expensive but reliable transaction isolation level where transactions are processed and executed sequentially. In addition to preventing dirty and unrepeatable reading, it also avoids phantom reading.

Spring transactions propagate properties

  • REQUIRED (default), if there is a current transaction, join it, if not, create a new one.
  • SUPPORTS, if there is no transaction, it is executed in a non-transactional manner.
  • MANDATORY, join the transaction if there is one, and throw an exception if there is no transaction.
  • REQUIRES_NEW, creates a new transaction and suspends it if one is currently present.
  • NOT_SUPPORTED, executed in a non-transactional manner, or suspends a transaction if one currently exists.
  • NEVER, executed nontransactionally, and throws an exception if a transaction is currently in place.
  • NESTED transactions have a very important concept, that is, an inner transaction depends on an outer transaction. If an outer transaction fails, the operation performed by the inner transaction will be rolled back. The failure of the inner transaction will not cause the rollback of the outer transaction.

What is AOP?

  • AOP(aspect-oriented Programming), namely Aspect Oriented Programming, is complementary to OOP(Object-oriented Programming) and provides a different perspective of abstract software structure from OOP. In OOP, we use a class as our basic unit, whereas in AOP, the basic unit is an Aspect.

What are the implementations of AOP?

The technologies for implementing AOP fall into two main categories.

  • Static proxy (refers to compilation using commands provided by the AOP framework to generate AOP proxy classes at compile time, hence also called compile-time enhancement)
    • Compile-time weaving (special compiler implementation)
    • Class load-time weaving (special class loader implementation)
  • Dynamic proxy (AOP proxy classes are generated in-memory at run time, and thus also run time enhancement)
    • JDK dynamic proxy
    • CGLIB

What is the difference between Spring AOP and AspectJ AOP?

  • Spring AOP is based on a dynamic proxy implementation and AspectJ is based on a static proxy implementation. Spring AOP supports only method-level cuts, while AspectJ AOP provides full AOP support, such as property-level cuts.

Describe the workflow of the DispatcherServlet

  • When the server receives the request, it is captured by the DispatcherServlet.
  • The DispatcherServlet queries the HandlerMapping based on the URL and finds the Handler and interceptor that encapsulates the HandlerExecutionChain.
  • The DispatcherServlet then finds the corresponding HandlerAdapter according to the Handler and invokes the preintercept of the interceptor.
  • Start the processing method of the Handlerc processor, and after the processing is completed, the HandlerAdapter transforms it into a unified ModelAndView, and calls the post-intercept of the interceptor.
  • According to the returned ModelAndView, through the ViewResolver, find the appropriate View page object, call the Render method of the View page object, pass in the model for rendering processing, and return the page data to the client.

Spring Boot interview question

What is Spring Boot?

  • Spring Boot is built on the existing Spring framework. Spring Boot provides many out-of-the-box Starter, which is larger than configuration by convention and provides many default configurations, reducing the need for a bunch of similar configuration files every time you start a project.

Why SpringBoot?

SpringBoot has the following advantages

  • Independent operation
    • Spring Boot is embedded with various servlet containers, such as Tomcat and Jetty, and now it is no longer necessary to deploy it in a WAR package. Spring Boot can run independently as long as it is made into an executable JAR package, and all dependencies are in a JAR package.
  • Simplify the configuration
    • Spring-boot-starter-web initiator, which is internally declared to rely on other components, simplifies maven configuration.
  • Automatic configuration
    • Spring Boot can automatically configure beans based on classes and JAR packages in the current classpath. For example, a Spring-boot-starter-Web initiator can have web functions without other configuration.
  • No code generation and XML configuration
    • Spring Boot configuration is done without code generation and without XML configuration files, all with the help of conditional annotations, one of the core features of Spring4.x.
  • Application of monitoring
    • Spring Boot provides a series of endpoints to monitor services and applications for health checks.

What are the advantages of Spring Boot?

The advantages of Spring Boot include

  • Reduced development, testing time and effort.
  • Using JavaConfig helps to avoid XML.
  • Avoid massive Maven imports and versioning conflicts.
  • Provide advice on developing methods.
  • Start development quickly by providing default values.
  • No separate Web server is required. This means you no longer need to start Tomcat, Glassfish or anything else.
  • Less configuration is required because there is no web.xml file. Simply add classes annotated with @Con figuration, then add methods annotated with @beans, and Spring will automatically load the object and manage it as before. You can even add @AutoWired to the bean method to make Spring automatically load the required dependencies.
  • Context based configuration Using these properties, you can deliver the environment you are using to your application: -dspring.pro files.active = {enviorgo nment}. After loading the main application properties file, Spring loads subsequent application properties files in (Application {environment}.properties).

What are the core annotations for Spring Boot? Which notes are it mainly composed of?

  • The annotation above the Boot class is @SpringBootApplication, which is also the core annotation of SpringBoot. It is a composite annotation that contains the functionality of the following three annotations
    • @springbootcon figuration, a composite @con figuration annotation, therefore has the function of being a container class.
    • EnableAutoConfiguration, turn autoconfiguration on and off, also turn off an autoconfiguration such as data source autoconfiguration,@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class }).
    • @ComponentScan, configures the package scanning path. By default, the package scanning starts from the startup class

What is the configuration loading order of Spring Boot?

  • The properties file
  • YML or YAML files
  • System environment variable
  • Command line parameters

What are the core configuration files for Spring Boot? What’s the difference?

The core configuration files for Spring Boot are the Application and Bootstrap configuration files.

  • Application configuration file Configuration file used for the SpringBoot project.
  • The Bootstrap configuration file is used to obtain configuration information for connecting to a remote configuration center when using Spring Cloud Config configuration centers.

MyBatis interview questions

What is Mybatis?

  • Mybatis is a semi-ORM (Object relational Mapping) framework, which encapsulates JDBC internally. When developing, you only need to pay attention to THE SQL statement itself, and do not need to spend energy to deal with the complex process of loading drives, creating connections, creating statements and so on. Programmers directly write the original SQL, SQL execution performance can be strictly controlled, high flexibility.
  • MyBatis can configure and map native information using XML or annotations to map POJOs to records in the database, eliminating almost all of the JDBC code and manual setting of parameters and fetching result sets. 3. Configure the statements to be executed through XML files or annotations, and map Java objects to the dynamic parameters of the SQL in the statement to generate the final SQL statement. Finally, the MYBatis framework executes the SQL and maps the results to Java objects and returns them. (The process from executing SQL to returning result).

The advantages of Mybaits

  • Programming based on SQL statement, quite flexible, will not cause any impact on the existing design of the application program or database, SQL written in XML, remove the COUPLING of SQL and program code, easy to unified management; Provides XML tags that support writing dynamic SQL statements and can be reused.
  • More than 50% less code than JDBC, eliminating a lot of JDBC redundant code, and no need to manually switch the connection.
  • Good compatibility with various databases (because MyBatis uses JDBC to connect to the database, so as long as JDBC support database MyBatis support).
  • Integrates well with Spring.
  • Provide mapping labels to support ORM field relational mapping between objects and databases; Provides object-relational mapping labels to support object-relational component maintenance.

Disadvantages of MyBatis framework

  • SQL statement writing workload is large, especially when there are many fields, associated tables, for developers to write SQL statement skills have certain requirements.
  • SQL statements depend on databases, which leads to poor database portability. Therefore, databases cannot be replaced at will.

MyBatis framework for applications

  • MyBatis focuses on SQL itself and is a flexible DAO layer solution.
  • MyBatis will be a good choice for projects with high performance requirements or variable requirements, such as Internet projects.

What are the differences between MyBatis and Hibernate?

  • Unlike Hibernate, Mybatis is not exactly an ORM framework because Mybatis requires programmers to write their own Sql statements.
  • Mybatis directly write the original SQL, SQL execution performance can be strictly controlled, high flexibility, very suitable for the software development of relational data model requirements are not high, because this kind of software needs to change frequently, but a demand change requires rapid output results. However, the premise of flexibility is that Mybatis cannot achieve database independence. If you need to implement software supporting a variety of databases, you need to customize multiple sets of SQL mapping files, and the workload is heavy.
  • Hibernate object/relational mapping ability is strong, database independence is good, for software with high requirements of relational model, if Hibernate development can save a lot of code, improve efficiency.

# {}andThe ${}What is the difference between?

  • # {}It’s precompiled processing,The ${}It’s string substitution.
  • Mybatis in dealing with# {}, will be in the SQL# {}Replace with? Call the set method in PreparedStatement to assign the value.
  • Mybatis in dealing withThe ${}When means theThe ${}Replace it with the value of the variable.
  • use# {}It can effectively prevent SQL injection and improve system security.

What if the attribute name in the entity class is different from the field name in the table?

  • In the first case, SQL statements use aliases to make the output field names match the entity attribute names.
  • The second method uses resultMap to define the mapping between entity attributes and table field names.

How do MyBatis determine Mapper method is unique? Are methods overloaded with different parameters allowed?

  • Method overloading is not supported. If you need a method with different parameters, use a different method name.

How do I get an automatically generated primary key

If the primary key is auto-increment, you can use the following method:

  • With the insert tag attribute,useGeneratedKeysProperty enables the function to obtain primary keys,keyPropertySpecifies the member property in the model to which the primary key is saved,keyColumnSpecifies the column name for which the primary key is incremented. The default value is the first column of the table. This parameter must be set if the primary key is not the first column.
<insert ID =" insertName "useGeneratedKeys=" true "keyProperty=" ID "keyColumn=" ID "> INSERT into names (name) values (#{name}) </insert>Copy the code

How do I pass multiple parameters in Mapper?

  • Method 1: Mapper method parameters are not annotated, using #{0}, #{1} in Xml to represent the sequence of parameters (not recommended).
  • Method 2: add parameter to Mapper method@paramAnnotations, and you can specify the name of the mapping, which is obtained in Xml using #{name}.
  • Method 3: Use a Map to store key-value pairs. The Map is passed to the parameter of the Mapper method, but it is not needed@paramAnnotations, obtained in Xml using #{keyName}.

What is Mybatis dynamic SQL? What dynamic SQL is there?

MyBatis provides dynamic SQL capability, execution according to the logic on the tag to determine the expression, dynamic splicing SQL. MyBatis provides nine dynamic SQL tags.

  • trim
  • where
  • set
  • foreach
  • if
  • choose
  • when
  • otherwise
  • bind

In the Xml mapping file of Mybatis, can there be a method with the same name for different Xml mapping files?

  • As long as the Xml file specified a different namespace, namespace is generally Mapper class fully qualified class name, id is the method name, determine the only method name is through namespace + ID, so as long as the namespace is different, can be.

Does Mybatis support lazy loading? If so, how does it work?

  • In MyBatis config file,lazyLoadingEnabled=true|falseTo enable or disable lazy loading.
  • When the getter method of the entity is called, invoke() of the dynamic proxy interceptor will be called to determine whether the attribute value is null. If it is null, the corresponding SQL will be called for query, and then the set value will be returned to the model.

Mybatis level 1, level 2 cache

  • Level 1 caching is enabled by default using a HashMap based on PerpetualCache, which functions as a SqlSession. When a SELECT query is called from the same SqlSession, if it hits the cache, the query is not performed and the same model object is returned. This cache is cleared, as well as when SqlSession closes.
  • Level 2 caching is not enabled by default. Level 2 caching is similar to Level 1 caching, with a HashMap based on PerpetualCache, but it is scoped at Mapper level and therefore cached across SqlSession. Also, when adding, deleting, or modifying, the cache is cleared.

How many pagination methods does MyBatis have?

Four kinds of way

  • Once the memory is queried, the Java code manually clippings the collection for paging.
  • Manually add limit to SQL for paging.
  • Add limits to SQL dynamically using a page blocker.
  • Using RowBounds, specify the starting position and the number of queries. By default, RowBounds is actually 0 and the number of queries is integer. MAX_VALUE is infinite.

Spring Cloud interview question

What is Spring Cloud?

  • The Spring Cloud Streaming application launcher is a Spring integration application based on Spring Boot that provides integration with external systems. Spring Cloud Task, a microservices framework with a short life span, is used to quickly build applications that perform limited data processing.

What do I mean by service registration and discovery? How is Spring Cloud implemented?

  • As there are more and more microservices, when the service is on, offline, or the location of the service changes, manual changes are easy to cause problems. Spring Cloud Eureka service automatically solves this problem. All service providers register with Eureka, and service consumers obtain information of providers through Eureka. In addition, Eureka and the service provider have heartbeat detection. If a service is down, it will be synchronized to the service consumer.

What are microservices?

  • Microservices architecture is an architectural pattern, or architectural style, that advocates partitioning a single application into a set of small services, each running in its own independent process, that coordinate with each other to provide ultimate value to users. Services communicate with each other through lightweight communication mechanisms (usually RESTful apis based on HTTP). Each service is built around a specific business and can be independently built in a production environment, a production environment, and so on. In addition, should avoid to unified, centralized service management mechanism, to the body of a service, should be based on the business context, select the appropriate language, tools, and to construct, there can be a very lightweight centralized management to coordinate these services, you can use different language to write the service, also can use different data storage.

What is a service circuit breaker? What is service degradation?

  • Service circuit breaker is a micro – service link protection mechanism against avalanche effect. When a microservice is unavailable or the response time is too long, the service will be degraded, and the invocation of the microservice on this node will be interrupted, and an “error” response message will be quickly returned. Restore the call link after detecting that the microservice invocation response of this node is normal. In the SpringCloud framework, circuit breakers are implemented through Hystrix. Hystrix monitors the status of calls between microservices. When a certain threshold of failed calls is reached, the default is 20 calls within 5 seconds.
  • Service degradation is generally considered from the overall load. When a service is blown down and the server is no longer called, the client can prepare a local fallback callback to return a default value. This way, although the level drops, but at least usable, rather than just dead.

Eureka and ZooKeeper both provide service registration and discovery functions. What is the difference between the two?

  • Zookeeper ensures CP (C: consistency, P: partition fault tolerance) and Eureka ensures AP (A: high availability)
    • When we query the registry for a list of services, we can tolerate the registry returning information from a few minutes ago, but not directly down and unavailable. In other words, the service registration function has high requirements for high availability, but zK will have such a situation that when the master node loses contact with other nodes due to network failure, the remaining nodes will choose the leader again. The problem is that it takes a long time to select a leader (30 to 120s), and the ZK cluster is unavailable during the selection period. As a result, the registration service will be broken during the selection period. In a cloud deployment environment, it is highly likely that the ZK cluster will lose its master node due to network problems. Although the service can be restored, the long selection time resulting in long-term registration unavailability cannot be tolerated.
    • Eureka ensures availability. All Eureka nodes are equal. The failure of several nodes will not affect the work of normal nodes, and the remaining nodes can still provide registration and query services. When Eureka’s client fails to register or discover a Eureka, it will automatically switch to other nodes. As long as one Eureka is still available, the registration service can be guaranteed, but the information found may not be the latest.
    • In addition, Eureka also has a self-protection mechanism. If more than 85% of the nodes have no normal heartbeat within 15 minutes, Eureka considers that there is a network failure between the client and the registry
      • Eureka does not remove services from the register that should expire because they have not received a heartbeat for a long time.
      • Eureka can still accept registration and query requests for new services, but will not be synchronized to other nodes (that is, the current node is still available).
      • When the network is stable, the new registration information of the current instance is synchronized to other nodes. Therefore, Eureka can deal with the situation that some nodes lose contact due to network failure, rather than the whole microservice breakdown like Zookeeper.

Advantages and disadvantages of microservices? Tell me about the potholes in the development project?

  • advantages

    • Each service is directly cohesive enough that the code is easy to understand
    • High development efficiency, a service only does one thing, suitable for small team development
    • Loosely coupled, functionally meaningful services
    • Can be developed in different languages, interface oriented programming
    • Easy third party integration
    • Microservices are just code for business logic, not HTML,CSS, or other interfaces
    • Can be flexible collocation, connect public library/connect independent library
  • disadvantages

    • Accountability of distributed systems
    • Multi-service operation and maintenance becomes more difficult
    • System deployment dependencies, inter-service communication costs, data consistency, system integration testing, performance monitoring

Eureka and Zookeeper

  • Eureka takes THE AP of CAP and pays attention to availability, while Zookeeper takes the CP of CAP and pays attention to consistency.
  • Zookeeper’s registration service crashed during the election, and although the service will eventually be restored, it will not be available during the election.
  • One result of Eureka’s self-protection mechanism is that it will no longer remove services from the register that have expired due to a long period of not receiving a heartbeat. Registration and query requests for new services can still be accepted, but will not be synchronized to other nodes. No service breakdown.
  • Zookeeper functions as Leader and Follower. All Eureka nodes are equal.
  • Zookeeper adopts the principle of more than half survival, while Eureka adopts the self-protection mechanism to solve the partition problem.
  • Eureka is essentially a project. Zookeeper is just a process.

What is the Eureka self-protection mechanism?

  • When the Eureka Server node loses too many instances in a short period of time (for example, when the network fails or the client is frequently started and closed), the node enters the self-protection mode to protect the registration information and not delete the registration data. When the fault is recovered, the Eureka Server node automatically exits the self-protection mode.

What is Ribbon?

  • The Ribbon is a load balancing client that controls HTT and TCP behavior. Feign integrates the ribbon by default.

What is a feigin? What are its advantages?

  • Feign uses interface-based annotations
  • Feign integrates the Ribbon with load balancing capabilities
  • Integrated with Hystrix, with fuse breaker capability

What’s the difference between the Ribbon and Feign?

  • The Ribbon calls other services, but in different ways.
  • The Ribbon is @ribbonClient feign and the Ribbon is @enableFeignClients
  • The Ribbon is declared on the @RibbonClient annotation, while Feign uses the @FeignClient declaration in the interface that defines the abstract method.
  • The Ribbon builds HTTP requests, simulates HTTP requests, and sends them to other services using the RestTemplate. Feign needs to define the method to be called as an abstract method.

Springcloud circuit breaker function?

  • When a service calls another service due to network or its own problems, the caller will wait for the response of the called service. When more services request these resources, more requests wait, resulting in a chain effect (avalanche effect).
  • Circuit breaker status
    • Fully open state: the service will not be requested next time the circuit breaker is fully open after it has been unavailable for a certain number of times over a period of time and has been monitored repeatedly with no signs of recovery.
    • Half-open: The circuit breaker will send partial requests to the service if there are signs of recovery within a short period of time. The circuit breaker will close when it is called normally.
    • Off: The service can be invoked when it is in the normal state.