2021 [Alibaba] Interview Questions

Article directory

1. What is the difference between TCP and UDP?

  • TCP is connection based and UDP is connectionless based.
  • TCP requires more system resources, UDP requires less.
  • UDP program structure is relatively simple.
  • TCP guarantees data correctness, and UDP may lose packets.
  • TCP guarantees data order, UDP does not.

2. Which layers of architecture does the TCP/IP protocol involve?

  • application layer
  • transport layer
  • Internetwork layer
  • network interface layer.

3. Describe the process of waving four times in a TCP connection? Why 4 waves?

Because TCP is full-duplex, each direction must be closed separately. When closing the connection, when the server receives the FIN
message, it may not close the SOCKET immediately, so it can only reply an ACK message first, telling the client
, "I have received the FIN message you sent".
I can only send the FIN message after all the messages on the server end have been sent , so they cannot be sent together. Therefore, a four-step handshake is required.

4. What does the operating system do when the computer is plugged in?

  • Power On –––– Turn on the power switch to power the motherboard and internal fans.
  • Start Bootloader ––––– The CPU begins executing instructions stored in the ROM BIOS.
  • POST – The computer performs diagnostic tests on the major components of the system.
  • Loading the Operating System – The computer reads the operating system files from the disk into memory.
  • Check the configuration file, customize the operating environment of the operating system – read the configuration file, and
    customize the operating system according to the user’s settings.
  • Ready to Read Commands and Data – The computer waits for the user to enter commands and data.

5. What are the Linux operating system device files?

Character device, block device.

6. What are the methods of multi-thread synchronization?

  • Use the synchronized keyword
  • wait and notify
  • Use special domain variable volatile to achieve thread synchronization
  • Thread synchronization using reentrant locks
  • Use local variables to achieve thread synchronization
  • Thread synchronization using blocking queues
  • Thread synchronization using atomic variables

7. Two methods of an object are synchronized, one thread enters sleep, and the other thread enters another method?

cannot.

8. What is a reentrant lock (ReentrantLock)?

Example to illustrate lock reentrancy

public class UnReentrant{
    
    
	Lock lock = new Lock();
	public void outer(){
    
    
		lock.lock();
		inner();
		lock.unlock();
	}
	public void inner(){
    
    
		lock.lock();
		//do something
		lock.unlock();
	}
}

The inner is called in the outer, and the outer locks the lock first, so that the inner can no longer acquire the lock. In fact, the thread calling
outer has already acquired the lock, but it cannot reuse the acquired lock resources in the inner. This kind of
lock is called non-reentrant. Reentrant means: the thread can enter any one it already owns. The block of code synchronized by the lock
.
Both synchronized and ReentrantLock are reentrant locks, which relatively simplifies the development of concurrent programming.

9. What are the three methods of creating threads?

  • Create a thread class by inheriting from the Thread class.
  • Implement the Runnable interface to create thread classes.
  • Threads are created through the Callable and Future interfaces.

10. How does Java get the return value of multithreading?

  • The main thread waits.
  • Use Thread's join to block the current thread to wait.
  • Implement the Callable interface (via FutureTask or Thread Pool's Future).

11. What are the ways to create a thread pool?

Java provides four thread pools through Executors (jdk1.5 concurrent package), which are:

  • newCachedThreadPool creates a cacheable thread pool. If the length of the thread pool exceeds the processing needs, it can flexibly
    reclaim idle threads. If there is no reclaimable thread, a new thread will be created.
  • newFixedThreadPool creates a fixed-length thread pool, which can control the maximum number of concurrent threads, and the excess threads will
    wait in the queue.
  • newScheduledThreadPool creates a fixed-length thread pool that supports timing and periodic task execution.
  • newSingleThreadExecutor creates a single-threaded thread pool, which only uses the only worker thread to execute
    tasks, ensuring that all tasks are executed in the specified order (FIFO, LIFO, priority).

12. What are the thread pool parameters?

  • corePoolSize core thread size.
  • maximumPoolSize The maximum number of threads in the thread pool.
  • keepAliveTime Idle thread survival time.
  • unit space thread survival time unit.
  • workQueue The work queue.
  • threadFactory thread factory.
  • handler reject policy.

13. What are the thread pool rejection strategies?

  • ThreadPoolExecutor.AbortPolicy: discard the task and throw RejectedExecutionExceptionan exception
    (default reject strategy).
  • ThreadPoolExecutor.DiscardPolicy: Discard the task, but do not throw an exception.
  • ThreadPoolExecutor.DiscardOldestPolicy: Discard the task at the head of the queue and resubmit the
    rejected task.
  • ThreadPoolExecutor.CallerRunsPolicy: The task is processed by the calling thread (the thread that submitted the task).

14. Do you think that the core parameters of the thread pool can be customized and configured? What are the three core parameters?

  • corePoolSize : The number of core threads The number of threads defines the minimum number of threads that can run at the same time.
  • maximumPoolSize : When the tasks stored in the queue reach the queue capacity, the
    number of threads that can currently run simultaneously becomes the maximum number of threads.
  • workQueue: When a new task comes, it will first judge whether the number of currently running threads has reached the number of core threads. If
    so, the trust will be stored in the queue.

15. ThreadPoolExecutor thread pool, corePoolSize=5, maximumPoolSize=10, queueCapacity=10, there are 20 time-consuming tasks handed over to this thread pool for execution, how will the thread pool execute these 20 tasks?

  • If the current number of threads < corePoolSize, if yes, create a new thread to execute the task.
  • If the current number of threads >= corePoolSize, then deposit the task BlockingQueue.
  • If the blocking queue is full and the current number of threads < maximumPoolSize, a new thread is created to execute the task.
  • If the blocking queue is full and the current number of threads >= maximumPoolSize, an exception is thrown.
  • RejectedExecutionException, telling the caller that tasks can no longer be accepted.

16. The task of sending a message to the user exceeds the queue, which rejection strategy do you use? Is there another way?

ThreadPoolExecutor.CallerRunsPolicy

  • Unbounded queue (LinkedBlockingQuene), continue to add tasks to the blocking queue to wait for execution.
  • Use the message queue to store task data, and the thread pool will process it slowly.

17. What are the new features of Java8?

  • interface's default method
  • Lambda expressions
  • functional interface
  • Method and Constructor References
  • Lambda expression scope
  • built-in functional interface
  • Optional
  • Streams
  • Parallel Streams
  • Maps
  • Date API (date related API)
  • Annotations

18. When to use multithreading, why should we design multithreading?

  • High concurrency
    When the system accepts the high concurrency of multi-user and multi-request, it realizes it through multi-threading.
    Thread background processing of large tasks
    A program is executed linearly. If the program executes a task that takes a lot of time to process, the main program has to wait for it to
    finish before continuing to execute the following. Then the user will have to wait for it to finish executing.
    At this time, you can open a thread and put the tasks that take a lot of time to process in the thread, so that when the thread is processing in the background, the main program can
    continue to execute, and the user does not need to wait. Execute the callback function after the thread execution.
  • Large tasks
    Large tasks are time-consuming to process. At this time, multiple threads can be used to speed up the processing in parallel (for example: uploading in pieces).
    Benefits: CPU utilization can be improved. In a multi-threaded program, when a thread must wait, the CPU can run
    other threads instead of waiting, which greatly improves the efficiency of the program. That is to say, a single program is allowed to create multiple
    threads of parallel execution to complete their respective tasks.

19. The more multi-threads, the higher the efficiency?

Not
more threads are more efficient when the total number of threads is less.
When the total number of threads is large, the more threads, the lower the efficiency due to the time-consuming calls of the threads themselves.
A higher number of threads will result in:

  • Thread lifetime overhead is very high
  • Consuming excessive CPU resources.

20. What concurrency issues will multithreading cause?

Security issues: Code that runs normally on a single-threaded system may have unexpected results in a multi-threaded environment.
Liveness issues: Incorrect locking and unlocking methods may lead to deadlock or livelock issues.
Performance issues: Multi-thread concurrency means that multiple threads switch to run. Thread switching will consume a certain amount and lock incorrectly.

21. How does Mybatis convert objects into SQL?

SQL binding is to load the Mybatis configuration file, then scan to which mapper child node, then load the mapper mapping file, scan the SQL nodes inside, and then encapsulate it into an object (MappedStatement, which encapsulates the sql statement in the SqlSource of this object). All the configuration information is saved in the Configuration class, and finally
when the dynamic proxy is executed, it takes out the object that encapsulates the sql and executes the sql.

22. What is virtual memory, and what is the principle of virtual memory?

Virtual memory is a technology for computer system memory management.
Virtual memory has the following two advantages:

  • The virtual memory address space is contiguous without fragmentation.
  • The maximum space of the virtual memory is the maximum addressing space of the cup, which is not limited by the size of the memory and can provide a larger address space than the memory.
    When each process is created, the kernel will allocate virtual memory for each process. At this time, the data and code are still on the disk. When the corresponding program is run, the process will look for the page table. If it is found that the address in the page table is not stored On the physical memory, but on the disk, a page fault occurs, so the data on the disk is copied to the physical memory and the page table is updated, and the next time the virtual address is accessed, it will be hit.

23. Will the stack overflow? When does it overflow? Will the method area overflow?

The stack is private to the thread, and its life cycle is the same as that of the thread. When each method is executed, a stack frame is created to store information such as local variable table, operand stack, dynamic link, and method exit. The local variable table contains basic data types and object reference types. If the stack depth requested by the thread is greater than the maximum depth allowed by the virtual machine, a StackOverflowError exception will be thrown, and the method recursive call will produce this result. If the Java virtual machine stack can be dynamically expanded, and the expansion action has been tried, but cannot apply for enough memory to complete the expansion, or there is not enough memory to create the corresponding virtual machine stack when a new thread is created, then the Java virtual machine The machine will throw an OutOfMemory exception. (Too many threads started).
The method area overflows.
Before HotSpot jdk1.7, the string constant pool was part of the method area. The method area was called "permanent generation". Before 1.7,
unlimited creation of objects would cause memory overflow. The prompt message: PermGen space is used after jdk1.7.
Start to gradually remove the permanent generation, and there will be no memory overflow.
The method area is used to store related information of Class, such as class name, access modifier, constant pool, field description, method description, etc.
If a large number of Class files are dynamically generated, memory overflow will also occur. Common scenarios include: a large number of JSP or
applications that dynamically generate JSP files (JSP needs to be compiled into java classes when running for the first time), OSGi-based applications (
even same class file is loaded by different class loaders will be treated as different classes).

24. How does the JVM load classes?

The JVM class loading mechanism is divided into five parts: loading, verification, preparation, resolution, and initialization.
Loading
Loading is a stage in the class loading process. In this stage, a java.lang.Class object representing this class will be generated in memory
as the entry of various data of this class in the method area. Note that it does not have to be obtained from a Class file.
It can be read from a ZIP package (such as from a jar package and a war package), or it can be calculated and generated at runtime
(dynamic proxy), or it can be generated by other File generation (such as converting JSP files into corresponding Class classes).
The main purpose of verification
at this stage is to ensure whether the information contained in the byte stream of the Class file meets the requirements of the current virtual machine
and does not endanger the safety of the virtual machine itself.
Preparation The preparation stage is the stage of formally allocating memory for class variables and setting the initial value of class variables, that is, allocating the memory space used by
these variables in the method area .
Pay attention to the concept of initial value mentioned here. For example, a class variable is defined as: In
fact, the initial value of the variable v after the preparation phase is 0 instead of 8080. The put static
instruction that assigns v to 8080 is stored in after the program is compiled. in the class constructor method.
But note that if the declaration is:
public static final int v = 8080;
ConstantValue attribute will be generated for v in the compilation stage, and the virtual machine
will assign v to 8080 according to the ConstantValue attribute in the preparation stage.
analyze
The resolution phase refers to the process in which the virtual machine replaces symbolic references in the constant pool with direct references. The symbol reference is the public static int v = 8080
in the class file; in fact, the initial value of the variable v after the preparation phase is 0 instead of 8080, and the put static instruction that assigns v to 8080 is stored in the class structure after the program is compiled. device method. But note that if the statement is: ConstantValue attribute will be generated for v in the compilation stage, and the virtual machine will assign v to 8080 according to the ConstantValue attribute in the preparation stage. Initialization The initialization stage is the last stage of class loading. After the previous class loading stage, except for the custom class loader in the loading stage , other operations are dominated by the JVM. In the initial stage, the Java program code defined in the class is actually executed.








25. Have you written the String class yourself and can it be loaded? When was the previous String loaded?

Cannot be loaded, because of the parental delegation mechanism, JVM for security reasons, String with the same fully qualified class name cannot
be loaded.
java.lang.String will be loaded by the top-level class loader Bootstrap Classloader. When the class file is loaded into
memory, other constants in the class file constant pool will be loaded into the runtime constant pool, but string constants will not. It will first
create a string object in the heap area, and then save the reference of this object to the global string constant pool.

26. Describe the underlying implementation principle and common scenarios of ThreadLocal (thread local variable)?

Implementation principle:

  • Each Thread thread has a ThreadLocalMap inside; with threads as keys and generics as values,
    it can be understood as a thread-level cache. Each thread gets a separate map.
  • Access methods such as set and get are provided, which store a separate copy for each thread using the variable
    , so the get method always returns the latest value set by the current thread of execution when set was called.
    Application scenario:
  • JDBC connection
  • Session management
  • Spring transaction management
  • Call chain, parameter passing
  • AOP
    ThreadLocal is a class that solves thread concurrency issues. It is used to create thread local variables. We know that
    all threads of an object will share its global variables, so these variables are not thread-safe. We can use synchronization technology.
    But when we don't want to use synchronization, we can choose ThreadLocal variable. For example, since JDBC's connection objects are not thread-safe, global variables are not thread-safe
    when multithreaded applications use them without coordination .
    By storing the JDBC connection object in ThreadLocal, each thread will have its
    own copy of the connection object.

27. What is microservice architecture?

The microservice architecture is to divide a single application into multiple applications, and these multiple applications become microservices. Each microservice
runs in its own process and communicates using a lightweight mechanism. These services are divided around business capabilities and
deployed independently through automated deployment mechanisms. These services can use different programming languages, different databases, to ensure a minimum
of centralized management.

28. What are the characteristics of microservices?

  • Decoupling - Services within the system are largely decoupled. Thus, the entire application can be easily built, changed and
    extended
  • Componentization – Microservices are treated as independent components that can be easily replaced and upgraded
  • Business Capabilities – Microservices are very simple and focus on a single function
  • Autonomy – developers and teams can work independently of each other, increasing velocity
  • Continuous Delivery – through the automation of a system of software creation, testing, and approval, allowing for frequent releases of software
  • Responsibility - Microservices do not focus on the application as a project. Instead, they view the application as a product they are responsible for
  • Decentralized Governance – The focus is on using the right tool for the right job. This means that there is no standardized model or any technical
    model. Developers are free to choose the most useful tool to solve their problems
  • Agile – Microservices support agile development. Any new features can be developed quickly and discarded again

29. What is a Lambda expression? Advantages and disadvantages?

Lambda expressions, also known as closures, are the most important new feature driving the release of Java 8. Lambda allows
functions to be used as parameters of a method (functions are passed into methods as parameters), and using Lambda expressions can make the code
more concise and compact.

  • advantage:
    • The code is more concise
    • Reduce the creation of anonymous inner classes and save resources
    • No need to remember the interface and abstract function used when using
  • shortcoming:
    • It is not easy to maintain later, you must be familiar with the types of parameters in lambda expressions and abstract functions
    • poor readability
    • If parallel calculation is not used, the calculation speed is not faster than the traditional for loop in many cases. (Parallel computing sometimes needs to be warmed up
      to show efficiency advantages)
    • Not easy to debug.
    • If other programmers have not learned lambda expressions, the code is not easy for programmers in other languages ​​to understand.

30. Talk about the expression scope of Lambda (Lambda Scopes).

  • access local variables
    • We can directly access external local variables in lambda expressions: but unlike anonymous objects, the
      variables here do not need to be declared as final, and the code is also correct, but the variables here must not be modified by the following code
      (that is, implicit Sexually has final semantics)
  • Access fields and static variables
    • In contrast to local variables, we have both read and write access to instance fields and static variables in lambda expressions.
      This behavior is consistent with anonymous objects.
      Access to default interface methods
    • Default methods cannot be accessed from lambda expressions.

31. What are the characteristics of MySQL transactions, and what do they mean?

  • Atomicity: that is, indivisibility, either all transactions are executed, or none are executed.
  • Consistency or stringability. The execution of a transaction causes the database to transition from one correct state to another.
  • isolation. Any changes to data made by a transaction are not allowed to be made available to any other transaction until the transaction is properly committed.
    Persistence. After the transaction is submitted correctly, its result will be permanently stored in the database, even if there are other failures after the transaction is submitted
    , the transaction processing result will also be saved

Guess you like

Origin blog.csdn.net/u011397981/article/details/131557809