Server-side development of Java prepares for the autumn recruitment interview 3

Continue to study today, first do two algorithm questions to practice your hands, continue to organize the stereotyped essays, and gain a deeper understanding, so that you can perform better in the interview. Let's work hard together. I hope that Qiuzhao will get more exciting offers. Go ahead.

Table of contents

1. Algorithm question: determine whether there is a ring in the linked list

2. Algorithm question: merge binary trees

3. What is a skip table?

4. What are the characteristics of Spring?

5. Mysql transaction features? mysql isolation level? How does mysql implement repeatable reading?

6. Tell me about B-tree, B+ tree, hash table, AVL tree, red-black tree?

7. How to ensure the thread safety of HashMap?

8. CAS(Compare And Swap) 、synchronized、volatile?

9. Can ThreadLocal guarantee resource synchronization? Will it cause a memory leak?

10. When is jvm garbage collection triggered?

11. What types of thread pools are there?

12. TCP three-way handshake and four waved hands?

13. Seven layers of OSI and four layers of TCP/IP? OSI five layers?

14. Algorithm question: Merge two ordered linked lists?

15. Algorithm question: reverse linked list


1. Algorithm question: determine whether there is a ring in the linked list

Topic link: Determine whether there is a ring in the linked list

To judge whether the linked list has a ring, you can use the fast and slow pointers. The fast pointer moves two steps at a time, and the slow pointer moves one step at a time. If the slow pointer is not empty and the fast and slow pointers can meet, the linked list has a ring, otherwise, the linked list has no ring.

Note: The handling of boundary values ​​prevents null pointer exceptions.

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public boolean hasCycle(ListNode head) {
        if(head == null || head.next == null){
            return false ;
        }
        ListNode fast = head;
        ListNode slow = head ;
        while(fast != null && fast.next != null){
            fast = fast.next.next ;
            slow = slow.next ;
            if(slow == fast){
                return true ;
            }
        }
        return false ;
    }
}

2. Algorithm question: merge binary trees

You can use the recursive method and the iterative method to merge, the recursive method is as follows, recursively merged into the tree t1.

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param t1 TreeNode类 
     * @param t2 TreeNode类 
     * @return TreeNode类
     */
    public TreeNode mergeTrees (TreeNode t1, TreeNode t2) {
        // write code here
        //合并到t1上
        if(t1 == null && t2 == null){
            return null ;
        }
        if(t1 == null){
            return t2 ;
        }
        if(t2 == null){
            return t1 ;
        }
        t1.val = t1.val + t2.val ;
        t1.left = mergeTrees(t1.left,t2.left) ;
        t1.right = mergeTrees(t1.right,t2.right) ;
        return t1 ;
    }
}

The iterative method is as follows:

Create a queue, and accumulate the corresponding node values ​​in the way of hierarchical traversal.

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param t1 TreeNode类 
     * @param t2 TreeNode类 
     * @return TreeNode类
     */
    public TreeNode mergeTrees (TreeNode t1, TreeNode t2) {
        // write code here
        //合并到t1上
      if(t1 == null && t2 == null){
        return null ;
      }
      if(t1 == null){
        return t2 ;
      }
      if(t2 == null){
        return t1 ;
      }
      Queue<TreeNode> queue = new LinkedList() ;
      queue.offer(t1) ;
      queue.offer(t2) ;
      while(!queue.isEmpty()){
        TreeNode node1 = queue.poll() ;
        TreeNode node2 = queue.poll() ;
        node1.val = node1.val + node2.val ;
        if(node1.left != null && node2.left != null){
            queue.offer(node1.left) ;
            queue.offer(node2.left) ;
        }
        if(node1.right != null && node2.right != null){
            queue.offer(node1.right) ;
            queue.offer(node2.right) ;
        }
        if(node1.left == null && node2.left != null){
            node1.left = node2.left ;
        }
        if(node1.right == null && node2.right != null){
            node1.right = node2.right ;
        }
      }
      return t1 ;
    }
}

3. What is a skip table?

1) Jump list, also known as jump list, jump list, adds the function of "jump" on the basis of ordered linked list.
2) The jump table adds a multi-level index to the original ordered linked list, and quickly searches through the index; it can support fast deletion, insertion and search operations.
3) The jump list is actually a linked list with forward pointers added, which is a randomized data structure.
4) SortedSet in Redis and MemTable in LevelDB both use jump tables.
5) Compared with the balanced tree, the implementation and maintenance of the skip table will be simpler, and the average time complexity of searching, deleting, and adding the skip table is O(logn).
Refer to this blog: Skip List (Skip List)_wink22's Blog-CSDN Blog_Skip List

4. What are the characteristics of Spring?

Three major features: Dependency Injection (DI), Inversion of Control (IOC), and Aspect-Oriented Programming (AOP).

You can refer to this blog: [Spring articles] The three major characteristics of Spring_I am not greedy blog-CSDN blog_spring features

5. Mysql transaction features? mysql isolation level? How does mysql implement repeatable reading?

ACID: Atomicity, Consistency, Isolation, Durability

Read Uncommitted, Read Committed, Repeatable Read, Serializable.

Repeatable reading is the default isolation level of Mysql, which means that the data read multiple times in the same transaction is consistent.

The implementation method is that Mysql uses multi-version concurrency control (MVCC): the MVCC we often say is implemented by the InnoDB storage engine of the MySQL database, not by MySQL itself. Different storage engines have different implementations for MVCC. It is in the InnoDB engine that InnoDB saves two hidden columns behind each row of records, which respectively save the creation time (version number) of the row and the deletion time (version number) of the row. What is stored here is not the actual time value, but the system version number. When the data is modified, the version number is incremented by 1. At the beginning of the read transaction, the system will give the current read transaction a version number, and then the transaction will read the data whose version number <= the current version number. At this time, if other write transactions modify this data (addition, deletion and modification), then the version number of this data will be increased by 1, which is higher than the version number of the current transaction. Therefore, the current transaction does not read the updated data. , but the data under the version corresponding to the current transaction.
Reference link: Implementation principle of mysql repeatable reading_Vance.'s blog-CSDN blog_Mysql implementation principle of repeatable reading

6. Tell me about B-tree, B+ tree, hash table, AVL tree, red-black tree?

These 2 articles introduce red-black trees, B-trees, and B+ trees, and they are okay: Why use red-black trees, B-trees, and B+ trees_-Parking Blog-CSDN Blog_Why use red-black trees for indexes

B tree, B+ tree, red black tree_prefect_start's blog-CSDN blog_b tree b+ tree red black tree

After reading this article, it is more comprehensive: interview questions

7. How to ensure the thread safety of HashMap?

Implemented through the ConcurrentHashMap thread safety class: JDK1.7 locks segments and fragments. JDK1.8 reduces the granularity of the lock, and ensures thread safety by locking the head node.

After reading the theory blog, it’s okay: How does ConcurrentHashMap ensure thread safety? _Tom Bomb Architecture Blog-CSDN Blog

8. CAS(Compare And Swap) 、synchronized、volatile?

1. Synchronized is a pessimistic lock, which is preemptive and will cause other threads to block.

2. volatile provides multi-thread shared variable visibility and prohibits instruction reordering optimization.

3. CAS is an optimistic lock (non-blocking) based on conflict detection.

Refer to this article, it is very well written: Basics: Detailed unlocking principle, synchronized, volatile+cas underlying implementation-Knowledge

9. Can ThreadLocal guarantee resource synchronization? Will it cause a memory leak?

  • When a variable is declared using ThreadLocal, ThreadLocal provides an independent copy of the variable for each thread that uses the variable, and each thread can independently change its own copy without affecting the corresponding copies of other threads
  • From the above concepts, we can see that ThreadLocal does not actually guarantee the synchronization of variables, but only assigns a variable copy to each thread.
  • hreadLocalMapThreadLocal Weak references   are used  Key , and weakly referenced objects will be recycled during GC. ThreadLocalMap uses the weak reference of ThreadLocal as the key. If a ThreadLocal does not have an external strong reference to refer to it, then the ThreadLocal will be recycled when the system is GC. In this way, an Entry with a key of null will appear in the ThreadLocalMap, and there will be no There is a way to access the value of these Entry whose key is null. If the current thread does not end for a long time, there will always be a strong reference chain for the value of these Entry whose key is null: Thread Ref -> Thread -> ThreadLocalMap -> Entry - > value can never be recycled, causing a memory leak.
  • Every time it is used ThreadLocal, its remove()method is called to clear the data and prevent memory leaks.

Refer to this blog post: ThreadLocal use attention: threads are not safe, memory leaks may occur_Deep Mountain Ape's Blog-CSDN Blog_What hidden dangers does threadlocal

10. When is jvm garbage collection triggered?

Refer to this blog post: jvm: When is garbage collection triggered? Garbage collection algorithm? What garbage collectors are there? _Flower Monk also has a spring blog-CSDN blog

11. What types of thread pools are there?

1. newCachedThreadPool: Create a cacheable thread pool. If the length of the thread pool exceeds the processing requirements, idle threads can be recycled flexibly. If the number of threads is not enough, new threads will be created.

2. newFixedThreadPool: Create a fixed-size thread pool, that is, threads with a specified number of threads. The number of concurrent threads can be controlled. If the number of worker threads reaches the initial maximum number of thread pools, the submitted tasks will be stored in the pool queue.

3. newSingleThreadExecutor: Create a single-threaded thread pool, that is, only create a unique worker thread to execute tasks, and ensure that all tasks are executed in the specified order (FIFO, LIFO, priority).

4. newScheduleThreadPool: Create a fixed-length thread pool that supports timing and periodic task execution.  

It is recommended to create a thread pool by  writing new ThreadPoolExecutor ()  , so that the number of writing threads is more flexible , and most of the development uses this class to create threads.

12. TCP three-way handshake and four waved hands?

The essence of TCP's three-way handshake and four-way wave is the connection and disconnection of TCP communication.

Three-way handshake: In order to track and negotiate the amount of data sent each time, ensure that the sending and receiving of data segments are synchronized, confirm data sending according to the amount of data received, when to cancel the connection after receiving, and establish a virtual connection.

Wave four times: Terminate the TCP connection, which means that when a TCP connection is disconnected, the client and the server need to send a total of 4 packets to confirm the disconnection of the connection.

Detailed description of the three-way handshake process:

1. The client sends a request message to establish a TCP connection, which contains a seq sequence number , which is randomly generated by the sender, and sets the SYN field in the message to 1 , indicating that a TCP connection needs to be established. (SYN=1, seq=x, x is a randomly generated value);

2. The server replies to the TCP connection request message sent by the client, which contains the seq sequence number, which is randomly generated by the reply end, and sets SYN to 1, and generates an ACK field. The value of the ACK field is sent by the client Add 1 to the previous serial number seq to reply, so that when the client receives the information, it knows that its TCP establishment request has been verified. (SYN=1, ACK=x+1, seq=y, y is a randomly generated value) The ack plus 1 here can be understood as confirming who to establish a connection with;

3. After receiving the TCP establishment verification request sent by the server, the client will add 1 to its serial number, and reply to the ACK verification request again, and add 1 to the seq sent by the server to reply. (SYN=1, ACK=y+1, seq=x+1).
 

Four waves​​​​​​The process is detailed:

1. The client sends a request message to disconnect the TCP connection, in which the message contains a seq sequence number, which is randomly generated by the sender, and also sets the FIN field in the message to 1, indicating that the TCP connection needs to be disconnected . (FIN=1, seq=x, x is randomly generated by the client);

2. The server will reply to the TCP disconnection request message sent by the client, which contains the seq sequence number, which is randomly generated by the replying end, and will generate an ACK field. The value of the ACK field is the seq sequence number sent by the client. Basically, add 1 to reply, so that when the client receives the information, it knows that its TCP disconnection request has been verified. (FIN=1, ACK=x+1, seq=y, y is randomly generated by the server);

3. After the server responds to the client's TCP disconnection request, it will not immediately disconnect the TCP connection. The server will first ensure that all the data transmitted to A has been transmitted before the disconnection. Once it is confirmed that the transmission of data is completed , the FIN field of the reply message will be set to 1, and a random seq sequence number will be generated. (FIN=1, ACK=x+1, seq=z, z is randomly generated by the server);

4. After the client receives the TCP disconnection request from the server, it will reply to the disconnection request from the server, including a randomly generated seq field and an ACK field. The ACK field will add 1 to the seq of the TCP disconnection request from the server, thus Complete the verification response requested by the server. (FIN=1, ACK=z+1, seq=h, h is randomly generated by the client)
At this point, the 4 waved process of TCP disconnection is completed.
Refer to this blog: One article to understand TCP's three-way handshake and four-way wave

Note: Can the TCP two-way handshake work?

Because the TCP protocol is bidirectional, the third handshake is to let the server know that the client has agreed to the connection request. The two handshakes can only confirm that the network from the client to the server is reachable, but cannot guarantee that the network from the server to the client is reachable. So we must ensure two-way reachability.

There is another important reason: the initialization of seq (serial number) needs to mutually determine the sequence number at which the two parties start sending each other, which is convenient for subsequent sending, control, error correction, etc.

If we use two handshakes, we can imagine such a situation: the client makes a request to the server, the server agrees and allocates resources, and sends information to the client, but at this time this information is lost due to network reasons, and the client does not understand the server. If the information sent by it is confiscated, the client will continue to send requests to the server. If the server receives it, it will think that it is another machine making the request and continue to allocate resources, and it is still impossible to establish a connection from the server to the client.
 

13. Seven layers of OSI and four layers of TCP/IP? OSI five layers?

You can get a general understanding by looking at the following figure, as follows: the application layer, presentation layer, and session layer can be classified as the application layer, and the data link layer and physical layer can be classified as the network interface layer.

Refer to this blog: OSI seven-layer and TCP/IP four-layer, five-layer protocol-everything goes with the wind

14. Algorithm question: Merge two ordered linked lists?

Idea 1: Iterative method, define a head node as 0, traverse and merge in turn, and finally remove the head node.

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode Merge(ListNode list1,ListNode list2) {
        //迭代法
        if(list1 == null){
            return list2 ;
        }
        if(list2 == null){
            return list1  ;
        }
        ListNode pHead = new ListNode(0) ;
        ListNode cur = pHead ;
        while(list1 != null && list2 != null){
            if(list1.val <= list2.val){
                cur.next = list1 ;
                list1 = list1.next ;
            }else{
                cur.next = list2 ;
                list2 = list2.next ;
            }
            cur = cur.next ;
        }
        //哪个链表还未结束,接在后面
        cur.next = list1 != null ? list1 : list2 ;
        //去掉头节点的0
        return pHead.next ;
        
    }
}

Idea 2: Recursive method. Merge recursively.

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode Merge(ListNode list1,ListNode list2) {
        //递归法
        if(list1 == null){
            return list2 ;
        }
        if(list2 == null){
            return list1  ;
        }
        //若list1的值更小,则递归合并后接到list1上
        if(list1.val <= list2.val){
            list1.next = Merge(list1.next,list2) ;
            return list1 ;
        }else{//反之,递归合并接到list2上
            list2.next = Merge(list1,list2.next) ;
            return list2 ;
        }
        
    }
}

15. Algorithm question: reverse linked list

Topic Link: Reverse Linked List_Niuke Topic_Niuke.com

Idea 1: When traversing the linked list, change the next pointer of the current node to point to the previous node . Since a node has no reference to its previous node, its previous node must be stored beforehand. The latter node also needs to be stored before changing the reference. Finally return the new header reference.

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode ReverseList(ListNode head) {
        ListNode pre = null ;
        while(head != null){
            //先定义下一个指针,防止被覆盖
            ListNode head_next = head.next ;
            //让当前元素指向pre
            head.next = pre ;
            //更新pre
            pre = head ;
            //更新当前元素
            head = head_next ;
        }
        return pre ;
    }
}

Recursive method: reverse two recursively each time, as follows:

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode ReverseList(ListNode head) {
      //递归法
      if(head == null || head.next == null){
        return head ;
      }
      ListNode ans = ReverseList(head.next) ;
      head.next.next = head ;
      head.next = null ;
      return ans ;

    }
}

Guess you like

Origin blog.csdn.net/nuist_NJUPT/article/details/129190234