[Java Campus Recruitment Interview] Practical Interview Experience (1)


Preface

"Practical Experience" is the second part of this column. This blog post is the first. If necessary, you can:

  1. Click here to return to the index articles of this column
  2. Click here to go to the next article "[Java Campus Recruitment Interview] Practical Interview Experience (2)"

1. Find three equal points in a singly linked list (the linked list may have rings)

	public class ListNode {
    
    
	    int val;
	    ListNode next;
	
	    ListNode(int x) {
    
    
	        val = x;
	        next = null;
	    }
	}
	
	public class Solution {
    
    
	    public ListNode findThreeEqualParts(ListNode head) {
    
    
	        if (head == null || head.next == null) {
    
    
	            return null;
	        }
	
	        // 快慢指针检查链表是否有环,将其转换为无环链表
	        ListNode slow = head;
	        ListNode fast = head;
	
	        while (fast != null && fast.next != null) {
    
    
	            slow = slow.next;
	            fast = fast.next.next;
	
	            if (slow == fast) {
    
    
	                // 得到相遇节点
	                fast = head;
	                while (fast.next != slow.next) {
    
    
	                    fast = fast.next;
	                    slow = slow.next;
	                }
	
	                // 断开环,将链表转换为无环链表
	                slow.next = null;
	                break;
	            }
	        }
	
	        // 使用快慢指针算法查找三等分点
	        // 上三等分点(三分之一)
	        ListNode oneThird = head;
	        // 下三等分点(三分之二)
	        ListNode twoThirds = head;
	        ListNode current = head;
	
	        int count = 0;
	        while (current != null) {
    
    
	            count++;
	            current = current.next;
	
	            if (count % 3 == 1) {
    
    
	                twoThirds = twoThirds.next;
	            } else if (count % 3 == 2) {
    
    
	                oneThird = oneThird.next;
	            }
	        }
	
	        // 如果链表元素不足以分成3部分相等长度,返回 null
	        if (count / 3 < 2) {
    
    
	            return null;
	        }
	        return oneThird.next;
	    }
	}

Code logic description:
  1. The code is divided into two parts. First, it is judged whether there is a ring in the singly linked list through the speed pointer. If there is a ring, it is separated. Then find the third point through another pair of fast and slow pointers.
  2. There may be a pitfall in the description of the trisection point. Ask the questioner which one he wants.


2. Let’s talk about some familiar design patterns

1. Singleton mode:
During the entire life cycle of the program, there is at most one instance of classA, and this instance is managed by classA itself. Spring's IoC uses singleton mode by default;

2. Proxy mode:
Provide a proxy for other objects to control access to this object. The proxy mode is used in Spring's AOP;

3. Factory method pattern:
Define the interface for creating objects and let subclasses decide which class to instantiate. The Factory Method pattern lets you defer instantiation of a class to its subclasses.


3. What are Spring IoC and AOP, how are they implemented, and what is Spring MVC?

1. IoC: That is Inversion of Control, inversion of control, which is to host the life cycle management of objects to achieve the purpose of code decoupling. The implementation methods of IoC include dependency monitoring (DL) and dependency injection (DI). Because dependency monitoring is intrusive to business code, it has been abandoned. IoC is now mainly implemented through dependency injection. Dependency injection is to establish dependencies when needed and inject the objects that the program depends on.

2. AOP: Aspect-oriented programming. It cannot replace OOP, but is a complement to it. AOP is suitable for scenarios with cross-cutting logic, such as performance monitoring, transaction management and logging. The implementation of AOP mainly relies on Java dynamic proxy, which is divided into two types: JDK dynamic proxy and CGLib dynamic proxy:

  1) JDK dynamic proxy: suitable for scenarios where business logic is implemented through interfaces;
  2) CGLib dynamic proxy: does not depend on interfaces. It can generate a subclass for the proxy class, then intercept all method calls of the parent class, and then weave Enter enhanced logic.

3. MVC means Model, Viewand Controller
  1) Controller: controls the entry of the Web program and the response to the request.
  2) Model: It is a data model. For example, our specific user object in a request is a model.
  3) View: It is the visual part of the web program, such as html pages, etc.


4. How to achieve thread safety? What are the differences between the various implementation methods? Is synchronized a reentrant lock?

1. Thread safety can be achieved using locking strategies and lock-free strategies . synchronizedKeywords and can be used for locking Lock, and implementation classes and version number mechanisms can be used for lock-free CAS.

2. Differences between various implementation methods

1) The difference and connection between synchronized and Lock:

  • synchronized does not require manual unlocking, while Lock requires manual unlocking;
  • Lock objects the lock and can monitor the status of the lock.
  • Lock can set the shackle waiting time, and give up the lock when it times out.
  • Lock can be set to a fair lock, while synchronized is an unfair lock.
  • Both synchronized and Lock are reentrant.

2) The implementation class of CAS includes Unsafe, which compares the old value and the current value of the object. If they are equal, it is considered that the object has not been changed by other threads and can be assigned a new value. Otherwise, try again.

3) The version number mechanism is suitable for databases. Each update sets a new version number for the corresponding row. When it is found that the version number has not changed, it is updated, which can avoid the ABA problem of CAS.


5. The underlying implementation of HashMap, how to achieve HashMap thread safety?

1. Red-black tree: In order to solve the problem of too long linked list, when the number of elements on the linked list is greater than 8, it will be converted into a red-black tree. The red-black tree is a self-balancing binary tree that achieves self-balancing through the rotation and color change of nodes.

2. Node array: After Java 8, HashMap uses a Node array internally as a hash table. Node has an attribute next, which is used to build a linked list. When it needs to be changed to a red-black tree, the Node will be replaced by its child. Subclass of class TreeNode.

3. During the put process, put will call putVal:
1) Determine whether the table has been created. If not, call the resize function to create the table with default settings. The default size is 16;

2) Determine whether there are nodes in the bucket corresponding to the key value currently being added:

  • If it is empty, create a new Node and put it in this bucket, otherwise:
    • If there is an ordinary Node in the bucket, create a new Node and add it to the last one in the linked list;
    • If the length of the linked list is greater than 8, call treeifyBinto convert the linked list into a red-black tree;
    • If the bucket is a TreeNode, call it putTreeValto insert the new key and value into the red-black tree;
  • During this period, if the key is found to be equal to the key in the bucket, the original Value will be overwritten with the new Value;

3) Finally, if the number of nodes is greater than the critical value, call the resize function to expand the table and double the length of the table;

4. The resize process:
  1) If the maximum capacity limit (2 to the 30th power) has been exceeded, the capacity will not be expanded, otherwise a new table will be created with twice the capacity of the old table;

  2) Traverse the old table and reposition each node on the new table. If the node is an ordinary Node with no successor, relocate it to hash & (newCap - 1); if it is a TreeNode, call the split function to rehash; if is the first node of a linked list, split the linked list and find the hash & oldCap of the node. If it is equal to 0, it will be added to the lo linked list, and if it is equal to 1, it will be added to the hi linked list.

  3) Finally, locate the lo linked list to its index in the old table, and the hi linked list at the index + oldCap position of the lo table;

5. Three views provided by HashMap:
  1) keySet(): a Set view containing all keys;
  2) values(): a Collection view containing all values;
  3) entrySet(): a Set view containing all entries.

6. Three methods of HashMap thread safety:
  1) Hashtable: Using object locks, the efficiency is relatively low;
  2) Collections.synchronizedMap(): Using object locks also, the efficiency is relatively low;
  3) ConcurrentHashMap: Using CAS + synchronized, the lock granularity is finer, and only Lock a bucket, so multiple threads can operate multiple buckets at the same time. When expanding, single-thread initialization and multi-thread replication are performed, so the efficiency is relatively high.


6. JVM memory management

JVM memory is divided into: virtual machine stack, local method stack, program counter, heap and method area
. The virtual machine stack, local method stack and program counter are thread-private, and the heap and method area are shared by threads.
Insert image description here

1. Program counter: used to record the line number of the bytecode currently executed by the thread;
2. Virtual machine stack: used to store the stack frame of method calls, and the stack frame stores the local variable table and operand stack dynamic link and method return address;
3. Local method stack: The local method stack is similar to the virtual machine stack and is used to execute Native methods;
4. Heap: The heap is used to store objects created through new;
5. Method area: used to store existing Class information, constants, and static variables loaded by the virtual machine. The constant pool is in the method area.


7. How to determine which objects need to be GC, GC methods, HotSpot GC algorithm and 7 types of garbage collectors.

1. Objects that are not referenced by other objects need to be GCed.

2. The algorithms for judging garbage include the reference counter method and the reachability analysis algorithm:
  1) Reference counter method: Each object has a counter, +1 when it is referenced, and -1 when the reference is completed (that is, setting the object = null). Objects with a counter of 0 can be recycled;

  2) Reachability analysis algorithm: Determine whether the object needs to be recycled by judging whether the reference chain of the object is reachable;

3. Garbage collection algorithm:
  1) Mark and clear algorithm: will cause memory fragmentation;

  2) Copy algorithm: Divide the memory into the object side and the free side. During each GC, the surviving objects are copied to the continuous space of the free side, the object side is cleared, and then the object side and the free side swap identities, which is suitable for low object survival rates. Scenes;

  3) Marking sorting algorithm: Move all surviving objects and make them continuous in the memory, clear other memories, suitable for scenarios with high object survival rate.

  4) Generational collection algorithm:
Insert image description here
    a) Young generation: divided into Eden area and Survivor area, and Survivor area is divided into From area and To area (the default ratio of the three is 8:1:1). Eden area is the place where objects are born. . Every time a GC occurs, copy the surviving objects in the Eden and From areas to the To area, then clean up the Eden and From areas, and swap the identities of the From and To areas.

    b) Old generation: used to store large objects (that is, objects that cannot be placed in the Eden or From area of ​​​​the young generation) or objects in the young generation that still survive after a certain number of GCs.

4. Conditions for triggering Minor GC and Full GC:
  1) Minor GC: when the Eden area is full;
  2) Full GC:
    a) System.gc() is called in the program, it is recommended that the system executes GC, but it may not be executed;
    b) There is insufficient space in the old generation;
    c) There is insufficient space in the method area.

5. Garbage collector:
  1) Young generation garbage collector (copy algorithm):
    a) Serial collector: single-threaded, the default young generation collector in Client mode;
    b) ParNew collector: multi-threaded collection;
    c) Parallel Scavenge collector: Multi-threaded collection, more concerned about system throughput than user thread pause time, the default young generation collector in Server mode.

  2) Old generation garbage collector:
    a) Serial Old collector: single thread, mark sorting algorithm, the default old generation collector in Client mode; b
    ) Parallel Old collector: multi-threaded, mark sorting algorithm;
    c) CMS collection Device: Mark-and-sweep algorithm.

6. CMS collector:
  1) Initial mark: Stop-The-World, the initial mark only marks the objects that GC Roots can directly associate with, it is very fast
  2) Concurrent mark: Concurrent traceability mark, the program will not pause
  3) Concurrent pre-cleaning: Find objects promoted from the young generation to the old generation during the concurrent marking phase
  4) Re-marking: Pause the virtual machine and scan the remaining objects in the CMS heap
  5) Concurrent cleaning: Clean up garbage objects, the program will not pause
  6) Concurrency Reset: Reset the data structure of the CMS collector
Insert image description here

Existing problems:
  1) Using a mark-and-clear algorithm without compressing the memory will cause space fragmentation.
  2) CPU resources are very sensitive. In the concurrency phase, although the user thread will not be paused, it will slow down the application and reduce the total throughput because some threads are occupied.
  3) The CMS collector cannot handle floating garbage and may fail with "Concurrent Mode Failure", causing Full GC to occur.
  4) Floating garbage: Since the user thread is still running during the concurrent cleanup phase of CMS, new garbage will naturally continue to be generated as the program runs. After the marking process of this part of garbage, CMS cannot process it in the current collection. , we have to leave it to be cleaned up in the next GC. These garbage are "floating garbage".

7. G1 Collector:
Insert image description here

  1) In the G1 algorithm, the heap memory is divided into multiple equal-sized memory blocks (Regions), and each Region is a logically continuous section of memory. Each Region is marked E, S, O and H, indicating that each Region plays a role at runtime. H is not found in previous algorithms. It represents Humongous, which means that these Regions store giant objects. (humongous object, H-obj), when the size of the new object exceeds half of the Region size, it is directly allocated in one or more new continuous Regions and marked as H.

  2) GC mode: G1 provides three modes of garbage collection mode, Young GC, Mixed GCand Full GC, which are triggered under different conditions.
    a) Young GC: A GC algorithm that occurs in the young generation. Generally, objects (except giant objects) allocate memory in the eden region. When all eden regions are exhausted and cannot apply for memory, a young gc will be triggered. This kind of The triggering mechanism is similar to the previous Young GC. After executing a Young GC, active objects will be copied to the survivor region or promoted to the old region, and the idle regions will be placed in the free list, waiting to be used next time.

    b) Mixed GC: When more and more objects are promoted to the old region, in order to avoid the heap memory being exhausted, the virtual machine triggers a mixed garbage collector, that is, Mixed GC. In addition to recycling the entire young region, it also To recycle a part of the old regions, you can choose which old regions to collect, so that you can control the time-consuming garbage collection.

    c) Full GC: If the object memory allocation speed is too fast, causing the old generation to be filled, a Full GC will be triggered. The Full GC algorithm of G1 is Serial Old executed by a single thread, which will cause an abnormally long pause time. Need Carry out continuous tuning and avoid Full GC as much as possible.

8. Relationship between collectors
Insert image description here


8. Class loading mechanism

There are Bootstrap ClassLoader, Ext ClassLoaderand App ClassLoader, where Bootstrap is the parent loader of Ext, and Ext is the parent loader of App.

1. Bootstrap ClassLoader: responsible for loading the core library of Java;
2. Ext ClassLoader: responsible for loading classes in the ext folder;
3. App ClassLoader: responsible for loading classes in the directory where the program is located;
4. Parental delegation mechanism: child loader judgment Check whether the class that currently needs to be loaded has been loaded. If not, call the parent loader to load it.
5. Why is the parent delegation mechanism safe: ClassLoader loads class files from many sources, and the class files from some sources are unreliable. For example, I can customize a java.lang.Integer class to override the default Integer class in jdk:

	package java.lang;
	 
	public class Integer {
    
    
	    public Integer(int value) {
    
    
	        ……
	    }
	}

This is very unsafe. If the parent delegation mechanism is used, this custom Integer class will not be loaded. Because BootStrapClassLoaderafter the delegation is loaded, the Integer class in the JDK will be loaded instead of the customized one, which ensures security.


9. The difference between threads and processes

1. A process is the smallest unit for system allocation of resources, and a thread is the smallest unit for CPU scheduling.
2. A process contains one or more threads, and a thread must belong to a certain process.
3. The cost of process switching is greater than that of threads.
4. In terms of concurrency, multi-process is more robust than multi-thread. In multi-threading, once an exception occurs in one thread, the entire process and all its threads will die. However, in multi-processing, the death of one process will not affect other processes.


10. Does HTTP have state? How to understand the statelessness of HTTP and how to solve the statelessness of HTTP?

1. HTTP is stateless.

2. Stateless means that the protocol has no memory ability for transaction processing, and the server does not know the state of the client. That is, after the server responds to the request, no information will be recorded.

3. To solve the statelessness of HTTP is to perform session tracking:
  1) URL rewriting: put the status information in the URL;
  2) Hidden form fields: set a hidden form in the page to record the status information;
  3) Session: use Session Store status information on the server;
  4) Cookie: Use Cookie to store status information on the client.


11. Java IO, NIO and asynchronous IO

1. Java IO: It is stream-oriented synchronous blocking IO. When the user thread sends a request, the user thread will be blocked. A typical example is the read method in the InputStream class, which has an infinite loop until the reading is completed.

2. Java NIO: It is buffer-oriented synchronous non-blocking IO. You can register the channel that needs to be monitored to the Selector in a thread. After the registration is completed, once the channel is in a ready state, the Selector can monitor it. The Selector can continuously poll the channel to check the status of the channel.

3. Comparison:
  1) For multiple clients, IO needs to create multiple threads and keep them in a blocked state, which will cause serious waste of resources. NIO only needs to create one thread;
  2) Thread switching efficiency is low. When there are many threads, frequent thread switching is required, and the performance of the application will drop sharply;
  3) At the same time, data reading and writing in IO is in bytes. Not as efficient as blocks of buffer in NIO.

4. Java asynchronous IO: Java implements asynchronous IO, and the implementation classes of these asynchronous IO are some subclasses of the Channel class. After the thread initiates IO, it can continue to execute the following program, and then notify the main thread through the callback function when the IO is completed. My understanding of asynchronous IO is that when we need to jump to the product page of the mall, we use asynchronous IO to jump to the page first and then wait for the images to be loaded one by one.


12. What is AJAX and its implementation principle?

AJAX is asynchronous JavaScript and XML, which allows web pages to be updated asynchronously by exchanging a small amount of data with the server in the background. Can refer to updating parts of a web page without reloading the entire page. AJAX performs asynchronous queries through the XMLHttpRequest object, which runs on the client side, reducing server workload.


13. Design a thread pool

It is divided into the following modules to design:

1. Thread creation module: When the number of threads is lower than corePoolSize, when a task is received, a thread is created to execute it; if it reaches corePoolSize, it is placed in the waiting queue. If the waiting queue is also full and the number of single threads has not reached maxPoolSize, threads will be created to execute tasks that cannot be placed in the waiting queue. If the number of threads reaches maxPoolSize, you need to use a handler to handle these tasks.

2. Waiting queue: As mentioned earlier, it is used to store tasks that are not assigned threads and are waiting to be executed.

3. Handler: As mentioned earlier, the processing strategy is used when the number of threads has reached maxPoolSize and there are no idle threads to perform these tasks. ThreadPoolExecutor has several strategies : throwing exceptions, directly letting the calling thread execute, directly abandoning, and abandoning older tasks .


14. MySQL optimization and index implementation

1. MySQL optimization:
  1) Database engine: If it is a pure retrieval system, choose MyISAM, because MyISAM does not support transactions and uses non-clustered indexes; otherwise, you should use one that supports transactions, row-level locks and clustered indexes. InnoDB.

  2) In terms of query optimization: try to make the query go through the index and avoid full table scan. You can use the EXPLAIN keyword and slow query logs to analyze the reason why the query statement is slow, and then perform corresponding optimization.

2. Index implementation: The index in MySQL is implemented using B+ tree.
Insert image description here

3. Conclusion: B+ tree is more suitable for storage index
  1) B+ tree has lower disk read and write costs, reads more index information at one time, and reduces IO times;
  2) B+ tree has more stable query efficiency, and all The search length of keyword values ​​is basically the same;
  3) B+ tree is more conducive to database scanning.


15. Transaction isolation level

isolation level dirty read non-repeatable read phantom reading Category 1 lost updates Category 2 lost updates
READ_UNCOMMITED allow allow allow not allowed allow
READ_COMMITED not allowed allow allow not allowed allow
REPEATABLE_READ not allowed not allowed allow not allowed not allowed
SERIALIZABLE not allowed not allowed not allowed not allowed not allowed

1. Dirty read: Thread A reads the uncommitted data of thread B, and then thread B rolls back.
2. Non-repeatable read: Thread A reads the data modified by thread B, resulting in different data read twice.
3. Phantom reading: Thread A reads newly inserted data by thread B, resulting in different data read twice.

MySQL's default transaction isolation level isREPEATABLE READ


16. Hibernate and MyBatis

They are all persistence layer frameworks. I mainly use Hibernate, which can automatically map relational entities and generate SQL statements. Mybatis is a semi-automated framework that requires manual writing of SQL statements.


17. Git

Git is a version control system, and Github is implemented based on Git. Commonly used commands on GitHub include:

  1. clone
  2. pull
  3. push
  4. commit
  5. merge

18. Common Linux commands

1. vim: editing tool
2. cat: view file content
3. grep: global regular expression search tool
4. find: search tool
5. |: pipe operator, the output of the previous command is used as the input of the following command


19. If a table is particularly large, how to optimize it?

Partitioned tables can be created, and MySQL supports the following types of partitioned tables:
1. RANGE partitioning: row data is partitioned based on a given continuous range.

2. LIST partition: Same as RANGE, the difference is that the given is not a continuous range, but a discrete value.

3. HASH partitioning: Partitioning is performed based on the return value of the user-defined expression. The return value cannot be a negative number.

4. KEY partitioning: Partitioning based on the hash function provided internally by MySQL.

5. COLUMNS partitioning: Non-shaped data can be used directly for partitioning. The partitions are obtained by direct comparison according to the type, and there is no need to convert to shaping.


postscript

In this interview, the interviewer asked a total of 20 questions including self-introduction, which was a lot in the actual interview. However, knowledge basically cannot be separated from the category of "eight-legged writing" .

When answering questions, we can expand the answer to the question based on the knowledge we know as much as possible until the interviewer interrupts you. This can help the interviewer understand how deeply you understand a knowledge point.

Guess you like

Origin blog.csdn.net/Mr_Megamind/article/details/130689133