This article has participated in the good article call order activity, click to see: back end, big front end double track submission, 20,000 yuan prize pool for you to challenge!

The interview

  • Generally, it is asked from shallow to deep. The idea is:
    • Inspect the foundation first whether pass, because the foundation knowledge decided a technical personnel development upper limit
    • Through the depth of whether there is enthusiasm and depth and breadth of technology
    • Questions and challenges may also be raised to see if the candidate can communicate with people who have different opinions

Examine content and method

Basic knowledge of

  • Technical depth and breadth of consideration
  • Basic knowledge: investigate the foundation of the time generally won’t go into depth to ask, the main purpose is to investigate knowledge
    • Theoretical basis of computer:
      • Computer network
      • The data structure
      • Principle of computer composition
      • Computer operating system
    • JDK:
      • The source code
      • A collection of
      • BIO or NIO
      • The annotation etc.
    • JVM:
      • The memory model
      • Class loading Principles
    • Database:
      • The index
      • The transaction
      • Deadlock etc.
    • Concurrent:
      • Pros and cons of concurrency
      • Memory visibility – volatile
      • The lock
      • synchronous
      • Thread pool framework
    • Network:
      • TCP
      • HTTP
    • Common Design patterns

In-depth investigation

  • In-depth study:
    • It’s not going to cover all the bases, it’s going to go deep at some point
    • This point can be for the candidate to choose a point, or the interviewer may choose based on the content of the resume
    • The main purpose is to see how well the candidate has mastered a particular technical point
    • Technology is interlinked. If a person can reach a very deep level in a certain technical point, there will be no big problems in other points. If a person prevaricates in the technical point that he or she claims to know very well, and has only a little knowledge about it, it can be judged that he or she is either limited in technology or unwilling to go deep into the problem
    • Examine the engineer’s engineering skills. For example: What projects have you worked on? What is the most difficult problem you have encountered? How was it solved? Tell me about your most rewarding task
  • Technical points of in-depth investigation:
    • Java framework:
      • Spring source AOP and IOC
    • JDK:
      • How does ConcurrentHashMap increase concurrency
      • NIO principles, including zero copy, out of heap memory, and pros and cons
    • The virtual machine:
      • The formation and solution of package conflict and class conflict can be extended to the modular design of JDK 9
      • The existence value of TCCL
    • Server:
      • Tomcat source
      • Netty source
    • Data structure:
      • An array of
      • The list
      • The tree
      • figure
      • The sorting
      • algorithm
    • Distributed:
      • Caching application
      • Consistent hash
      • Principle and design of RPC – communication protocol, serialization mode, timeout mechanism, etc
      • Load balancing
      • Distributed cache architecture design
      • Distributed message
      • Message queue design and use
      • Middleware deployment in a distributed environment
      • Distributed transaction
      • paxos
    • Middleware:
      • MQ
      • ES
    • Database:
      • Database performance optimization – slow SQL, index optimization, large transactions, kernel parameter tuning
      • Underlying principles of the MySQL database
      • Database problems encountered in work and solutions
      • Redis
    • Concurrent:
      • Non-blocking locks CAS
      • The effect of concurrency on compiler optimization
      • Thread pool tuning
      • Concurrency problems encountered at work and solutions
    • Technology Trends:
      • Docker
      • Micro service

Business related

  • What are the advantages and disadvantages of the technology stack used in the project?
  • If you start from scratch, can you do it again?
  • Who is using the current system? How many users? At what point in time do users converge?
  • What data is missing from the system? Who is using this data? Who is the system dependent on?
  • Draw the relevant flow chart from the technical, product and business perspective

The work handover

  • Handoffs between products, businesses, operations, and technology:
    • Know the boundaries of your responsibilities
    • Figure out what you need to do
    • What the rest of us should do
    • Communicate neither servile nor pushy

Interview preparation

  • The best ways to prepare for an interview:
    • Must be a lot of accumulation at ordinary times
    • Don’t run away from problems
    • Think about it and solve it
    • In the process of solving one problem after another, we can accumulate the ability to solve the problem and form our own knowledge system
  • How to prepare ahead of time to show their usual accumulation:
    • Think about your answers and expand on what you are interviewing for. If you know most of it, you have to go deeper. This process is mainly about sorting out your own body of knowledge
    • Review the “hard points” and “bright points” from your resume and past projects, because these are the key points that distinguish the candidates. The interview will always ask, “What was the most technical difficulty you experienced on a project?” Organize your thoughts so that you don’t lose track of details during the interview because of the time lapse
    • The communication process should be reasoned, neither servile nor pushy. Adhere to their own objective and principle on technical issues, according to the facts agreed by the logical judgment of the point of view

The interview content,

Java based

  • Private modified methods can be accessed through reflection, so what does private mean?
  • Check your mastery of Java design
    • Java’s private modifier is not designed for absolute security, but more as a constraint on the user’s regular use of Java
    • When you make regular calls to objects from outside, you get a clear idea of the class structure
  • How to use reflection to get fields of a class in Java?
  • Common class loading
  • Java class initialization order?
  • Java class initialization order:
    • Base class static code blocks, base class static member variables (in order of precedence, in the order they appear in the code, and only on the first load)
    • Derived class static code blocks, derived class static member variables (in order of precedence, in the order they appear in the code, and only executed on the first load)
    • Base class ordinary code blocks, base class ordinary member variables (in order of precedence, in order of occurrence in the code)
    • Base class constructor
    • Derived class ordinary code blocks, derived class ordinary member variables (in order of precedence, in order of occurrence in the code)
    • Derived class constructor
  • Local variables need to be explicitly assigned before they are used, otherwise they won’t pass compilation. Why do you need to do this?
  • Member variables:
    • It can be left uninitialized and default values can be given during the preparation phase of the class loading process
    • The order of assignment and value access is uncertain
    • Member variables can be assigned before or after a method call. This happens at run time, the compiler can’t determine, so it’s up to the JVM to assign
  • Local variables:
    • You need to explicitly assign an initial value before using it
    • The assignment and access order of local variables are determined
    • This is designed as a constraint to minimize user error:
      • Given that local variables can be assigned with default values, you can always inadvertently forget to assign values, which can lead to unexpected situations
  • What’s the difference between ArrayList and LinkList? Which is faster, insert or find?
  • Random insertion of ArrayList?
  • Is LinkList a one-way linked list or a two-way linked list?
  • How does a one-way linked list implement a stack?
  • How is the underlying HashMap PUT implemented?
  • What is the difference between HashTable, ConcurrentHashMap? Why is ConcurrentHashMap concurrency higher?
  • When will get and set in ConcurrentHashMap be locked? What happens if you leave it unlocked? When is the CAS operation?
  • How does HashMap work, and what changes have been made in Java 8?
  • In terms of structural implementation:
    • The HashMap implementation is an array + a linked list + a red-black tree (the red-black tree part was added after JDK 1.8)
    • HashMap allows a maximum of one record to have a null key and multiple records to have null values
    • HashMap is non-thread-safe
  • What is the difference between String and StringBuilder?
  • Variable and immutable:
    • String is immutable, and every time a “+” is executed, a new object is generated, so frequent String changes are not used to save memory
  • Multithreaded safety or not:
    • StringBuilder does not synchronously lock methods, so it is non-thread-safe. Both stringBuffers and strings are thread safe
  • What’s the difference between a Vector and an Array?
  • By default, ArrayList expands by 50%+1 when memory runs out, and Vector expands by twice
  • Vectors are thread-safe, but in most cases we don’t use vectors because thread-safe is more overhead
  • What’s the difference between HashMap and HashTable?
  • HashTable inherits from Dictionary and HashMap inherits from AbstrctMap
  • A HashTable does not allow empty key-value pairs, while a HashMap does, but only with one empty object at most
  • HashTable is synchronized while HashMap is not synchronized, which is more efficient than HashTable
  • ConcurrentHashMap and HashTable compare, two threads concurrently access the same chain in the Map, one thread in the tail to delete, one thread in the front to traverse the search. Why can the previous thread correctly find the node that was later deleted by another thread?
  • ConcurrentHashMap combines the advantages of both HashTable and HashMap:
    • HashTable is synchronized and thread-safe, while HashMap does not allow for synchronization, so HashMap is more efficient in single-threaded situations
    • HashTable in the case of multiple threads, synchronization ensures correct program execution
    • But the HashTable is blocked, locking the entire structure every time the synchronization is executed
  • ConcurrentHashMap just solves the efficiency and blocking issues:
    • ConcurrentHashMap allows multiple modification operations to be performed concurrently. The key to the technique is the use of lock separation. That is, an Array holds multiple objects, uses the locks of those objects as separation locks, and uses either one randomly when getting or putting
    • ConcurrentHashMap uses multiple locks to control changes to different parts of the Hash table
    • Starting with JDK 1.6, in the HashEntry structure, each insert uses the newly added node as the head node of the chain, the same as the HashMap implementation.
      • Each time a node is deleted, all nodes before the deletion are copied to form a new chain, and the next of the previous node of the current node is pointed to the next node of the current node. There will be two chains after deletion
      • This ensures that even in the same chain, where one thread is deleting and another thread is traversing, it works fine. Because the traversing thread can continue to use the original chain
    • In Java 8, volatile HashEntry is used to hold data, with the table element as the lock. From the Table array + unidirectional linked list, added the red-black tree
      • A red-black tree is a special binary search tree. The properties of a red-black tree are:
        • Nodes are red or black
        • The root node is black
        • The leaves are black
        • If one node is red, the other node is black
        • There are the same number of black nodes on all paths from a node to its descendants
  • What’s the difference between ArrayList and LinkedList?
  • The underlying data structure of ArrayList is an array and supports random access. The underlying data structure of LinkedList is a LinkedList and does not support random access
  • Access an element using the following table:
    • The time complexity of ArrayList is O(1)
    • The time complexity of LinkedList is O(n). LinkedList is a two-way LinkedList
  • The put() element in a HashMap has a conflict. Why use the LinkedList zipper method instead of ArrayList? How can new elements be added to the list when the key values are different? Why?
  • What’s the difference between Comparator and Comparable in Java?
  • The Comparable interface is used to define the natural order of objects and is the sort interface
  • A Comparator is used to define a user-defined order. It is a comparison interface
    • If the order of a class needs to be controlled and the class itself does not support sorting, that is, it does not implement the Comparable interface, a “comparator of the class” can be built to do the sorting
    • Comparable is always only one, but can have multiple Comparators to define the order of objects
  • What is an abstract class? What’s the difference with an interface? Why use abstract classes?
  • Abstract classes are classes that are not allowed to be instantiated. A class can only use the inheritance relationship once, but a class can implement multiple interfaces
  • Abstract classes and interfaces reflect different design concepts:
    • The abstract class represents “is-a”
    • The interface is “like-a”
  • Classes that implement abstract classes and interfaces must implement all the methods in them. Abstract classes can have non-abstract methods and interfaces cannot have implementation methods, but Java 8 allows interfaces to have static default methods
    • A variable defined in an interface is public static final by default and must be given an initial value, so the implementation class cannot redefine or change the value
    • A variable defined in an abstract class defaults to friendly, and the value of this variable can be redefined or reassigned in the subclass
    • When a subclass implements an abstract method from its parent class. Visibility can be greater than or equal to that in the superclass
    • Interface implementation class The visibility of interface methods in a class must be the same as that in an interface, that is, public
  • Abstract classes are used for reuse, less coding, and less coupling
  • Overloading and rewriting in Java?
  • Overloading and overwriting both implement different functions using the same name, but overloading is a compile-time activity and overwriting is a run-time activity
  • Methods can be overridden in the same class, but they can only be overridden in a subclass. Overridden methods must have inheritance
  • Overloading:
    • When overloaded, the method name should be the same, but the parameter type and number of parameters should be different, and the return value type can be the same or different
    • You cannot distinguish overloaded functions by return types
  • Rewrite:
    • Methods inherited from the base class can be overridden as needed in a subclass
    • The overridden and overridden methods must have the same method name, argument list, and return type
    • Overridden methods cannot have stricter access than the overridden methods
  • What is the difference between a Collection and a Collection?
  • Collection< E > is the basic interface in the Java Collections framework
  • Collections is a utility class provided by the Java Collections framework that contains a large number of static methods for manipulating and returning Collections
  • The realization principle of polymorphism in Java?
  • Polymorphism is when a parent class refers to an object that points to a child class, and when a method is called, the child class’s implementation is called instead of the parent class’s implementation
  • The key to realizing polymorphism is dynamic binding
  • What methods are defined in Object?
  • clone()
  • equals()
  • hashCode()
  • toString()
  • notify()
  • notifyAll()
  • wait()
  • finalize()
  • getClass()
  • Generics and type erasure in Java?
  • A generic type is a parameterized type. When a collection is created, it specifies the type of the elements in the collection. The collection can only pass in parameters of that type
  • Type erasing: Bytecode generated by the Java compiler does not include generic information, so it is erased at compile time
    • Generics are replaced with the top – level superclass
    • remove
  • New features introduced in JDK 1.8?
  • Lambda expressions
  • The Stream API allows anonymous functions to be passed like objects, taking full advantage of modern multi-core cpus and allowing very clean code to be written
  • Date and Time API, there is a stable and simple Date and Time library available to use
  • Interfaces can have static, default methods
  • Repeating annotations allows you to use the same annotation multiple times on the same type
  • Public,private,protected, and default keywords in Java?
  • Protected can be subclassed in and out of the package
  • Default can only be accessed within the same package
  • Private can only be accessed within the same class
  • Common data structures?
  • A collection of
  • Linear structure
    • An array of
    • The queue
    • The list
    • The stack
  • A tree structure
  • The graph structure
  • What tree is TreeMap implemented in Java?

TreeMap in Java is implemented using red-black trees

  • What is an anonymous inner class? How do I access variables defined outside an anonymous inner class?
  • Anonymous inner classes are inner classes that have no name. Anonymous inner classes can only be used once, usually to simplify code writing
  • An anonymous inner class can only access final variables of the outer class
  • In Java 8, a local variable is automatically final if it is accessed by an anonymous inner class
  • How can I efficiently create a thread-safe singleton pattern?
  • Through the enumeration
  • Through static inner classes
  • You can also create a singleton pattern by double-checking, but this singleton pattern is thread-unsafe
  • What’s the difference between the poll() and remove() methods?
  • Both poll() and remove take an element from the queue
  • Poll () returns null on failure to get an element
  • Remove () throws an exception when obtaining an element fails
  • Write a piece of code that removes an element while iterating through an ArrayList?
  • Using iterators
Iterator it = list.iterator();
while (it.hasNext()) {
  if (...) {
  	it.remove();
  }
}
Copy the code
  • The principle of annotations
  • Which open source protocols?
  • GPL: GNU General Public License
  • LGPL: GNU Lesser General Public License
  • BSD: Berkeley Software Distribution, Berkeley Software Distribution License Agreement
  • MIT: Massachusetts Institute of Technology
  • Apache: Indicates the Apache license
  • MPL: Mozilla Public Licence

thread

  • Thread synchronization vs. blocking? Is synchronization always blocked? Is blocking always synchronized?
  • It does not matter whether the thread is synchronized or not
  • Synchronization is a process, and blocking is a state of the thread
  • Contention occurs when multiple threads operate on a shared variable
  • Synchronization is needed to prevent more than two threads from entering the critical section at the same time. During this process, the thread entering the last critical section blocks, waiting for the first thread to exit the critical section
  • What’s the difference between synchronous and asynchronous?
  • The biggest difference between synchronous and asynchronous is: one needs to wait, one does not need to wait
  • Synchronization is used to avoid deadlocks and dirty data read when sharing a resource
    • If everyone has permission to modify a file at the same time, it could cause one person to read what the other person has deleted, and an error would occur
    • The synchronization is changed in order
  • The thread pool?
  • The function of the thread pool is to effectively limit the number of threads to execute according to the system’s own situation, so that the performance of the best
  • Thread pools do the following:
    • Controls the number of threads of execution
    • The number of threads queued exceeded
    • Wait for a task to complete
    • Then the task is fetched from the top of the queue and executed
  • How do I call the wait() method? Use an if block or loop? Why is that?
  • The wait() method should be called inside the loop:
    • By the time the thread gets to the CPU and starts executing, other conditions may not have been met
    • Therefore, before processing, whether the cycle detection condition is better satisfied
  • The wait(),notify(), and notifyAll() methods are the wait and wake methods provided by the Java.lang.object class for threads to implement synchronous control for inter-thread communication
  • How many ways to implement threads?
  • How to implement threads:
    • Override the run function by extending the Thread class
    • Implement the Runnable interface and override the run function
    • Implement the Callable interface and override the call function
  • What is false sharing in multi-threaded environment?
  • Pseudo-sharing is a common performance problem in multithreaded systems where each processor has its own local cache
    • The cache is stored by cache line in the cache system
    • A cache line is an integer power of 2 consecutive bytes, typically 32 to 256 bytes
    • The most common cache line is 64 bytes
    • Pseudo-sharing occurs when multiple threads modify independent variables that affect each other’s performance if they share the same cache line
  • The state of the thread?
  • Which packages have been used concurrently?
  • java.util.concurrent
  • java.util.concurrent.atomic
  • java.util.concurrent.lock
  • ReadWriteLock Are reads and writes mutually exclusive?
  • ReadWriteRock Usage scenarios of read and write locks:
    • Read –
    • Read write
    • Write –
  • All are mutually exclusive except for the read-read, which is shared
  • How to implement mutex and synchronization locks
  • Test the mastery of AQS and CAS
  • Helper classes in Java Concurrent Programming?
  • Semaphore
  • CountDownLatch
  • CyclicBarrier
  • Exchanger
  • What’s the difference between CountDownLatch and CyclicBarrier?
  • Are ReadWriteLock mutually exclusive?
  • ReadWriteLock Usage scenarios of read and write locks:
    • Read, read
    • Reading, writing
    • Write, write
  • They are mutually exclusive except that the reads are shared with each other

After that, we’ll talk about how to implement mutex and synchronous lock, how much do you know about AQS,CAS, technology learning

  • Are Semaphore execution threads mutually exclusive?
  • The threads on which Semaphore gets execution are mutually exclusive
  • Semaphore, CountDownLatch, CyclicBarrier, and Non-recoverable are four secondary classes for Java concurrent programming. Learn the difference between CountDownLatch and CyclicBarrier
  • Semaphore may have multiple locks that allow multiple threads to execute simultaneously, which can cause thread-safety problems if these threads concurrently access the same object
  • Semaphore:
    • You can have multiple locks, allowing multiple threads to have execution rights simultaneously
    • These threads with execution rights can cause thread-safety problems if they access the same object concurrently
  • How do threads execute sequentially?
  • What happens when an exception is encountered during thread execution and how to handle it?
  • Write a singleton pattern?
  • The singleton pattern is one of the most commonly encountered design patterns that examines the depth of understanding of frequently encountered problems
  • There are five implementations of singletons:
    • The hungry
    • lazy
    • Static inner class
    • Double check the lock
      • The enumeration
  • If you write a simple slacker, you might ask: How do you ensure thread safety when you have multiple threads?
    • Using double check locks ensures thread safety.
  • Why double check? What else could be wrong with a double lock?
    • The object is defined with the volatile keyword
  • Extended discussion of atomicity and visibility,Java memory model, class loading process
  • Enumeration mode, static inner class, double lock can be implemented singleton mode. Double lock singleton mode:
public Class Singleton {
	private Singleton(a) {}private volatile static Singleton instance;

public static Singleton getInstance(a) {
	if (null == instance) {
		synchronized (Singleton.class) {
			if (null == instance) {
				instance = newSingleton(); }}}returninstance; }}Copy the code
  • Double lock write a singleton pattern. Why use volatile objects?
  • Object object = new Object(); Is object null here? Why is that?
  • Object object = new Object(); What is the order of initialization? What is being done in the various regions of the JVM?
  • Under what circumstances can a deadlock occur? Write a deadlock?
  • Four conditions for a deadlock:
  • Example: define two arraylists, both with locks A, b. thread 1,2. Thread 1 acquires lock A and requests lock B. Thread 2 acquires lock B and requests lock a. Neither acquires the lock while waiting for the other to release it
public class DeadLock {
	public static void main(String[] args) {
		final List<Integer> list1 = Arrays.asList(1.2.3);
		final List<Integer> list2 = Arrays.asList(4.5 ,6);
		new Thread(new Runnable() {
			@Override
			public void run(a) {
				synchronized (list1) {
					for (Integer i : list1) {
						System.out.println(i);
					} 
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					synchronized (list2) {
						for (Integer i : list2) {
							System.out.println(i);
						}
					}
				}
			}
		}).start();
 
 		new Thread(new Runnable() {
 			@Override
 			public void run(a) {
 				synchronized (list2) {
 					for (Integer i : list2) {
 						System.out.println(i);
 					}
 					try {
 						Thread.sleep(1000);
 					} catch (InterruptedException e) {
 						e.printStackTrace();
 					}
 					synchronized (list1) {
 						for(Integer i : list1) { System.out.println(i); } } } } }).start(); }}Copy the code
  • String a = “ab”; String b = “a” + “b”; a == b; Is it the same? Why?
  • equal
  • New An object is assigned to a variable
  • This line of expression creates several objects
  • int a = 1; Is it atomic?
  • is
  • Can a for loop be used to directly remove specific elements of an ArrayList? What could possibly go wrong? How to solve it?
  • You cannot use a for loop to directly remove a specific element from an ArrayList:
    • Different for loops cause different exceptions
    • Generic for will throw ConcurrentModificationException
    • If the normal for wants to remove duplicate and contiguous elements from a collection, it can only remove the first one
  • The reason:
    • JDK source ArrayList
    • Remove in ArrayList has two methods with the same name, but the input parameters are different:
      • Implementation of Object with input:
        • Normally, the execution path of the program goes to the else path and ends up calling the faseRemove() method, which executes the system.arrayCopy () method, causing the removal of the element to involve the movement of the array element
        • An ordinary for loop removes the element from the array when iterating over the first string that meets the deletion criteria, and moves the second element to the current position. As a result, the last string is not successfully iterated during the next iteration, so it cannot be deleted. This can be avoided by deleting in reverse order
  • Solution: Use an Iterator
List<String> list = new ArrayList(Arrays.asList("a"."b"."b"."c"."d"));
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
	String element = iterator.next();
	if ("b".equals(element)) { iterator.remove(); }}Copy the code
  • How does the thread pool handle new tasks that are submitted to the thread pool?
  • Step 1: The thread pool determines whether all threads in the core thread pool are executing tasks. If not, a new worker thread is created to perform the task. If all threads in the core thread pool are executing tasks, the second step is performed
  • Step 2: The thread pool determines if the work queue is full. If the work queue is not full, the new submitted task is stored in the work queue and waits. If the work queue is full, go to step 3
  • Step 3: Thread pool determines whether all threads in the thread pool are working. If not, a new worker thread is created to perform the task. If it is full, the saturation strategy is given to handle the task
  • AQS and CAS principles?
  • Abstract queue synchronizer AQS: AbstractQueuedSychronizer
    • If java.util.concurrent is based on CAS, then AQS is the core of the entire Java concurrent package
    • ReentrantLock, CountDownLatch, Semaphore all use AQS
    • AQS actually connect all entries in a two-way queue:
      • ReentrantLock: All waiting threads are placed in an Entry and connected to a bidirectional queue. The previous thread uses ReentrantLock, so the first Entry in the bidirectional queue actually starts running
    • AQS defines all operations on bidirectional queues and only opens up tryLock and tryRelease methods to developers. Developers can override the tryLock and tryRelease methods according to their own implementations to implement their own concurrency functionality
  • Compare and replace CAS: Compare and Swap
    • Suppose we have three operands:
      • The memory of the V
      • The old expected value A
      • The value B to modify
      • Change the memory value to B and return true if and only if the expected value A is the same as the memory value V. Otherwise, do nothing and return false.
      • The entire comparis-and-replace operation is an atomic operation
    • The CAS must use volatile variables to ensure that each variable is the latest response value in main memory. Otherwise, the old expected value A is always A fixed value for A thread A. As long as A CAS operation fails, the CAS operation will never succeed
    • CAS solves the problem of atomic operations efficiently, but three problems remain:
      • Loop time is long and expensive
      • Atomic operations that guarantee only one shared variable
      • ABA problem
  • What is the underlying implementation of AtomicLong?
  • ReentrantLock is a ReentrantLock. What is a ReentrantLock?
  • How is atomicity implemented at the bottom of CAS?
  • Synchronized underlying implementation principle?
  • Principle of synchronized (this) :
    • Two instructions: monitorenter and monitorexit
    • Synchronized methods: The decompiled results of the synchronized methods show that – methods are not synchronized with the monitorenter and monitorexit commands, but with the ACC_SYNCHRONIZED identifier in the constant pool instead of the normal methods
  • The JVM synchronizes methods according to the ACC_SYNCHRONIZED identifier:
    • When a method is called, the calling directive checks whether the ACC_SYNCHRONIZED access flag for the method is set
    • If this is set, the executing thread will first acquire the monitor, then execute the method body after the successful acquisition, and then release the monitor after the method completes execution
    • During method execution, no other thread can get the same Monitor object again
  • What is the difference between lock and synchronized?
  • Java object headers, biased locks, lightweight locks, heavyweight locks, and their conversion to each other?
  • What is the difference between a modified class lock and a modified method lock?
  • Volatile action, order reorder related?
  • An understanding of Java’s memory model is a prerequisite for understanding the role of the volatile keyword
  • The volatile keyword serves two main purposes:
    • Multithreading focuses on two features: visibility and atomicity. Using the volatile keyword to modify variables ensures visibility across multiple threads. That is, every time a volatile variable is read, it must be the latest data
    • Execution of the underlying code: Java code -> bytecode -> execute the corresponding C/C++ code according to the bytecode -> C/C++ code is compiled into assembly language -> interact with the hardware circuit. In reality, JVMS may reorder instructions for better performance, and unexpected problems can occur with multiple threads. Using volatile prevents semantic reordering, but it also reduces the efficiency of your code to some extent
  • From a practical point of view, an important function of volatile is to ensure atomicity in combination with CAS. Such as AtomicInteger

Java thread pool

  • How thread pools work and the core parameters
  • Thread pool construction parameters?
  • How to interrupt a thread, specific implementation? Can a running thread be interrupted?
  • How to set the number of threads in a thread? Is the number of cpus computational or twice the number of cpus?
  • CPU 100% How to locate?

The data structure

  • What kind of problems do B trees and B+ trees solve? How did it evolve? What’s the difference between the two?
  • B tree and B+ tree, both examine the implementation principle of MySQL index, also examine the basis of data structure
  • Let’s start with binary trees:
    • Because of degradation, a balanced binary tree is proposed
    • How to reduce the traversal height by putting more nodes in each layer to derive the M-tree
    • M-fork search tree will also degenerate, which leads to m-fork equilibrium tree, namely B-tree
    • In this case, each node has both a key and a value. How can each node have as many keys as possible to reduce the number of times to traverse the height and access the disk
    • You can put only the key value in each node, put the value value in the leaf node, and increase the pointer to the adjacent node in the leaf node value, which is the optimized B+ tree
  • Then talk about the failure of the database index:
    • Why is indexing low dispersion fields, such as gender, undesirable? Querying data is slower
    • What happens if you combine a high dispersion field with a low dispersion field like gender? What’s the concern?

Spring

  • Which frameworks have seen the source code?
  • What is the Spring framework? What are the modules of the Spring framework?
  • What design patterns are used in Spring?
  • Benefits of the Spring framework?
  • What is IOC Inversion of Control?
  • What is dependency injection and how it works?
  • What’s the difference between @Autowired and @Resource in Spring?
  • What is the difference between BeanFactory and ApplicationContext?
  • Life cycle of Spring Beans?
  • What are the scopes of Spring Beans and what are the differences between the various scopes?
  • Are singletons in the Spring Framework Thread-safe?
  • What are the differences and application scenarios between BeanFactory and FactoryBean?
  • How is Spring’s proxy implemented?
  • JDK proxy mechanism?
  • AOP and IOC principles?
  • AOP and IOC are the essence of Spring
  • AOP:
    • AOP can be seen as a complement to OOP, extending code horizontally
    • Through the proxy pattern. Proxy modes include static proxy and dynamic proxy.
    • Spring uses dynamic proxies to weave enhancements into the source code as the program runs
  • IOC:Inversion of control
    • By giving control of objects to the Spring framework, users can use them without having to create them
  • AOP and IOC focus on understanding design ideas
  • How does Spring solve the problem of circular dependencies
  • Spring’s circular dependency problem:
    • What is a cyclic dependency?
    • How are cyclic dependencies detected?
    • There are several ways to use Spring cyclic dependencies. Why don’t you have problems using setter-based cyclic dependencies?
  • The lifecycle of the Bean?
  • How does dispatchServlet distribute tasks?

  • 1. When the user sends a request -> DispatcherServlet: The front-end controller does not process the request after receiving it, but delegates it to other parsers for processing. It acts as a unified access point for global process control
  • 2. DispatcherServlet -> HandlerMapping: HandlerMapping will map the request to a HandlerExecutionChain object. The HandlerExecutionChain contains a Hander handler and multiple HandlerInterceptor interceptors
  • 3. DispatcherServlet -> HandlerAdapter: The HandlerAdapter wraps processors as adapters to support multiple types of processors
  • 4. HandlerAdapter -> Handler function call: The HandlerAdapter will call the actual handler function based on the result of the adaptation, complete the function processing, and return a ModelAndView object. The ModelAndView object contains the model data. Logical view name
  • 5. ModelAndView logical View name -> ViewResolver: The ViewResolver resolves the logical View name into the concrete View
  • 6. View -> Render: The View is rendered based on the Model data passed in. The Model is a Map data structure
  • 7. Return control to the DispatcherServlet, which returns a response to the user

The database

  • What are the paradigms in the database?
  • First Normal form: All field values of a table in a database are indivisible atomic data items
  • Second normal form: Every column in a database table is associated with a primary key, not just a part of the primary key
  • Third normal form: Each column of data in a database table is directly related to the primary key, not indirectly
  • The paradigm is to reduce data redundancy
  • What happens when MySQL indexes low dispersion fields?
  • Repetitive fields are not suitable for adding indexes
  • MySQL indexes low dispersion fields, such as gender, and queries based on gender are slower
  • A table may involve two data structures:
    • Data table: Stores the data in the table
    • The index
  • Index:
    • Arrange one or more fields (composite index) in a regular order, and append the physical address of the data in the row where the field is located (in the table)
      • For example, if one of the fields is age, if you want to select all rows of a certain age group, then you might normally need to do a full table scan
      • However, if you create an index based on this age group, the index will be arranged according to the specific data structure based on the age group, so that it can be quickly located in the index without the need for a full table scan
  • Why is gender not appropriate for indexing?
    • Since accessing an index requires additional IO overhead, all you get from the index is the address, you still need to perform an IO on the table to actually access the data
    • If you want to fetch a few of the million rows in the table, you can use the index to quickly locate and the IO overhead of accessing the index is negligible
    • If you take 500,000 rows from a million rows in the index and access the table 500,000 times, the total cost is not less than a full scan of the table
  • If you set the gender field to a focused index, you can certainly speed up queries for that field by about half
  • Focusing index:
    • This refers to the table itself by which field the data is sorted
    • Focusing the index does not incur additional IO overhead
    • There can be only one focused index

    – So the focus index is used on the most frequently searched fields

  • Gender can be federated with the rest of the fields as required by the business scenario. For example, with a timestamp, place the timestamp field before the gender
  • MySQL’s leftmost matching principle?
  • What is the isolation level of MySQL?
  • B+ B tree?
  • Common optimizations and considerations for MySQL?
  • Database slow query optimization idea
  • What are the logs in MySQL? What do they do?
  • undo log:
  • redo log:
  • binlog:
  • Database ACID?
  • What is the isolation level of database transactions?
  • What is the subtable of database?
  • How to achieve the global unique ID of the sub-table?
  • The structure of the indexes in the database? When is it appropriate to create an index?
  • The index structure in the database is a sort of data structure. The index of the database is realized by B tree and deformed B+ tree
    • When it is not appropriate to create indexes:
      • For columns that are rarely used or referenced during the query
      • For columns with very few data values
      • For columns defined as image,text, and BIT data types
      • When the modification performance is much greater than the retrieval performance
  • According to the environment of the system itself, the number of threads is effectively limited to achieve the best operation effect
    • Thread is mainly through the control of the number of execution threads, exceeding the number of threads queuing, waiting for the completion of the execution of a task, and then from the front of the queue to take out the task execution
  • Q: How to optimize MySQL?
  • SQL optimization
  • Table structure optimization
  • The index optimization
  • Cache parameter optimization
  • What are the data types of Redis?

distributed

  • CAP theory?
  • Write a producer-consumer pattern?
  • Producer consumer model:
    • synchronizedA lockLinkedList:
      • Producer: As long as the queue is not satisfied, after production to save
      • Consumer: as long as the queue is not empty, after consumption, go out to fetch
    • The two are coordinated by wait() and notify()
  • How can we improve efficiency
  • Familiar with message queue design and use
  • Why use message queue MQ?
  • Asynchronous processing: compared with the traditional serial, parallel mode, improve the throughput of the system
  • Application decoupling: Systems communicate with each other through messages, not caring about the processing of other systems
  • Traffic peaking: The request volume can be controlled by message queue length, which can alleviate high concurrent requests in a short period of time
  • Log processing: Transmits a large number of logs
  • Message communication: Message queues generally have efficient communication mechanisms built in, so they can be used for pure message communication. Such as implementing point-to-point message queues, chat rooms and so on
  • How to ensure high availability of message queue MQ?
  • Sort all brokers and Partition to be allocated
  • Assigns the ith Partion to the (I mod n) Broker
  • The JTH Replica of the ith Partion is allocated to the ((I +j) mod n) Broker
  • What are some common problems with MQ? How to solve these problems?
  • Message queue order problem

  • Message order means that messages can be consumed in the order in which they were sent
  • Suppose the producer produces two messages :M1,M2. Suppose M1 is sent to S1 and M2 to S2. If we want to ensure that M1 is consumed before M2, how to ensure that:
    • Solution:
      • Ensure that the producer-MQserver-consumer relationship is one to one
    • Defect:
      • The degree of parallelism can become the bottleneck of the system, and the throughput is not enough
      • There will be more exception handling problems: whenever a consumer has a problem, the entire process will be blocked and the blocking will have to be resolved
      • This can be avoided by rational design or by breaking the problem down:
        • There are a lot of applications that don’t care about chaos
        • An out-of-order queue does not mean an out-of-order message
  • Message duplication problem:
    • Root cause of message duplication: The network is unreachable
    • So the way to solve this problem is to get around it. That is: If the consumer receives two identical messages, what should it do?
      • Solution:
        • The business logic for processing messages on the consumer side remains idempotent
          • As long as the idempotent, no matter how many repeated messages come, the final result is the same
          • Ensure that each message has a unique number and that the success of the message processing occurs at the same time as the log of the de-duplication table
          • A log table is used to record the IDS of messages that have been processed successfully. If a new message ID is already in the log table, the message is no longer processed
  • Kafka, ActiveMQ, RabbitMQ, RocketMQ each have advantages and disadvantages?

  • What is Dubbo? Main application scenarios? Core features?
  • Dubbo implementation process?

  • Dubbo Node role?

  • Call relationship in Dubbo?
  • The service container is responsible for starting, loading, and running service providers
  • At startup, a service provider registers its services with the registry
  • Service consumers, at startup, subscribe to the registry for the services they need
  • The registry returns a list of service provider addresses to the consumer, and if there are changes, the registry pushes the change data to the consumer based on the long link
  • The service consumer, from the list of provider addresses, selects a provider to invoke based on the soft load balancing algorithm. If the call fails, another machine is selected for the call
  • Service consumers and service providers accumulate the number of calls and call time in memory, and regularly send statistical data to the monitoring center every minute
  • With Dubbo’s registry cluster down, is communication still possible between publishers and subscribers?
  • What protocols does Dubbo support, what are the application scenarios of each protocol, and what are their advantages and disadvantages?
  • How to set the Dubbo timeout period?
  • What are the load balancing policies of Dubbo?
  • Random:
    • Random load balancing policy: set the random probability based on the weight
    • The probability of collision on a cross section is high, but the larger the amount of modulation, the more uniform the distribution, and the more uniform the weight is used according to the probability, which is conducive to the dynamic adjustment of the provider weight
  • RoundRobin:
    • Round-robin load balancing policy. The round-robin load balancing ratio is set based on the weight after the convention
    • There is a problem with slow provider accumulation of requests
    • For example: the second machine is slow, but not down, and when the request to the second machine will be stuck, over time, all requests will be stuck when the switch to the second machine
  • LeastActive:
    • Minimum number of active calls Load balancing policy. Random calls with the same number of active calls. The active number refers to the count difference before and after the call
    • Slow providers receive fewer requests, because the slower the provider, the bigger the count difference before and after the invocation
  • ConsistentHash:
    • Consistent Hash load balancing policy. Requests with the same parameters are always sent to the same provider
    • When a provider goes down, requests originally sent to that provider are amortized to other providers, based on virtual nodes, without drastic changes
    • < dubbo:parameter key=” Hash. Arguments “value=”0,1″ /> < dubbo:parameter key=” Hash. Arguments” value=”0,1″ />
    • < dubbo:parameter key=”hash. Nodes “value=”320” >
  • Dubbo Cluster Fault tolerance Strategy?

  • Failover: Automatic Failover occurs when a failure occurs. If the failure occurs, try another server. Usually used for read operations, but retries can cause longer delays. You can set retries=”2″ to set the number of times to retry, excluding the first time
  • Failfast: indicates a fast failure. The call is made only once and an error is reported immediately if the call fails. Usually used for nonidempotent write operations, such as adding a record
  • Failsafe: Failsafe. When an exception occurs, it is ignored directly. It is used to write audit logs
  • Failback: Automatically recovers the failed request. The background records the failed request and resends the request periodically. Commonly used for message notification operations
  • Forking: Calls multiple servers in parallel, returning if one succeeds. The maximum number of concurrent operations can be set by setting forks=”2″. (Forks =”2″
  • Broadcast: Broadcast calls all providers one by one, and any one of them reports an error. It is typically used to notify all providers to update local resource information such as caches or logs
  • Dubbo’s dynamic proxy strategy?
  • As an RPC framework, Dubbo first completes cross-system and cross-network service invocation
    • Consumers and providers follow a uniform interface definition
      • When the consumer calls the interface,Dubbo converts it into a data structure in a uniform format
      • Through the network transmission, the provider finds the interface implementation according to the rules and completes the invocation through reflection
    • The consumer gets a proxy for the remote serviceProxy,Providers need a wrapper because they want to support different interface implementationsWrapper
      • Call procedure:

      • The consumer Proxy and the provider Wrapper enable Dubbo to build a complex and unified system
      • This dynamic proxy and wrapper is implemented through the SPI plug-in with the ProxyFactory interface:
      @SPI("javassist")
      public interface ProxyFactory {
      		@Adaptive({Constants.PROXY_KEY})
      		<T> T getProxy(Invoker<T> invoker) throws RpcException;
      		@Adaptive({Constants.PROXY_KEY})
      		<T> invoker<T> getInvoker(T proxy, Class<T> type, URL url) throws RpcException;
      }
      Copy the code
      • ProxyFactor can be implemented in two ways:
        • JDK based proxy implementation
        • Javassist-based implementation
      • @SPI(” Javassist “) is defined on the ProxyFactory interface, which defaults to the Javassist implementation
  • What registries are available in Dubbo?
  • The relationship between Dubbo and Spring?
  • What communication framework does Dubbo use?
  • How is Dubbo security implemented?
  • What’s the difference between a Dubbo registry connection and a direct connection?
  • Dubbo communication Protocol Why does Dubbo adopt the asynchronous single persistent connection mode?
  • Dubbo communication protocols Applicable Scope and application scenarios of Dubbo?
  • What serialization protocols does Dubbo support? Hessian? Hessian’s data structure?
  • Dubbo Serialization: Ali’s Java-based serialization implementation
  • Hessian2 serialization: Hessian is an efficient binary serialization across languages. This is not native Hessian2 serialization, but ali’s modified Hessian Lite serialization, which is enabled by Dubbo by default
  • Json serialization:There are currently two implementations:
    • Use Ali’s FastJSON library
    • Simple Json library implemented by Dubbo itself
      • In general,json text serialization is not as good as binary serialization
  • Kryo and FST: Kryo and FST generally perform better than Hessian and Dubbo serialization
  • What is the difference between Hessian serialization and the Java default serialization?
  • Hessian is a lightweightremoting on httpTools, adoptBinary RPCProtocol, very suitable for sending binary data, but also has firewall penetration
    • Hessian supports serialization across languages
    • Hessian serialization offers better performance and ease of use than Java’s default serialization
    • Hessian serialization supports a number of languages
  • What’s a Protoco Buffer?
  • Protoco Buffer is a lightweight and efficient structured data storage format from Google, which is much more powerful than Json and XML
  • Protoco serialization and deserialization are simple and fast. The reasons are:
    • Simple encoding and decoding, only simple mathematical operations = displacement and so on
    • Using Protoco Buffer’s own framework code and the compiler
  • Protoco Buffer has good compression effect, that is, the volume of serialized data is small. The reasons are:
    • Adopt unique coding method, such as Varint,Zigzag coding method and so on
    • T – L – V data storage method, reduce the use of delimiters and data storage compact
  • The registry is down. Can we continue to communicate?
  • can
  • Dubbo consumers pull the address interfaces of registered producers from the registry and cache them locally when the application starts. Each time a call is made, the call is made at the locally stored address
  • What’s ZooKeeper for? What does ZooKeeper work on?
  • ZooKeeper is a distributed application coordination system that has been used in many distributed projects to complete
    • Uniform Naming Service
    • Status synchronization service
    • Cluster management
    • Manage distributed application configuration items

  • Each Server stores one copy of data in memory
  • When ZooKeeper starts, a leader(Paxo protocol) is elected from the instance
  • The Leader handles operations such as data updates (Zab protocol)
  • An update operation succeeds if and only if most servers successfully modify data in memory
  • What’s Netty for? What’s NIO,BIO,AIO for? What’s the difference?
  • Netty is a network communication framework
  • Netty event processing process:
    • Channel is the connection Channel, is the producer of ChannelEvent
    • ChannelPipeline can be understood as a collection of ChannelHandlers

  • IO modes are usually divided into:
    • Synchronizing the blocking BIO
    • Synchronize non-blocking NIO
    • Asynchronous non-blocking AIO
  • For network applications using synchronous blocking BIO:
    • If you want to process multiple client requests at the same time, or if the client is communicating with multiple servers at the same time, you must use multithreading
  • Synchronous non-blocking NIO based on Reactor:
    • When a stream can be read or written to the socket, the operating system notifys the corresponding reference program to process the stream, and the application reads the stream into the buffer or writes the stream to the operating system
    • At this point, either a connection corresponds to a processing thread. It is a valid request that corresponds to one thread, and when the connection has no data, there is no worker thread to process it
  • Asynchronous non-blocking AIO differs from NIO:
    • When reading or writing, you simply call the READ or write methods of the API
    • Both methods are asynchronous:
      • For read operations, when a stream is available, the operating system feeds the readable stream into the buffer of the read method and notifies the application
      • For write operations, the operating system actively notifying the application when it has finished writing the stream passed by the write method
    • The read or write methods are asynchronous, and the callback function is invoked actively after completion
  • Why split the system? Can you split it without Dubbo?
  • Classification of system split:
    • From the perspective of resources:
      • Application of split
      • Database splitting
    • From the order of adoption:
      • Horizontal scaling
      • The vertical resolution
      • business
      • Horizontal split

  • Whether to use Dubbo depends on the actual business scenario:
    • With the increasing number of vertical applications, the interaction between applications is inevitable. Core businesses are extracted as independent services and a stable service center is gradually formed to enable front-end applications to respond more quickly to changing market demands. At this point, RPC, a distributed framework for improving business reuse and integration, is key
    • When the number of services increases, problems such as capacity evaluation and waste of small service resources gradually appear. In this case, a scheduling center needs to be added to manage cluster capacity in real time based on access pressure to improve cluster utilization. At this point, the resource scheduling and governance center SOA to improve machine utilization is key
  • What’s the difference between Dubbo and Thrift?
  • Dubbo supports service governance, while Thrift does not
  • Thrift is a cross-language RPC framework
  • How does Redis implement distributed locking?

SetNX key value Value is unique to prevent thread A from releasing the lock acquired by thread B

  • If the setNX command is used, how can other services get the lock if the locked machine is down?

Setting the Expiration Time

  • How to set expiration time? Set the key value first and then set the expiration time? If two commands are used,set key value succeeds but expiration time fails, the preceding problems also exist. So how to ensure that the set key value and set the expiration time atomic operation?

The set command provides atomic operation commands to guarantee the set key value and set the expiration time of the atomic operation

  • Is Redis the cluster used? If it is a cluster, when the client executes setNX to Redis the cluster, how do I consider the set to be successful? If half of the cluster set is successful, is it considered successful? Or is success considered only when all sets are successful?

The Redis cluster uses multiple master nodes and multiple slave nodes. The Redis cluster is successful only when more than half of the master nodes are set successfully

  • Half success even if successful, suppose Redis cluster have a, b, c three main nodes, each have a slave node, thread a in a, b, the master node set success, and in the master node set c failure, this thread a access to the lock, and just at this time the master node b is down, just data is not synchronized to the slave node, then at that moment, from node b ‘upgrading to the master node, it Thread B executes the set command on the same key to acquire the lock. When B ‘and C successfully set the lock, multiple threads acquire the lock.
  • How to update the Redis cache?

Delete the cache first, then update the DB, and delay the Delete cache for a period of time or update the DB first, and delay the Delete cache for a period of time

  • Why the delay?

If thread A first deletes the cache and thread B finds that there is no data in the cache, it will read the old data from the DB and reload it to the cache. After thread A updates the database, the cache is inconsistent with the data in the database, so the deletion needs to be delayed for some time

  • If Delete fails?

Retry mechanism

  • What are the data structures in Redis? In what scenarios is the skip table used?
  • Volatile keyword? Lock?
  • Problems in concurrent programming:
    • Atomicity problem
    • Visibility problem
    • Order problem
  • volatile:
    • The volatile keyword guarantees visibility and only disallows reordering of instructions, not atomicity
    • Visibility only guarantees that the latest value is read each time, but volatile does not guarantee atomicity of operations on variables
    • Add the Lock keyword and memory barrier to generated variable statements
  • Lock:
    • A Lock implementation provides a wider range of locking operations than can be achieved using synchronized methods and statements, and can solve thread synchronization problems in a more elegant manner
    • Methods or statements modified with synchronized release the Lock automatically after code execution, whereas methods or statements modified with Lock release the Lock manually
  • Java needs to be recompiled and packaged for deployment every time it is modified. Is there a better way?

Hot deployment

  • What are the ways of interprocess communication?
  • Pipe, Pipe
  • Named Pipe: Named Pipe
  • Signal: Signal
  • Message queue: Message
  • The Shared memory
  • Memory mapping: Mapped Memory
  • Semaphore: Semaphore
  • Socket: Socket
  • Synchronized method instance?

Synchronized refers to static methods. The lock itself is not an instance. Non-static methods lock instances

  • When does an operating system deadlock occur?
  • Deadlock: A deadlock caused by multiple running processes competing for resources
  • Cause:Compete for resources
    • When multiple processes in the system use shared resources, and the resources are insufficient to meet the requirements, the process will compete for resources, resulting in deadlock
    • Improper sequence of progress between processes
    • The wrong order in which resources are requested and released can also result in process deadlocks
  • The four conditions that produce a deadlock
  • Mutually exclusive: Processes monopolize resources
  • Request and hold: When a process is blocked by a request for a resource, it holds a resource that has been obtained
  • Non-deprivation condition: a process has obtained resources and cannot forcibly take them away until they are used up
  • Circular wait: Several processes form an end-to-end circular wait for resource relationships
  • How to understand distributed locking?

Online servers are distributed and deployed, so they often face the problem of data consistency in distributed scenarios. Distributed locks are needed to solve these problems

  • What are the implementations of distributed transactions?
  • Architecture for microservices?

JVM

  • Java class initialization order?
  • Java class initialization order:
    • Base class static code block, base class static member variables. They are executed in the order they appear in the code, and only on the first load
    • Derived class static code block, derived class static member variables. They are executed in the order they appear in the code, and only on the first load
    • Base class ordinary code block, base class ordinary member variables. Rank priority, in the order in which the code block appears
    • Base class constructor.
    • Derived class ordinary code block, derived class ordinary member variables. Rank priority, in the order in which the code block appears
    • Derived class constructor.
  • Why do we do generations?
  • What is the understanding of method and permanent areas and the difference between them?
  • The method area is required by the JVM specification, and the permanent area is the specific implementation of the method area by the Hotspot virtual machine
  • The method section is the specification, the permanent section is the implementation (changed since JDK 1.8)
  • A Java class has three files. How many class files are compiled?
  • There are several classes in the file, and there are several class files when compiled
  • Local variables need to be explicitly assigned before they are used, otherwise they won’t pass compilation. Why design them like this?
  • Member variables can be left uninitialized and given default values during the preparation of the class loading process.
  • Local variables need to be explicitly assigned initial values before they can be used
  • Javac not infer that can not do so, for the member variable, in the order of the assignment and access values of uncertainty, for a member variable can assignment before a method call, also can undertake the assignment after the method call, it is running, the compiler can’t find it out, do more appropriate to the JVM
  • For local variables, the assignment and access order of local variables are determined, so the design is a constraint to minimize the possibility of user error:
    • Given that local variables can have default values, you can always inadvertently forget to assign them, which can lead to unexpected situations
  • Memory partitions for the JVM?
  • The partitions of heap memory and the garbage collection algorithm for each partition? Recycler G1,CMS is marked clear, mark sorting method?
  • How to check Full GC,OOM?
  • Too many threads will result in an OOM, but does this include all the threads in the program? Like a thread pool that includes pigeon?
  • What are the methods in the parent delegation model for class loading in the JVM?
  • Class loading process:
    • loading
    • Validation: The validation phase ensures that the byte stream of a Class file contains information that complies with JVM specifications and does not cause harm to the JVM
    • Preparation: The preparation phase allocates memory for variables and sets the initialization of class variables
    • Parsing: The process of parsing is to replace symbolic references in the constant pool with direct references
    • Initialize the
  • Methods in the parent delegate model:A parent delegate means that if a class receives a class loading request, it does not try to load the class itself first, but finds the parent class loader first. When the class loader is started at the top level to indicate that the class cannot be loaded, subclasses will load it themselves. Instead of looking down, a ClassNotFound exception is thrown when the loader can’t load back to the original originator
    • Bootstrap the class loader
    • Standard Extension class loader
    • Application class loaders
    • Context (Custom) class loaders
    • The meaning is to prevent multiple copies of the same bytecode from appearing in memory
  • What does the garbage collector know?
  • What are GC ROOTS?
  • The GC algorithm? What kind of object is a recyclable object? Accessibility analysis? CMS collector?
  • How does the JVM determine if an object has become garbage recyclable?
    • Reference counter method: Reference counter does not solve the circular reference problem
    • Root search algorithm: Starting from a series of GC Roots, search down the path called the reference chain. When there is no chain of references between an object and GC Roots, it is called reference unreachable. Objects whose references are unreachable are considered recyclable
  • Several types of garbage collectors:
    • Serial New or Serial Old: Serial
    • Parrallel New: in parallel
    • Parrallel Scavenge
    • Parrallel Old
    • G1: a parallel and concurrent collector that models predictable pause times, based on mark cleaning overall and replication locally
    • CMS
  • CMS collector is a collector aiming at obtaining the shortest collection pause time. It is a concurrent collector using the Mark-Sweep algorithm
  • How is the GC replication algorithm implemented in the JVM?
  • What regions is the JVM divided into? What does each zone do?
  • Method area: Shared by all threads, the Method area contains all class information and static variables
  • Heap: Shared by all threads and containing object instances and arrays, the Java Heap is the primary area for GC
  • Stack: Each thread contains a Stack in which local variables are stored
  • Program counter: An indicator of the lines of bytecode executed by the current thread
  • The NEW generation of JVM, the old generation, and the persistent generation. What does it store?
  • A new generation stores all newly generated objects
  • In the old days, objects with a longer life cycle were stored
  • The persistence generation mainly stores class information about Java classes and has little to do with the Java objects to be collected by garbage collection
  • Memory overflow and memory leak?
  • Out of memory: when a program requests memory, there is not enough memory
  • Memory leak: Garbage objects cannot be collected, but use the Memory Analyzer tool to look for leaks
  • Processes and threads?
  • Process: a running program that is independent, dynamic, and concurrent
  • Thread: the sequential flow of execution in a process
  • The difference between processes and threads:
    • Memory is not shared between processes
    • It is much more expensive to create processes for resource allocation, so multithreading is more efficient in a highly concurrent environment
  • Serialization and deserialization?
  • Serialization: Converting a Java object into a sequence of bytes
  • Deserialization: Converts a sequence of bytes into a Java object
  • Serialization and deserialization are mainly used for communication between Java threads, to achieve object transfer. Only objects that implement Serializable or Externalizable interfaces can be serialized
  • What is the length of an int in a 64-bit JVM?

In the JVM, the length of a variable of type int is a fixed value, platform independent,4 bytes and 32 bits long

  • What is the difference between WeakReference and SoftReference in Java?
  • There are four types of references in Java:
    • StrongReference
    • SoftReference
    • WeakReference
    • PhantomReference
  • A StrongReference is the default Reference implementation for Java, which lives in the JVM as long as possible and is collected by GC when no object points to it
  • SoftReference holds the reference as long as possible until the JVM runs out of memory, guaranteed by the VIRTUAL machine. This feature makes SofeReference ideal for caching applications
  • WeakReference is a WeakReference. When the referenced object no longer has a strong reference in the JVM, it will be reclaimed by GC
  • The difference between WeakReference and SoftReference:
    • WeakReference and SoftReference are beneficial to improve the efficiency of GC and memory
    • Once WeakReference loses the last strong reference, it will be collected by GC
    • SoftReference holds the reference as long as possible until the JVM runs out of memory, guaranteed by the VIRTUAL machine
  • Partition of JVM memory?
  • Java heap partition?
  • What’s the difference between heap and stack in Java?
  • The heap and stack in Java belong to different areas of memory and are used for different purposes
  • Stacks are typically used to hold method frames and local variables. Objects are always allocated on the heap
  • The stack is usually smaller than the heap and is not shared across multiple threads, whereas the heap is shared by all threads throughout the JVM
  • Java heap space and GC?
  • Java heap space:
    • When a Java process is started with a Java command, memory is allocated, part of which is used to create heap space
    • When an object is created in a program, memory is allocated from the heap space
  • GC:
    • GC is a process within the JVM that reclaims the memory of invalid objects for future allocation
  • Which objects will be reclaimed by the JVM?

network

  • How does TCP ensure reliable transmission? Three handshakes?
  • In a TCP connection, data flows must arrive at each other in the correct order

-TCP reliability:

  • By sequential coding and acknowledgment (ACK)
  • TCP connections are initialized using a three-way handshake. The purpose of the three-way handshake is to synchronize the serial numbers and acknowledgement numbers of the two sides of the connection and exchange TCP window size information:
    • First time: The client initiates a connection
    • Second time: Indicates that the server receives the client request
    • Third time: Indicates that the client receives feedback from the server
  • How do I recognize a session?
  • The session ID stored in the cookie
  • HTTP Message structure?
  • HTTP status code?
  • Common commands in Linux:
  • CD: used to change the directory. CD / – goes to the root directory, CD ~ – goes to the user directory
  • Ls: displays the contents of a directory
  • Cp: used to copy a file cp sourceFileName targetFileName
  • Mv t.txt Document
  • What are the common Hash algorithms?
  • Additive Hash: An additive Hash is the process of adding the input elements one by one to form the final result
  • Bit-operated Hash: This type of Hash function fully mixes input elements by utilizing various bit-operated operations, such as shift or XOR
  • Multiplication Hash: 33*hash + key.charAt(i)
  • What is a consistent Hash?
  • The design goal of consistent Hash is to solve the Hot spot problem in the Internet. The consistent Hash algorithm proposes four definitions to determine the quality of a Hash algorithm in a dynamically changing Cache environment:
    • Balance: Balance
    • Monotonicity: Monotonicity
    • Dispersion: Spread
    • Load, the Load
  • What’s the difference between get and POST in form submission?
  • Get is to get information from the server, and POST is to send information to the server
  • Get can transmit a small amount of data, while POST can transmit a large amount of data
  • Get is less secure than POST
  • What is the difference between TCP and UDP?
  • TCP: Tranfer Control Protocol. It is a connection-oriented guarantee transport Protocol. Before the transmission of data, two parties establish a virtual communication channel, which can transmit data with few errors
  • UDP:User DataGram Protocol is a connectionless Protocol. When using UDP, each data segment is an independent piece of information, including the complete source address and destination. It reaches the destination by any possible path on the network. Therefore, whether or not the destination can be reached, as well as the time and the integrity of the content of the destination can not be guaranteed
    • TCP takes longer to establish a connection than UDP. Compared with UDP,TCP has higher security and reliability
    • The size of TCP is unlimited. Once a connection is established, both parties can transfer a large amount of data in a certain format. However, UDP is an unreliable protocol with a limited size
  • What are the Java IO models?
  • What’s the difference between synchronous and asynchronous, blocking and non-blocking?
  • Introduction to Netty