Alibaba: 2021 spring recruits intermediate and advanced java interview questions, 50 detailed explanations, just right

Alibaba: Autumn recruits intermediate and advanced java interview questions, 50 detailed explanations, just right

 

Recently, many children's shoes have asked me about my interview questions. Today, I have compiled some common questions in programmer interviews for everyone. I hope it will be helpful to children's shoes! [There is a complete interview question collection method at the end of the article]

Question 1 : What is the use of multithreading?

A question that may seem nonsense to many people: I will use multi-threading. What's the use of it? In my opinion, this answer is even more nonsense. The so-called "knowing what is and knowing why", "being able to use" is just "knowing what is going on", "why use" is "knowing what is going on", and only when it reaches the level of "knowing what is going on, knowing what is going on" can it be said to be A knowledge point can be used freely. OK, let me talk about my views on this issue:

(1) Give full play to the advantages of multi-core CPU

With the advancement of industry, current notebooks, desktops and even commercial application servers are at least dual-core, and 4-core, 8-core or even 16-core are not uncommon. If it is a single-threaded program, then on a dual-core CPU 50% was wasted, and 75% was wasted on a 4-core CPU. The so-called "multithreading" on a single-core CPU is fake multithreading. The processor can only process a piece of logic at the same time, but the threads switch faster, and it looks like multiple threads are running "simultaneously". Multi-threading on a multi-core CPU is the real multi-threading. It allows your multi-segment logic to work at the same time. Multi-threading can truly take advantage of the multi-core CPU and achieve the purpose of making full use of the CPU.

(2) Prevent blocking

From the perspective of program efficiency, a single-core CPU not only does not give play to the advantages of multi-threading, but it will switch the thread context due to multi-threading running on a single-core CPU, which will reduce the overall efficiency of the program. But for single-core CPUs, we still have to apply multi-threading, just to prevent blocking. Imagine that if a single-core CPU uses a single thread, then as long as the thread is blocked, for example, reading a certain data remotely, the peer has not returned and the timeout period has not been set, then your entire program will be before the data is returned. Stopped running. Multi-threading can prevent this problem. Multiple threads are running at the same time. Even if the code execution of one thread is blocked for reading data, it will not affect the execution of other tasks.

(3) Easy to model

This is another advantage that is not so obvious. Suppose there is a big task A, single-threaded programming, then there are a lot of considerations, and it is troublesome to build the entire program model. But if you decompose this large task A into several small tasks, task B, task C, and task D, build the program model separately, and run these tasks separately through multi-threading, it will be much simpler.

Question 2 : How to get the thread dump file in Java

For problems such as infinite loops, deadlocks, blocking, slow page opening, etc., hitting thread dump is the best way to solve the problem. The so-called thread dump is the thread stack. There are two steps to obtain the thread stack:

(1) To obtain the pid of the thread, you can use the jps command, or in the Linux environment, you can use ps -ef | grep java

(2) To print the thread stack, you can use the jstack pid command, and you can also use kill -3 pid in the Linux environment

In addition, the Thread class provides a getStackTrace() method that can also be used to obtain the thread stack. This is an instance method, so this method is bound to a specific thread instance, and each time you get the stack that a specific thread is currently running,

Question 3 : What is the role of the producer consumer model

This question is very theoretical, but very important:

(1) Improve the operating efficiency of the entire system by balancing the production capacity of the producer and the consumption capacity of the consumer . This is the most important function of the producer-consumer model

(2) Decoupling , which is an incidental effect of the producer-consumer model. Decoupling means that there are fewer connections between producers and consumers. The fewer connections, the more they can develop independently without receiving mutual constraints.

Question 4 : short s1=1; s1=s1+1; what’s wrong? short s1=1; s1+=1; what’s wrong?

Analysis:

Interview questions are very abnormal, so be prepared for abuse.

s1=s1+1 will cause an error, s1+1 is an int type, and int cannot be assigned to s1. Need to display the conversion, s1=(int)(s1+1), and s1+=1 will not go wrong. As for the reason, some people say that it is related to the mechanism of the compiler. You need to look at the principle of compilation. The principle of compilation is the most annoying. How about this.

Alibaba: Autumn recruits intermediate and advanced java interview questions, 50 detailed explanations, just right

 

Question 5 : How to detect whether a thread holds an object monitor

I also saw a multi-threaded interview question on the Internet to know that there is a way to determine whether a thread holds an object monitor: Thread class provides a holdsLock (Object obj) method, if and only if the monitor of the object obj is Only when a thread holds it will return true. Note that this is a static method, which means "a thread" refers to the current thread.

Question 6 : Give me one of the runtime exceptions you see most frequently.

Analysis :

This question is also very common. If you can't answer it, the interviewer will think you have no programming experience.

NullPointerException, null reference exception. To be honest, ChinaSoft’s written test questions have this. Many people even misunderstood the meaning of the question. They did not recognize that runtime exception refers to runtime exception.

Question 7 : The difference between synchronized and ReentrantLock

Synchronized is the same keyword as if, else, for, while, and ReentrantLock is a class, which is the essential difference between the two. Since ReentrantLock is a class, it provides more and more flexible features than synchronized. It can be inherited, can have methods, and can have a variety of class variables. ReentrantLock is more extensible than synchronized in several aspects:

(1) ReentrantLock can set the waiting time to acquire the lock, so as to avoid deadlock

(2) ReentrantLock can obtain information about various locks

(3) ReentrantLock can flexibly implement multiple notifications

Question 8 : The role of the volatile keyword

A very important issue is that every Java programmer who learns and applies multithreading must master it. The prerequisite for understanding the role of the volatile keyword is to understand the Java memory model. The Java memory model is not discussed here. You can refer to point 31. The volatile keyword has two main functions:

(1) Multithreading is mainly developed around the two characteristics of visibility and atomicity. The variable modified by the volatile keyword ensures its visibility between multiple threads, that is, every time a volatile variable is read, it must be the latest The data

(2) The underlying code execution is not as simple as the high-level language we have seen—Java program. Its execution is Java code—>bytecode—>execute the corresponding C/C++ code according to the bytecode—>C/C++ The code is compiled into assembly language -> interact with the hardware circuit. In reality, in order to obtain better performance, the JVM may reorder the instructions, and some unexpected problems may occur under multi-threading. Using volatile will reorder the prohibited semantics, of course, this also reduces the code execution efficiency to a certain extent

From a practical point of view, an important role of volatile is to combine with CAS to ensure atomicity. For details, see the classes under the java.util.concurrent.atomic package, such as AtomicInteger.

Question 9: What are optimistic locking and pessimistic locking

(1) Optimistic lock: Just like its name, it is optimistic about the thread safety issues caused by concurrent operations. Optimistic lock believes that competition does not always occur, so it does not need to hold the lock. It will compare-replace the two This action is used as an atomic operation to try to modify the variables in the memory. If it fails, it means that there is a conflict, so there should be corresponding retry logic.

(2) Pessimistic lock: still like its name, it is pessimistic about thread safety issues caused by concurrent operations. Pessimistic lock believes that competition will always occur, so every time a resource is operated, it will hold an exclusive The lock is just like synchronized, no matter if it is three or seven twenty-one, you can operate the resource directly when you lock it.

Question ten : Java programming to write a program that will cause deadlock

The first time I saw this topic, I thought it was a very good question. Many people know what a deadlock is: Thread A and Thread B wait for each other's locks, causing the program to loop indefinitely. Of course, it is limited to this. I don’t know how to write a deadlock program. In this case, I don’t understand what a deadlock is. If I understand a theory, it’s over. I encountered a deadlock problem in practice. Basically it is invisible.

To truly understand what a deadlock is, this problem is not difficult, just a few steps:

(1) The two threads hold two Object objects: lock1 and lock2. These two locks are used as locks for synchronization code blocks;

(2) The synchronization code block in the run() method of thread 1 first acquires the object lock of lock1, Thread.sleep(xxx), it does not take much time, 50 milliseconds is almost the same, and then acquires the object lock of lock2. The main purpose of this is to prevent thread 1 from acquiring the object locks of lock1 and lock2 objects at once.

(3) Thread 2 run) (The synchronization code block in the method first obtains the object lock of lock2, and then obtains the object lock of lock1. Of course, the object lock of lock1 has been held by the lock of thread 1, and thread 2 must be waiting for the thread. 1 Release the object lock of lock1

In this way, thread 1 "sleeps" after sleeping, thread 2 has acquired the object lock of lock2, and thread 1 tries to acquire the object lock of lock2 at this time, and it is blocked. At this time, a deadlock is formed. The code is not written, it takes up a lot of space. Java Multithreading 7: Deadlock This article contains the code implementation of the above steps.

Alibaba: Autumn recruits intermediate and advanced java interview questions, 50 detailed explanations, just right

 

Question 11 : What happens if the thread pool queue is full when you submit a task

If you use LinkedBlockingQueue, which is an unbounded queue, it does not matter. Continue to add tasks to the blocking queue to wait for execution, because LinkedBlockingQueue can be regarded as an infinite queue, which can store tasks indefinitely; if you use a bounded queue, for example In the case of ArrayBlockingQueue, the task will be added to the ArrayBlockingQueue first. When the ArrayBlockingQueue is full, the rejection policy RejectedExecutionHandler will be used to process the full tasks. The default is AbortPolicy.

Question 12 : The difference between hashmap and hashtable.

Analysis:

This one has encountered more.

Alibaba: Autumn recruits intermediate and advanced java interview questions, 50 detailed explanations, just right

 

Question 13 : What is spin

Many codes in synchronized are just simple codes, and the execution time is very fast. At this time, all the waiting threads are locked. It may be a not worthwhile operation, because thread blocking involves the problem of switching between user mode and kernel mode. Since the code in synchronized executes very fast, let the thread waiting for the lock not be blocked, but do a busy loop on the boundary of synchronized, which is spin. If you do multiple busy loops and find that the lock has not been obtained, block again. This may be a better strategy.

Question 14: What is the Java memory model

The Java memory model defines a specification for multi-threaded access to Java memory. The complete description of the Java memory model is not something that can be said clearly in these few sentences. Let me briefly summarize several parts of the Java memory model:

(1) Java memory model divides memory into main memory and working memory. The state of the class, that is, the variables shared between classes, is stored in the main memory. Each time a Java thread uses these variables in the main memory, it will read the variables in the main memory once and let these memories exist. There is a copy in your working memory. When you run your own thread code, you use these variables and operate on the copy in your working memory. After the thread code is executed, the latest value will be updated to the main memory

(2) Several atomic operations are defined to manipulate variables in main memory and working memory

(3) Define the rules for the use of volatile variables

(4) happens-before, that is, the principle of first occurrence, which defines some rules that operation A must occur before operation B. For example, in the same thread, the code before the control flow must occur before the code after the control flow, and a release lock The unlock action must happen before the lock lock action for the same lock, etc. As long as these rules are met, no additional synchronization measures are required. If a piece of code does not meet all happens-before rules, this piece of code Must be thread-unsafe

Question 15 : After a thread enters a synchronized method of an object, can other threads enter other methods of this object?

Analysis:

Alibaba: Autumn recruits intermediate and advanced java interview questions, 50 detailed explanations, just right

 

Alibaba: Autumn recruits intermediate and advanced java interview questions, 50 detailed explanations, just right

 

Question 16 : There is a return statement in try{}, then the code in finally{} immediately after the try will be executed, when will it be executed, before or after return?

Analysis :

It is executed before return, as evidenced by the program:

Alibaba: Autumn recruits intermediate and advanced java interview questions, 50 detailed explanations, just right

 

The result is:

retrun

finally

return 1

Question 17 : Thread safety of singleton mode

It's an old-fashioned question. The first thing to say is that the thread safety of the singleton mode means that an instance of a certain class will only be created once in a multi-threaded environment. There are many ways to write singleton mode, let me summarize:

(1) The writing of the hungry Chinese singleton pattern: thread safety

(2) The writing method of the lazy singleton mode: non-thread-safe

(3) The wording of the double check lock singleton mode: thread safety

Question 18 : There is clearly only one statement "return count" in the size() method of Hashtable, why do we need to synchronize?

This is my previous confusion, I don’t know if you have thought about this issue. If there are multiple statements in a method, and they are all operating on the same class variable, then no locking in a multithreaded environment will inevitably lead to thread safety issues. This is easy to understand, but the size() method clearly has only one statement , Why do we need to lock it?

There are two main reasons for understanding this issue through working and studying slowly:

(1) At the same time, only one thread can execute the synchronized method of a fixed class, but for the non-synchronized method of the class, multiple threads can access it at the same time. Therefore, there is a problem. Maybe thread A is executing the put method of Hashtable to add data, and thread B can normally call the size() method to read the number of current elements in the Hashtable, and the value read may not be the latest Thread A may have finished adding data, but thread B has already read the size without matching size++, so the size read by thread B must be inaccurate. After adding synchronization to the size() method, it means that the thread B calls the size() method only after the thread A calls the put method, which ensures thread safety.

(2) The CPU executes code, but it is not Java code. This is very important and must be remembered. Java code is finally translated into assembly code for execution, and assembly code is the code that can really interact with hardware circuits. Even if you see that there is only one line of Java code, or even if you see that the bytecode generated after the Java code is compiled is only one line, it does not mean that for the bottom layer, there is only one operation of this sentence. One sentence of "return count" is assumed to be translated into three assembly sentences and executed. It is entirely possible that after the first sentence is executed, the thread is switched.

Question 19 : Can swtich act on byte, long, and string?

Analysis:

The expression in the switch statement can only be of integer type, that is, it must be int, char or enumerated type data. It cannot be boolean or floating point, or even other types of integer data (byte, short and long).

Question 20 : How do businesses with high concurrency and short task execution time use thread pools? How do businesses with low concurrency and long task execution time use thread pools? How do businesses with high concurrency and long business execution time use thread pools?

This is a question I saw on the concurrent programming website. I put this question on the last one. I hope everyone can see and think about it, because this question is very good, very practical, and very professional. Regarding this issue, my personal opinion is:

(1) For services with high concurrency and short task execution time, the number of threads in the thread pool can be set to the number of CPU cores + 1, reducing thread context switching

(2) Businesses with low concurrency and long task execution time should be distinguished:

  • If the business time is long concentrated on IO operations, that is, IO-intensive tasks, because IO operations do not take up the CPU, so do not let all the CPU idle, you can increase the number of threads in the thread pool to make the CPU processing more More business
  • If the business time is long and concentrated on computing operations, that is, computationally intensive tasks, this is no way. Same as (1), set the number of threads in the thread pool to be less, reducing thread context switching

(3) High concurrency and long business execution time. The key to solving this type of task is not the thread pool but the overall architecture design. Seeing whether certain data in these businesses can be cached is the first step, and adding servers is the first step. The second step, as for the setting of the thread pool, please refer to (2) for setting. Finally, the problem of long business execution time may also need to be analyzed to see if middleware can be used to split and decouple tasks.

Reader benefits:

Due to space reasons, I cannot list all the problems. I have organized these problems into documents and transferred them to the network disk. Friends in need only need to [ see the picture below to add a small assistant ] to receive them for free ! ! !

Alibaba: Autumn recruits intermediate and advanced java interview questions, 50 detailed explanations, just right

 

Alibaba: Autumn recruits intermediate and advanced java interview questions, 50 detailed explanations, just right

 

Alibaba: Autumn recruits intermediate and advanced java interview questions, 50 detailed explanations, just right

 

Alibaba: Autumn recruits intermediate and advanced java interview questions, 50 detailed explanations, just right

 

Guess you like

Origin blog.csdn.net/m0_50180963/article/details/114174903