Java Interview Summary

  • For more information, please follow my official account: nezha_blog
  • My tech blog: nezha.github. IO

1. Which collection classes have you used?

40 Java Collections Interview Questions and Answers Java.util. Collections is a wrapper class. It contains a variety of statically polymorphic methods for collection operations. Java.util. Collection is a Collection interface. It provides generic interface methods for performing basic operations on collection objects.

├List │├LinkedList │├ArrayList │├ Stack ├ Set ├Hashtable ├HashMap ├ WeakHashMap


The ArrayList, HashMap, TreeMap, and HashTable classes provide random access to elements.

Thread safety

Vector HashTable(no inserts allowed)

Non-thread-safe

ArrayList LinkedList HashMap(allows null values to be inserted) HashSet TreeSet TreeMap

2. What is the difference between arrayList and LinkedList?

ArrayList and LinkedList both implement the List interface, but there are some differences between them. (1) ArrayList is an index-based data structure supported by Array, so it provides random access to elements (2) Compared with ArrayList, Inserting, adding, and removing an element into LinkedList is faster (3) LinkedList consumes more memory than ArrayList because each node in LinkedList stores references to the nodes before and after

3. How is the underlying implementation of HashMap? What other ways to handle hash conflicts?

Methods for handling hash conflicts:

There is generally no particularly good way to solve a HashMap, either expand and rehash or optimize the structure of a conflicting list

1. Open fixed address method – linear detection method 2. Open fixed address method – square detection method 3. Linked list solution – red black tree can be used to improve search efficiency

Introduction to HashMap A HashMap is a hash table that stores key-value mappings. HashMap extends AbstractMap and implements Map, Cloneable, java.io.Serializable interfaces. The implementation of HashMap is not synchronous, which means it is not thread-safe, but the Collections synchronizedMap method can be used to make HashMap thread-safe. Both key and value can be null. In addition, the mappings in a HashMap are not ordered. Instances of a HashMap have two parameters that affect its performance: “Initial capacity” and “load factor.” The default initial capacity is 16. The default loading factor is 0.75, which seeks a compromise between time and space costs. The high loading factor reduces the space overhead, but also increases the query cost. HashMap is implemented by array + list + red-black tree (JDK1.8 added red-black tree section). When the list length is too long (default is more than 8), the list is converted to red-black tree.

Java8 series – re-understanding the implementation of HashMap functionality – methods

  1. Determine the index position of the Hash bucket array: The Hash algorithm here is essentially three steps: the hashCode of the key, the high level operation, and the modulus operation.
Method one:static final int hash(Object key) {   / / jdk1.8 & jdk1.7
     int h;
     // h = key.hashcode () takes the hashCode value for the first step
     // h ^ (h >>> 16) participates in the second step
     return (key == null)?0 : (h = key.hashCode()) ^ (h >>> 16); } Method 2:static int indexFor(int h, int length) {  //jdk1.7 source code, JDk1.8 does not have this method, but the implementation principle is the same
     return h & (length-1);  // The third step is the modulo operation
}
Copy the code
  1. Analyze the PUT method of a HashMap
  1. Expansion mechanism: double the original

4. What algorithms are you familiar with, and tell me about their time complexity?

Summary and implementation of classical sorting algorithm

5. The underlying code of ArrayList and Vector and their growth strategies, how do they scale up?

The default array size of ArrayList is 10, where ensureCapacity is expanded, trimToSize is adjusted to moderate, and the array size is ((the original array length *1.5) and the larger of the passed parameters. Vector expansion factor can be specified, and the Vector expansion policy is: 1. Double the original capacity. 2. Original capacity + Capacity expansion parameter value.

Detailed content can be read with the source code

6. The JVM principle. Program run area division

Q: Java runtime data areas? Answer: Includes program counters, JVM stacks, local method stacks, method areas, and heaps. Native method stack: Serves a similar role to the JVM stack, except that the JVM stack performs Java methods (bytecode) for the JVM, while the native method stack serves native methods used by the JVM. JVM stack: local variable table, operand stack, dynamic linking, method exit. Method area: used to store information about classes that have been loaded by the virtual machine, constants, static variables, code compiled by the just-in-time compiler, etc. Heap: Stores object instances.

7. When will minor GC and Full GC trigger? . Which garbage collection algorithms are used? A brief introduction to the algorithm

GC (or Minor GC) : Collects Young areas with short life cycles. Full GC (or Major GC) : Collect Young areas with short life cycles and Old areas with long life cycles for garbage collection of the entire heap. This generation is usually short-lived recycling based on algorithms that divide available memory into two pieces of equivalent size and use only one piece at a time. When this block is used up, the surviving objects are copied onto the other block, and the used memory is cleaned up. In HotSpot, given the short lifetime of most objects, memory is divided into Eden and two Survivor, with a default ratio of 8:1:1. The cost is that there is some memory space waste, suitable for use in the new generation; Old s different in Cenozoic, the object s survival time is longer and more stable, so Mark (Mark) algorithm is used to recycle, the so-called marker is scanning the object of survival, and then recycling has not been labeled objects, recycled to use empty space to merge, or marked for next time allocated, The overall goal is to reduce the efficiency loss caused by memory fragmentation. The JVM provides Serial GC(Serial MSC), Parallel MSC (Parallel MSC), and concurrent GC(CMS) in terms of execution mechanism.

Minor GC, Full GC triggers conditions

  • Minor GC triggering condition: When the Eden field is full, the Minor GC is triggered.

  • Full GC trigger condition:

  • (1) When system. gc is called, Full GC is recommended, but not necessarily executed

  • (2) Insufficient space in the old era

  • (3) Insufficient space for method to go

  • (4) The average size of the old generation after passing the Minor GC is larger than the available memory of the old generation

  • (5) If the size of the object is larger than the available memory of To Space, the object is transferred To the old age, and the available memory of the old age is smaller than the size of the object

8. Implementation principle of HashMap

In the Java programming language, there are two basic structures, one is an array, the other is a mock pointer (reference), all data structures can be constructed with these two basic structures, HashMap is no exception. A HashMap is actually a “linked list hash” data structure, which is a combination of arrays and lists.

9. What is used under the java.util.concurrent package

1. Block queue BlockingQueue(ArrayBlockingQueue, DelayQueue, LinkedBlockingQueue, SynchronousQueue will LinkedTransferQueue, LinkedBlockingDeque ConcurrentHashMap. 3. 3. 4 Semaphore — Semaphore CountDownLatch – atresia 5. 6 CyclicBarrier – fence. Exchanger – switch 7. Executor – > ThreadPoolExecutor, ScheduledThreadPoolExecutor

Semaphore semaphore = new Semaphore(1);  
//critical section  semaphore.acquire(); . semaphore.release();Copy the code

8. Lock Lock – already ReadWriteLock, Condition, LockSupport

Lock lock = new ReentrantLock();  
lock.lock();  
//critical section  
lock.unlock();
Copy the code

10. ConcurrentMap is different from HashMap

1. HashMap can have null keys, concurrentMap cannot have null keys. 2. It needs to be in a multithreaded Collections. SynchronizedMap (hashMap), the ConcurrentMap using the reentrant lock ensure thread safety. 3. When deleting elements, the two algorithms are different. The main difference between ConcurrentHashMap and Hashtable is around the granularity of locks and how to lock them. This can be simply interpreted as splitting a large Hashtable into multiple locks.

11. What is a semaphore and how to use it? What is the volatile keyword?

Semaphore: A synchronization mechanism proposed in 1965 by Dijkstra, a famous Dutch computer scientist. A facility used in a multithreaded environment that coordinates threads to ensure that they use common resources correctly and reasonably. Shaping semaphore: Represents the state of the shared resource and can only be changed by a special atomic operation. Synchronization and mutual exclusion: The same process is mutually exclusive (printer problem), and the different process is synchronous (consumer producer).


The use of the volatile keyword is an effective solution to the synchronization problem. The Java volatile keyword indicates that the variable is always “storage into main memory.” A more accurate statement is that each read of a volatile variable is read from main memory, not the CPU cache. Similarly, each time a volatile variable is written, it is written back to main memory, not just the CPU cache. Java guarantees that the volatile keyword ensures that changes to variables are visible to individual threads.

12. Blocking queue understand? How to use

BlockingQueue is an important data structure under the Java Util. concurrent package. BlockingQueue provides thread-safe access to queues. When fetching data from a blocking queue, if the queue is empty, the thread will block and wait until the queue is empty. Many advanced synchronization classes are implemented based on BlockingQueue.

In the case of ArrayBlockingQueue, let’s take a look at the code:

public void put(E e) throws InterruptedException {
    if (e == null) throw new NullPointerException();
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();
    try {
        while (count == items.length)
            notFull.await();
        enqueue(e);
    } finally{ lock.unlock(); }}Copy the code

If the number of elements is equal to the length of the array, it calls notfull.await () and waits. When it is woken up by another thread, it inserts the element through enqueue(e) and finally unlocks the element.

/**
* Inserts element at current put position, advances, and signals.
* Call only when holding lock.
*/
private void enqueue(E x) {
    // assert lock.getHoldCount() == 1;
    // assert items[putIndex] == null;
    final Object[] items = this.items;
    items[putIndex] = x;
    if (++putIndex == items.length) putIndex = 0;
    count++;
    notEmpty.signal();
}
Copy the code

After successful insertion, the thread waiting to fetch the element is awakened by notEmpty.

13. What are NIO, BIO, and AIO in Java?

There are several types of IO, synchronous blocking BIO, synchronous non-blocking NIO, and asynchronous non-blocking AIO

1.BIO, synchronous blocking IO, simple to understand: one thread at a time. BIO mode is suitable for small and fixed number of connections. This mode requires high server resources, concurrency is limited to the application, and the only choice before JDK1.4, but the program is intuitive, simple and easy to understand.

Prior to JDK1.4, writing a network request in Java would set up a ServerSocket. Then, when the client set up the Socket, it would ask if there was a thread available to handle it. If not, it would either wait or be rejected. That is, one connection requires that the Server correspond to one processing thread.

NIO, synchronous non-blocking IO, simple to understand: one thread per request. NIO is suitable for architectures with a large number of connections and relatively short (light operation) connections, such as chat servers, where concurrency is limited to applications and programming is complicated. JDK1.4 supports NIO.

NIO itself is event-driven and addresses the large concurrency problem in BIO: In web applications that use synchronous I/O, multiple client requests must be processed simultaneously, or clients must communicate with multiple servers simultaneously. That is, each client request is assigned to a thread to process separately. This will do what we want, but at the same time, it will cause another problem. Each time a thread is created, a certain amount of memory (also known as working memory) is allocated for that thread, and the operating system itself has a limit on the total number of threads. If the client requests too much, the server may become overwhelmed and reject the client’s requests, or even crash the server.

3.AIO, asynchronous non-blocking IO, simple to understand: a valid request to a thread. AIO mode is used in the architecture with a large number of connections and long connections (heavy operation), such as photo album server. It fully calls OS to participate in concurrent operations, and the programming is complicated, which is supported by JDK7.

14. What is the class loading mechanism

The loading of classes in the JVM is implemented by the ClassLoader, an important Component of the Java runtime system, and its subclasses. It is responsible for finding and loading the classes of the class file at runtime. There are five processes for class loading: loading, validation, preparation, parsing, and initialization.

The entire life cycle of a class is divided into seven phases, from when it is loaded into virtual machine memory to when it is unmounted from memory. 2, Loading, Verification, Preparation, Resolution, Initialization, Using, Unloading. Verification, preparation, and resolution are collectively referred to as connections.

15. What is idempotency

Idempotent, simply put, means that multiple calls to an interface produce the same result as one call. So why do we need interfaces to be idempotent? Consider the following scenario:

  • When PLACING an order in the App, I clicked “confirm”, but there was no response, so I clicked it several times. In this case, if the idempotent nature of the interface is not guaranteed, the repeat order problem will occur.
  • The message push repeats when the message is received. If the interface handling the message is not idempotent, the impact of repeated consumption of the message can be significant.

16. Experience with JVM tuning

Summary of Jvm parameters: http://linfengying.com/?p=2470

Memory parameters

parameter role
-Xmx The maximum heap size. The heaps of current mainstream virtual machines are scalable
-Xms The minimum heap size. You can set it to the same value as -xmx
-Xmn The size of the Cenozoic. Modern virtual machines are “generational”, so the heap space is made up of the new generation and the old generation. As the Cenozoic age increases, the old age decreases correspondingly. Sun officially recommends that the new generation make up 3/8 of the heap
-Xss Stack size per thread. This value affects the maximum number of threads a machine can create
-XX:MaxPermSize= The maximum number of permanent generations. Persistent generation is specific to HotSpot, which uses persistent generation to implement method areas
-XX:PermSize= The minimum value of a permanent generation. It can be set to the same value as -xx :MaxPermSize
-XX:SurvivorRatio= Ratio of Eden to Survivor. The copy-based garbage collector in turn classifies the new generation into one Eden and two survivors, and if this parameter is 8, Eden is Eden
-XX:PretenureSizeThreshold= Directly to the size of the object of the old age. Objects larger than this parameter will be allocated directly in the old age. The default value is 0, indicating that the function is disabled
-XX:HandlePromotionFailure= Whether to allow assignment guarantees to fail. This parameter is invalid after JDK 6 Update 24.
-XX:MaxTenuringThreshold= The object advances to the age of the old age. The age of the object is incremented by one after each Minor GC, and the age beyond this value is old. The default value is 15
-XX:MaxDirectMemorySize= Maximum value of direct memory. For applications that use NIO frequently, this parameter should be set explicitly, with a default value of 0

The GC parameter

Garbage collector parameter note
Serial (New Generation) -XX:+UseSerialGC Default value for the VM in Client mode. After this function is enabled, the collector combination of Serial + Serial Old is used. Serial is a single-threaded collector
ParNew -XX:+UseParNewGC Enforces the use of ParNew, and when this switch is turned on, the collector combination of ParNew + Serial Old is used. ParNew is a multithreaded collector and the preferred new generation collector in server mode
-XX:ParallelGCThreads= Number of garbage collection threads
Insane. -XX:+UseParallelGC The default value of the VIRTUAL machine in Server mode. Use the Parallel Scavenge + Serial Old collector combination when this switch is turned on
-XX:MaxGCPauseMillis= In milliseconds, the collector tries to ensure that a single memory reclamation pause does not exceed this value.
-XX:GCTimeRatio= The percentage of the application’s total time spent on GC, which is used to control the throughput of the program
-XX:+UseAdaptiveSizePolicy After setting the parameters, it is no longer need to specify the size of the Cenozoic (Xmn), Eden and Survisor (- XX: SurvivorRatio), and the proportion of the old s promotion object’s age (- XX: PretenureSizeThreshold), This is because the collector adjusts automatically based on how the current system is running. Of course, the premise is to set the first two parameters.
Serial Old There is no Serial Old is an older version of Serial, which is mainly used for collecting Old generations in Client Mode and as a backup solution for CMS in the event of Concurrent Mode Failure
Parallel Old -XX:+UseParallelOldGC When this switch is turned on, use the Parallel Avenge + Parallel Old collector combination. The Parallel Old is an older version of the Parallel Insane, a combination that can be preferred in throughput and CPU resource-sensitive applications
CMS (The Old days) -XX:+UseConcMarkSweepGC When this switch is turned on, the collector combination of ParNew + CMS is used.
-XX:CMSInitiatingOccupancyFraction= The CMS collector triggers garbage collection after how much old chronspace has been used
-XX:+UseCMSCompactAtFullCollection Whether to do a memory defragmentation after garbage collection
-XX:CMSFullGCsBeforeCompaction= Memory defragmentation takes place after several garbage collections

Graphic: Collector combinations that can be used together

There are seven collectors, divided into two parts, the Cenozoic collector on the top and the old collector on the bottom. If there is a wire between two collectors, they can be used together.

The other parameters

parameter role
-verbose:class Print the class loading process
-XX:+PrintGCDetails To PrintGC logs when garbage collection occurs, this parameter is automatically accompanied by -verbose:gc and -xx :+PrintGC
-XX:+PrintGCDateStamps / -XX:+PrintGCTimeStamps Prints the gc trigger event, which can be mixed with -xx :+PrintGC and -xx :+PrintGCDetails
-Xloggc: Gc Log Path
-XX:+HeapDumpOnOutOfMemoryError If OOM is displayed, the memory snapshot is dumped for post-analysis
-XX:HeapDumpPath= The file path of the heap dump snapshot

17. Do you understand distributed CAP?

Consistency Availability Partition tolerance

18. If the key of a Java HashMap is a class object, what conditions should the class meet?

You need to override both the class’s hashCode() method and its equals() method.

When a program tries to put a key-value pair into a HashMap, it first decides where to store the Entry based on the return value of the key’s hashCode() : If two Entry keys return the same hashCode() value, they are stored in the same location. If the keys of the two entries return true through equals comparison, the value of the new Entry overwrites the value of the original Entry in the collection, but the key does not. If the keys of the two entries return false through equals, the new Entry will form an Entry chain with the original Entry in the collection, And the new Entry is at the head of the Entry chain — see the addEntry() method for details.

19. Will non-recyclable objects appear in Java garbage collection? How to solve the memory leak problem? How to locate the problem source?

There are generally no uncollectible objects because today’s GC reclaims unreachable memory.

20. How many ways are there to terminate a thread? Why is the terminating thread marker variable of type Valotile?

1. The thread completes its normal execution and terminates normally. 2. Terminate a thread with the interrupt method

The Java keyword volatile is used to define exit. The purpose of this keyword is to synchronize exit, meaning that only one thread can modify the value of exit at a time

21. What concurrent data structures have been used? What does cyclicBarrier do? Semaphore action? How to solve database read/write block

  • The main locking mechanism is based on the CONCURRENT package of CAS.
  • CyclicBarrier literally means CyclicBarrier. What it does is allow a group of threads to block when they reach a barrier (also known as a synchronization point), and the barrier will not open until the last thread reaches the barrier, and all threads blocked by the barrier will continue to work. The CyclicBarrier’s default constructor is CyclicBarrier(int parties), whose argument is the number of threads that the barrier intercepts, and each thread calls the await method to tell the CyclicBarrier that I have reached the barrier and the current thread is blocked. CountDownLatch’s counter can only be used once. The CyclicBarrier counter can be reset using the reset() method.
  • **Semaphore is used to control the number of threads accessing a particular resource at the same time. It coordinates threads to ensure proper use of common resources. * * for many years, I find it difficult to understand from the literal meaning expressed by the Semaphore, can only compare it to is to control the flow of traffic lights, such as XX to limit of the road traffic, allowing only have one hundred vehicles on the road at the same time, the other must be waiting at an intersection, so before the one hundred car would see a green light, you can into the road, At the back of the car to see the red light, can’t enter XX road, but if five of the top one hundred car has left the XX road, then is allowed to have 5 car behind into the street, this example said the car was thread, said in the execution thread into the road, leaving the road said thread execution is completed, see the red light means that thread is blocked, can not perform.

22. The relationship between abstract classes and interfaces

In short, an abstract class is an incomplete class. An interface is simply a collection of abstract method declarations and statically unmodifiable data, neither of which can be instantiated. In a sense, interface is a special form of abstract class. In Java language, abstract class represents an inheritance relationship. A class can only inherit one abstract class, but a class can implement multiple interfaces. In many cases, interfaces can actually replace abstract classes if you don’t need to intentionally express inheritance on properties.

23. The difference between heap and stack memory

Register: JVM internal virtual register, access speed is very fast, the program can not control. Stack: store values of local variables including: 1. Store values of basic data types; 2. Save the reference variable, that is, the reference (pointer) to the heap object. It can also be used to save frames from loading methods. Heap: Used to store dynamically generated data, such as new objects. Note that the created objects contain only their own member variables, not member methods. Because objects of the same class have their own member variables, stored in their own heap, but they share the class’s methods, they are not copied every time an object is created. Constant pooling: The JVM maintains a constant pool for each loaded type, which is an ordered collection of constants used by that type. This includes direct constants (primitive types, strings) and symbolic references to other types, methods, and fields (1). The data in the pool is accessed by an index just like an array. Constant pools play a central role in Java dynamic linking because they contain all symbolic references to other types, methods, and fields of a type. Constant pools exist in the heap. Code snippet: Used to store source code read from the hard disk. Data segment: A static member used to hold static modifiers (in Java static is used to indicate whether the variable, method, or code block belongs to a class or an instance).

24. What about the inner classes of Java files? What is an anonymous inner class? How do I access variables defined outside of it?

Static inner classes cannot access non-static members of external classes ###25. The difference between overloading and overwriting is overload, which is a different concrete implementation of the same method name in a class. And override is override, which is a subclass that overrides a method in its parent class.

26. The difference between String, StringBuffer and StringBuilder

StringBuilder > StringBuffer > String

String: String constant StringBuffer: String variable StringBuilder: String variable

** A summary of the three uses: ** 1. If you want to manipulate a small amount of data use = String 2. Single thread operation String buffer to manipulate a large amount of data = StringBuilder 3. Multithreaded manipulation of large amounts of data in string buffers = StringBuffer

27. What are the similarities and differences between run-time exceptions and general exceptions? Common abnormal

Java provides two main types of exceptions: Runtime Exceptions and Checked Exceptions Common exceptions: NullPointerException, IndexOutOfBoundsException, ClassNotFoundException, IllegalArgumentException, ClassCastException ###28. What is the difference between error and exception? Error represents a serious problem in cases where recovery is not impossible but difficult. Let’s say memory runs out. It is impossible to expect the program to handle such a situation. Exception represents a design or implementation problem. That is, it represents a situation that would never happen if the program worked properly. ###29.Java exception handling mechanism

1. Catch exceptions: try, catch, and finally. 2. Throw exceptions

methodname throwsException1,Exception2,.. ,ExceptionN { }Copy the code

30. How many ways can you implement a thread in Java?

Java multithreading learning (vomiting blood super detailed summary) 40 Java multithreading problems summary


Class Thread2 implements Runnable{}; class Thread3 implements Runnable{}; class Thread3 implements Runnable{} Callable{}, then new FutureTask(thread3), then wrapped with new Thread(Future).

class Thread1 extends Thread {
    private String name;
    public Thread1(String name) {
        this.name = name;
    }
    @Override
    public void run(a) {
        for (int i = 0; i < 5; i++) {
            System.out.println(name + "Run - > > >"+ i); }}public static void main(String[] args) {
        Thread1 mTh11=new Thread1("A");
        Thread1 mTh12=new Thread1("B"); mTh1.start(); mTh2.start(); }}class Thread2 implements Runnable {
    private String name;
    private int count = 15;
    public Thread2(a) {}public Thread2(String name) {
        this.name = name;
    }
    public void run(a) {
        for (int i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread().getName() + "Run:"+ count--); }}public static void main(String[] args) {
        Thread2 mTh2 = new Thread2();
        new Thread(mTh2, "C").start();
        new Thread(mTh2, "D").start(); }}class MyCallableThread implements Callable<Integer>{
        public Integer call(a) throws Exception {
        int i = 0;
        for(; i<100; i++) { System.out.println(Thread.currentThread().getName()+""+i);
        }
        return i;
    }
    
    public static void main(String[] args) {
        MyCallableThread mct = new MyCallableThread();
        FutureTask<Integer> ft = new FutureTask<Integer>(mct);
        for(int i = 0; i <100; i++) { System.out.println(Thread.currentThread().getName()+"The value of the loop variable I of+i);
            if(i==20)
            {
                new Thread(ft,"Thread with return value").start(); }}try
        {
            System.out.println("Return value of child thread:"+ft.get());
        } catch (InterruptedException e)
        {
            e.printStackTrace();
        } catch(ExecutionException e) { e.printStackTrace(); }}}Copy the code

If a class inherits Thread, it is not suitable for resource sharing. However, if the Runable interface is implemented, it is easy to implement resource sharing.

Common Java classes, packages, interfaces.

class: ‘Date’,’System’,’Calender’,’Math’,’ArrayList’,’HashMap’ package: ‘java.lang’,’java.util’,’java.io’,’java.sql’,’java.net’ interface: ‘Collection’,’Map’,’List’,’Runnable’,’Callable’

32. Java handles thread synchronization in the following ways:

1. Synchronized keyword. 2. Lock Indicates locking. 3. Semaphore. CAS algorithm 5. Concurrent package

33. Spring IOC/AOP?

The concepts of IOC/DI and AOP are answered. AOP (aspect-orientedProgramming, aspect-oriented programming) can be said to be OOP (Object-oriented Programing, object-oriented programming) complement and perfect. OOP introduces concepts such as encapsulation, inheritance, and polymorphism to build an object hierarchy that simulates a collection of common behaviors. OOP is helpless when we need to introduce common behavior to discrete objects. That is, OOP allows you to define top-to-bottom relationships, but not left-to-right relationships. For example, the logging function. Logging code tends to be spread horizontally across all object hierarchies, regardless of the core functionality of the object to which it is spread. The same is true for other types of code, such as security, exception handling, and transparency persistence. This scattering of extraneous code is called cross-cutting code, and in OOP design it leads to a lot of code duplication, which is not conducive to reuse of modules. Dependency Injection and Inversion of Control are the same concept. When one role (perhaps a Java instance, caller) needs the assistance of another role (another Java instance, caller), in traditional programming, it is usually the caller who creates the instance of the caller. But in Spring, the job of creating the called is no longer done by the caller, so it is called inversion of control. The job of creating an instance of the called is usually done by the Spring container and then injecting the caller, hence the term dependency injection. Both dependency injection and inversion of control illustrate Spring’s dynamic and flexible approach to managing objects. The concrete implementations of objects are transparent to each other. Before we understand di, let’s look at how this problem can be solved in various societies: a person (Java instance, caller) needs an axe (Java instance, caller).

34. What about garbage collection for JVM?

The purpose of the garbage collector is to find and recycle (clean up) unwanted objects. To allow the JVM to use memory more efficiently.

35. The difference between a process and a thread, and the way it communicates

A program has at least one process, and a process has at least one thread. 2. Processes have separate memory units during execution, while multiple threads share memory 3. A thread is an entity of a process and is the basic unit of CPU scheduling and dispatch

  • Interprocess communication
1. Named Pipe 2. Signal 3. Message queue 4. Shared memory 5. Semaphore 6. SocketCopy the code

36. How does the JVM GC, Generation, generation, and persistent store what?

JVM GC algorithms are: reference counter algorithm, root search method

Newly generated objects are first placed in the young generation. The goal of the younger generation is to collect objects with short life spans as quickly as possible.

Objects that survive N garbage collections in the young generation are put into the old generation. Therefore, you can think of the tenured generation as holding objects with long life cycles.

The persistent generation mainly stores the class information of Java classes

37. What parts of the JVM are divided into, and what does each part do?

Q: Java runtime data areas? Answer: Includes program counters, JVM stacks, local method stacks, method areas, and heaps. Native method stack: Serves a similar role to the JVM stack, except that the JVM stack performs Java methods (bytecode) for the JVM, while the native method stack serves native methods used by the JVM. JVM stack: local variable table, operand stack, dynamic linking, method exit. Method area: used to store information about classes that have been loaded by the virtual machine, constants, static variables, code compiled by the just-in-time compiler, etc. Heap: Stores object instances.

38. In the reference reachability analysis algorithm used by GC, which objects can be used as GC Roots objects?

  • Objects referenced in the virtual machine stack (the local variable table in the stack frame);
  • The object referenced by the class static attribute in the method area;
  • The object referenced by the constant in the method area;
  • Objects referenced by JNI (commonly referred to as Native methods) in the Native method stack

39. What tools do YOU use to debug the program? Jmap, jStack,JConsole?

Virtual machine performance monitoring and tuning – blog

40. Have thread pools been used?

Thread Pool – Concurrent Programming Network – ifeve.com

Thread pools are useful for limiting the number of threads running at any one time in an application. There are performance costs associated with starting a new thread, each thread needs to allocate some memory to the stack, and so on.

Instead of starting a new thread for each concurrent task, we can pass concurrent tasks to a thread pool. As long as there are free threads in the pool, the task is assigned to one thread for execution. Inside the thread pool, tasks are inserted into a Blocking Queue, and threads in the pool fetch tasks from that Queue. When a new task is inserted into the queue, an idle thread successfully retrieves the task from the queue and executes it.

41. How does the operating system schedule pages? —To take an examination of LRU

First in, first out (FIFO). Third, the least recent use of the replacement algorithm -LRU 4. Clock replacement algorithm

// Extend the LinkedHashMap class to implement the LRU algorithm
class LRULinkedHashMap<K.V> extends LinkedHashMap<K.V>{
    // Define the cache capacity
    private int capacity;
    private static final long serialVersionUID = 1L;
    // Constructor with arguments
    LRULinkedHashMap(int capacity){
        // Call the constructor of LinkedHashMap, passing in the following parameters
        super(16.0.75 f.true);
        // Pass in the specified maximum cache capacity
        this.capacity=capacity;
    }
    // The key method to implement LRU is to delete the top element of the list if the number of elements in the map exceeds the maximum cache capacity
    @Override
    public boolean removeEldestEntry(Map.Entry<K, V> eldest){
        System.out.println(eldest.getKey() + "=" + eldest.getValue());
        returnsize()>capacity; }}Copy the code

42. Something about LinkedHashMap

Java8 LinkedHashMap working principle and implementation

LinkedHashMap is implemented through hash tables and linked lists. It maintains a linked list to ensure that the hash table is iterated in order, which is the order in which the key-value pairs are inserted.

The rough implementation of the LinkedHashMap is shown below. Of course, the same key-value pairs in the linked list and hash table refer to the same object, but they are drawn separately just to give a clearer structure.

LinkedHashMap is an implementation of Hash and linked lists, and relies on bidirectional linked lists to ensure that the order of iteration is the order of insertion.

Three functions that focus on implementation

The following definitions are mentioned in the HashMap:

// Callbacks to allow LinkedHashMap post-actions
//1. Move current node e to the end of the list. Because we use a bidirectional list, tail inserts can be done in order (1) time. And this operation will only be performed if accessOrder is set to true. This method is called in the putVal method of the HashMap.
void afterNodeAccess(Node<K,V> p) {}//2. AfterNodeInsertion method is called when a new node is inserted into the hash table. It removes the first node of the list by calling the removeNode method of the HashMap. AfterNodeInsertion method and afterNodeAccess method, can easily implement a least recently used (LRU) elimination strategy? Of course, we'll also override the removeEldestEntry method, which returns false by default.
void afterNodeInsertion(boolean evict) {}//3. This method is called when a HashMap deletes a key-value pair. It removes the key-value pair from the HashMap, ensuring consistency between the hash table and the linked list.
void afterNodeRemoval(Node<K,V> p) {}Copy the code

LinkedHashMap inherits from HashMap, so it reimplements the three functions that do something after a node is visited, after a node is inserted, and after a node is removed.

43. What is the relationship between thread synchronization and blocking? Does synchronization have to block? Does blocking have to be synchronized? What’s the difference between synchronous and asynchronous?

Synchronous and asynchronous: mainly in the case of mutually exclusive access to critical resources blocking and non-blocking: mainly in terms of CPU consumption

44. What is the difference between int and Integer

1. Integer is the wrapper class provided by int, and int is the basic data type of Java. 2. Integer defaults to null, and int defaults to 0. 3. Variables declared as Integer need to be instantiated, while variables declared as int need not be instantiated. 4. Integer is an object with a reference to it, and int is a primitive type that stores values directly.Copy the code

Int is the basic data type, Integer is the wrapper class, and structures like HashMap must use the wrapper class, because the wrapper class inherits from Object and needs to implement HashCode, so it can be used in data structures like HashMap.

45. Detailed procedure of RPC

The main focus of RPC is as follows: dynamic proxy, mainly the invoke reflection principle serialization, the use of Thrift efficient communication mode, the use of Netty NIO can improve the efficiency of service discovery, and the use of ZooKeeper can be achieved

  • 1) Service consumer (Client) invocation invokes the service in a local invocation mode;
  • 2) After receiving the call, the Client stub is responsible for assembling methods and parameters into a message body capable of network transmission;
  • 3) The client stub finds the service address and sends the message to the server.
  • 4) The Server Stub decodes the message after receiving it.
  • 5) The Server Stub invokes the local service according to the decoding result;
  • 6) The local service executes and returns the result to the server stub;
  • 7) The Server Stub packages the returned result into a message and sends it to the consumer;
  • 8) The Client stub receives the message and decodes it.
  • 9) The service consumer gets the final result.