preface

2020 is an extraordinary year, epidemic, tsunami, high school entrance examination postponement. For the Internet is also an extraordinary year, the volume, the size of the company’s capital chain fracture bankruptcy and so on. This year also has a special meaning for me. First, I stayed in my work city for half a month because of the epidemic. Then, due to the organizational structure adjustment of my old employer, the future development direction did not meet my expectations. Therefore, I decided to leave even though I had just over one year of working experience. After careful preparation and more than a month of intensive interviews, I got several offers from large and small companies. Finally, I chose Boiled water Tuan. The end of the year is the peak of job-hopping, so this series records the interview questions and answers of Ali, Bytedance, Kuaishou and other big factories, hoping to be helpful to everyone. I wish my friends all the best.

The interview began

MySQL > select * from ‘MySQL’;

Deadlock: in two or more concurrent processes, if each process have some kind of resource and are waiting for the other process to release it or the resources, they are now kept before did not change the state cannot move forward, says it produced a set of processes a deadlock Generally speaking, is that two or more processes are blocked indefinitely and wait for a condition

The necessary conditions for a deadlock to occur:

  • Mutualexclusion. A resource can only be used by one process at a time
  • A process cannot nopreemption resources it has acquired before they are used up
  • Hold andwait, when a process is blocked by requesting a resource and holds on to the resource it has acquired
  • Circularwait is a circular waiting resource relationship between several processes, which is connected end to end.
T1:
begin;
select * from user u where u.id=1 for update; 
update user u set u.name='Carson' where id=2;

T2:
begin;
delete from user u where u.id=2;
delete from user u where u.id=1;
Copy the code

Launched two transactions, such as the code above, when a transaction T1 for id = 1 and pessimistic locks, but the second statement has not been performed, the transaction T2 also opened up and remove the id = 2 rows of data, both T1 and T2 at this time to execute the next statement will find related id line has been held another transaction and each other is not released, when the deadlock.

What is the inverted index, MySQL inverted index implementation principle?

An inverted index is a technique to find any content information in an entire book or article stored in a database. To put it simply, if you have several documents and want to find out which documents the keyword appears in, you can think of only a full traversal without inverted index, which is obviously a very inefficient way to obtain the keyword. So there is an inverted index, which means to record which documents the keyword appears in, such as the following:

text documents
keyword 1, 6
code 2, 6

If you want to query a keyword, you can use the index to locate it in the corresponding document, and then directly return it to the business side. In fact, Google, Baidu and other search engines are realized through this technology. So how is MySQL implemented? There are two important concepts: Auxiliary Tables and FTS Index Cache. Secondary tables invert the location of the index key and the corresponding index document. Full-text index caching is mainly used to improve full-text index performance.

Handwriting: three threads add the same variable ten times, the main thread waits for three child threads to complete the sum, and prints 30.

(4) : The bytedance interviewer asked me to write code to start three threads adding up the number to 30

How does ThreadLocal work?

ThreadLocal is a ThreadLocal variable that can be read or written only by a thread and cannot be accessed by other threads. ThreadLocal is a generic class that is guaranteed to accept objects of any type.

Since multiple ThreadLocal objects can exist within a thread, the ThreadLocal maintains a Map that is not directly used as a HashMap, It is a static inner class of ThreadLocal’s implementation called ThreadLocalMap. The get() and set() methods we use actually call the corresponding get() and set() methods of ThreadLocalMap. For example, the following set method:

 	public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if(map ! =null)
            map.set(this, value);
        else
            createMap(t, value);
    }
Copy the code

When we call ThreadLocal’s set method, we first get the current thread, then get the ThreadLocalMap object maintained by the current thread, and finally add it to the ThreadLocalMap instance. If the ThreadLocalMap instance does not exist, it is initialized and assigned an initial value.

Here we see that the first argument to the set method is this, which refers to the current ThreadLocal object, and the code you’ll be looking at is the mLocal object. In ThreadLocalMap, the set method performs some operations and judgments based on the current ThreadLocal object instance, and finally implements the assignment operation (see source code for details). 2 Typical application: Saves sessions. 3 memory leak problem: The key used in ThreadLocalMap is a weak reference to ThreadLocal. Weak references can be cleaned up in the next garbage collection if there are only weak references to the object.

So if a ThreadLocal is not strongly referenced, it will be cleaned up during garbage collection, and so will any key in the ThreadLocalMap that uses this ThreadLocal. However, a value is a strong reference and will not be cleaned up, resulting in a value with a null key.

The ThreadLocalMap implementation already takes this into account by calling the set(), get(), and remove() methods to clean up records with a null key. If there is a memory leak, it is only if the remove() method is not called manually after a record with a null key is present, and the get(), set(), and remove() methods are never called again.

Where does the sessionId exist?

The sessionId is the key of a session. When the browser accesses the server for the first time, a session is generated on the server side and a sessionId corresponds to it. The session IDS generated by Tomcat are called jsessionids. Jetty sessionId. Sesssion content is stored in server memory and sessionids are stored in client cookies. Of course, you can persist it to a database, redis.

HTTPS encryption and decryption process?

HTTPS adds an SSL/TLS Layer (Secure Sockets Layer) for encryption and decryption between traditional HTTP and TCP. To use HTTPS, you must have your own digital certificate (including public and private keys). HTTPS encryption and decryption process:

  • The client requests the server to obtain theCertificate of public key
  • Client (SSL/TLS) parse certificate (invalid will pop up warning)
  • Generate random value
  • withPublic key encrypts random valueGenerate the key
  • The client sends the secret key to the server
  • The service side withPrivate key Decompress the private keyGet a random value
  • Mixing information with random valuesSymmetric encryption
  • Sends the encrypted content to the client
  • The client decrypts the information with a secret key

For details, you can refer to the following blog post: 👇 PRINCIPLES of HTTPS and principles of encryption and decryption

Nginx request process?

If you can talk about this question in detail for half an hour, in the interview to focus on the process of talking about it. Not hard, pure memory stuff, non-Nginx middleware development I’m sure not many people can speak clearly, step by step. Here I post the core process for your reference.

  • Read Request Headers: parses the Request Headers.
  • Identify Configuration Block: Identifies which location is used for processing and matches the URL.
  • Apply Rate Limits: Determines whether the Rate limit is limited. For example, the request may have too many concurrent connections to exceed the limit, or the QPS may be too high.
  • Perform Authentication: performs connection Authentication. For example, you might do some anti-theft Settings based on the Referrer header, or verify the user’s permissions.
  • Generate Content: Generates a response that is returned to the user. To generate this response, you may need to communicate with Upstream Services while doing the reverse proxy, and then there may be sub-requests or redirects that take you through Internal redirects and subrequests.
  • Response Filters: Filter the Response returned to the user. Such as compressing the response, or manipulating the image.
  • Log: records logs.

Can an infinite loop cause a crash?

This problem is not difficult in fact, the main test job seekers to the problem of thinking. You can refer to shaoxia’s answer at that time: it depends on the actual scene, if the loop will produce large objects or objects have been accumulated can not be recycled in time, then it will soon crash. If the infinite loop is idling, not executing complex logic and producing large objects, only the CPU will rise. Shaoxia has tested that the infinite loop is executed continuously for an hour, and the CPU usage is about 60%, but it will not crash.

What do redo logs and undo logs do?

Redo log:

  • Ensure the persistence of transactions.
  • In case there are dirty pages that have not been written to disk at the time of the failure, redo the mysql service according to the redo log to achieve transaction persistence.

Rollback log (undo log)

  • Holds a version of the data prior to the transaction, can be used for rollback, and can also provide multi-version concurrent control read (MVCC), also known as snapshot read.

For more information about MySQL transactions and logs, see 👇. For more information about MySQL transactions, see: binlog, redo log, undo log

What are the JVM reference types? Strong references, weak references, what are the application scenarios?

Strong references: In Java, we use strong references when we declare by default, such as:

A a = new A();
Copy the code

As long as strong references are used, the garbage collector will never reclaim the referenced object. Since the memory size is fixed, the JVM simply throws outofMemoryErrors when it runs out of memory because there is no way to reclaim free space. If you want to break the relationship between a strong reference and an object, you can explicitly assign it to NULL so that the JVM can do garbage collection at the appropriate time.

A a = null;
Copy the code

Soft references: Soft references are less powerful than strong references and represent objects that are not necessary but still useful. It looks like this: (1) When there is enough memory, soft reference objects are not recycled. (2) When the memory is insufficient, the system will reclaim the soft reference object. If there is still not enough memory after the soft reference object is reclaimed, an out-of-memory exception is thrown. Because of this nature of soft references, it is very suitable for implementing caching technologies such as web page caching, image caching, and so on. After JDK1.2, using Java. Lang. Ref. SoftReference class soft references. Weak references: Weak references are even weaker, and their main feature is that when the JVM starts garbage collection, objects associated with weak references are collected regardless of whether memory is sufficient.

After JDK1.2, using Java. Lang. Ref. WeakReference weak references. A classic example is ThreadLocal, see the problem with ThreadLocal above. Virtual references: Virtual references are the weakest type of reference relationship. If an object holds only virtual references, it can be reclaimed at any time as if there were no references at all. After JDK1.2, the PhantomReference class is used.

How to design a short link service, such as the short link of microblog.

The short link service is to convert ordinary web addresses into shorter web addresses. When we type t.cn/RlB2PdD in the browser

  1. DNS first resolves to obtain the IP address of T.cn
  2. When the DNS obtains an IP address (for example, 74.125.225.72), it sends an HTTP GET request to the address to query the short codeRlB2PdD.
  3. t.cn The server will pass the short codeRlB2PdDGets the corresponding long URL. The mapping between short codes and long urls is stored in MySQL.
  4. Requests are forwarded via HTTP 301 to the corresponding long URL m.helijia.com. Here is a small point of knowledge, why use 301 jump and not 302.

301 is a permanent redirect, 302 is a temporary redirect. Short addresses do not change once generated, so using 301 is HTTP semantic. At the same time, the server pressure will also be reduced. However, if 301 is used, we cannot count the number of clicks on the short address. And that number of clicks is a very interesting data source for big data analysis. There are many, many things that can be analyzed. So choosing 302 will increase server stress, but I think it is a better choice.

What algorithm is used to generate short codes?

  1. Self-increasing sequence algorithm is also called never repeat algorithm; 2. MD5 algorithm.

Handwriting: Post-order traversal of binary trees (non-recursive)

LeetCode 145, using a stack.

public List<Integer> postorderTraversal(TreeNode root) {
        LinkedList<Integer> ans = new LinkedList<>();
        Stack<TreeNode> stack = new Stack<>();
        if (root == null) return ans;

        stack.push(root);
        while(! stack.isEmpty()) { TreeNode cur = stack.pop(); ans.addFirst(cur.val);if(cur.left ! =null) {
                stack.push(cur.left);
            }
            if(cur.right ! =null) { stack.push(cur.right); }}return ans;
    }
Copy the code

Handwriting: integer square root, accurate to m decimal places.

Using dichotomy, the code is as follows.

    /** * take the square root of the positive integer n **@paramN Positive integer *@paramM Reserved decimal precision *@return* /
    public static double sqrt(int n, int m) {
        double lower = 0;
        double high = n;
        double mid = 0;
        double threshold = Math.pow(10, -m);
        do {
            mid = lower + (high - lower) / 2;
            if (mid * mid > n) {
                high = mid;
            } else{ lower = mid; }}while (Math.abs(mid * mid - n) > threshold);

        return new BigDecimal(mid).setScale(m, BigDecimal.ROUND_DOWN).doubleValue();
    }
Copy the code

conclusion

When I thought about changing jobs, I struggled and prepared for it. How can I say, the Internet is very difficult, technology can not be too old, but also can not be too old. Record dachang’s writing experience, not only their own follow-up learning materials, but also hope to help you looking for a job. The answers to the second interview are being sorted out. I wish you all an early landing.

I’m Luffy. I’ll see you next time.

A little attention, won’t get lost