preface

Multithreading and concurrent questions are one of the most popular questions that Java technology interviewers ask. Here, most of the important questions are listed from the perspective of the interview, but you should still have a solid grasp of Java multithreading basics to deal with the future problems, small series here also organized a concurrent programming mind map, convenient knowledge overview.

Java Oop, Java Collections containers, Java exceptions, concurrent programming, Java reflection, Java serialization, JVM, Redis, Spring MVC, MyBatis, MySQL database, messaging middleware MQ, Dubbo, Linux, ZooKeeper, distributed & data structure and algorithm, etc. 25 thematic technical points, are all small editor in each big factory summary of the interview real questions, there have been many fans with this PDF to win many big factory offer. Today, here is a summary to share to everyone! [Finished]

The full version of the Java interview questions address: 2021 latest interview questions collection collection.

The serial number project content link
1 The middleware Java Middleware (2021) Juejin. Cn/post / 694870…
2 Micro service Java Microservices (2021) Juejin. Cn/post / 694906…
3 Concurrent programming Concurrent Programming in Java (2021 latest Edition) Juejin. Cn/post / 695053…
4 Java based Java Basics (2021) Juejin. Cn/post / 695062…
5 Spring Boot Spring Boot Interview Questions (2021 Latest edition) Juejin. Cn/post / 695137…
6 Redis Redis Interview Questions (2021 Latest edition) Juejin. Cn/post / 695166…
7 Spring MVC Spring MVC (2021) Juejin. Cn/post / 695166…
8 Spring Cloud Spring Cloud Interview Questions (2021) Juejin. Cn/post / 695245…
9 MySQL optimization MySQL optimize interview questions (2021 latest edition) Juejin. Cn/post / 695246…
10 JVM JVM Performance Tuning Interview questions (2021 Latest Edition) Juejin. Cn/post / 695246…
11 Linux Linux Interview Questions (2021 latest edition) Juejin. Cn/post / 695287…
12 Mybatis Mybatis (2021 latest Edition) Juejin. Cn/post / 695287…
13 Network programming TCP, UDP, Socket, Http Network programming interview (2021 latest edition) Juejin. Cn/post / 695287…
14 Design patterns Design Mode Interview Questions (2021 Latest edition) Juejin. Cn/post / 695544…
15 Big data 100 Big Data Interview Questions (2021 latest edition) Juejin. Cn/post / 695544…
16 Tomcat Tomcat Interview Questions (2021 Latest edition) Juejin. Cn/post / 695570…
17 multithreading Multithreaded Interview Questions (2021 Latest edition) Juejin. Cn/editor/draf…
18 Nginx Nginx_BIO_NIO_AIO interview Questions (2021 Latest edition) Juejin. Cn/editor/draf…
19 memcache Memcache Interview Questions (2021 latest edition) Juejin. Cn/post / 695608…
20 Java exception Java Exception Interview Questions (2021 Latest edition) Juejin. Cn/post / 695644…
21 The Java virtual machine Java Virtual Machine Interview (2021 latest edition) Juejin. Cn/post / 695658…
22 Java collection Java Set Interview Questions (2021 Latest edition) Juejin. Cn/post / 695684…
23 Git Git Git Command (2021) Juejin. Cn/post / 695692…
24 Elasticsearch Elasticsearch (2021 Latest Edition) Juejin. Cn/post / 695840…
25 Dubbo Dubbo Interview Questions (2021 Latest edition) Juejin. Cn/post / 695842…
# 1. Basic knowledge

1. Why use concurrent programming

  • Take full advantage of the computing power of multi-core CPUS: Use concurrent programming to maximize the computing power of multi-core cpus and improve performance
  • Facilitate service separation and improve system concurrency capability and performance: In special service scenarios, it is inherently suitable for concurrent programming. Nowadays, the system often requires millions or even tens of millions of concurrent, and multi-threaded concurrent programming is the basis of developing high concurrency system, the use of multi-threaded mechanism can greatly improve the overall concurrent ability and performance of the system. In the face of complex business models, parallel programs are better suited to business requirements than serial programs, and concurrent programming is better suited to this kind of business separation.

2. Multi-threaded application scenarios

3. What are the disadvantages of concurrent programming

The purpose of concurrent programming is to improve the execution efficiency of the program and improve the running speed of the program, but concurrent programming can not always improve the running speed of the program, and concurrent programming may encounter many problems, such as memory leak, context switch, thread safety, deadlock, etc..

4. What are the three essential elements of concurrent programming?

Three elements of concurrent programming (the safety of threads is reflected in) :

Atomicity: Atom, i.e., a particle that can no longer be divided. Atomicity means that one or more operations either all execute successfully or all fail.

Visibility: Changes made by one thread to a shared variable can be immediately seen by another thread. (synchronized, volatile)

Orderliness: The order in which a program is executed is the order in which the code is executed. (The processor may reorder the instructions)

Causes of thread-safety issues:

  • Atomicity issues with thread switching
  • Visibility issues caused by caching
  • Order problems with compiler optimization

Solutions:

  • JDK Atomic classes, synchronized, and LOCK can solve Atomic problems
  • Synchronized, volatile, and LOCK solve the visibility problem
  • The happens-before rule solves the orderliness problem

5. How to ensure the safety of multithreading in Java program?

6. What is the difference between parallelism and concurrency?

7. What is multithreading

Multithreading: Multithreading refers to the fact that a program contains multiple execution streams, that is, multiple threads can run simultaneously in a program to perform different tasks.

8. Benefits of multithreading

It can improve CPU utilization. In multithreaded programs, when one thread has to wait, the CPU can run other threads instead of waiting, which greatly improves the efficiency of the program. This allows a single program to create multiple threads of parallel execution to complete their respective tasks.

9. Disadvantages of multi-threading:

  • Threads are also programs, so threads need to take up memory, and the more threads they have, the more memory they take up;
  • Multithreading requires coordination and management, so it requires CPU time to track threads;
  • Access to shared resources affects each other between threads, and the problem of competing for shared resources must be resolved.

10. Differences between threads and processes

process

An application that runs in memory. Each process has its own independent memory space. A process can have multiple threads. For example, in Windows, a running XX. exe is a process.

thread

An execution task (control unit) in a process that is responsible for the execution of programs in the current process. A process has at least one thread. A process can run multiple threads, and multiple threads can share data.

Thread has many characteristics of traditional Process, so it is also called light-weight Process or Process element. The traditional Process is called a heavy-weight Process, which is equivalent to a task with only one thread. In operating systems that introduce threading, it is common for a process to have several threads, or at least one thread.

Fundamental difference: Processes are the basic unit of operating system resource allocation, while threads are the basic unit of processor task scheduling and execution

Resource overhead: Each process has its own code and data space (program context), and switching between programs can be expensive; Threads can be regarded as lightweight processes. The same type of threads share code and data space, and each thread has its own independent running stack and program counter (PC). Switching between threads has little overhead.

Inclusion: If there are multiple threads in a process, the execution process is not one line, but multiple lines (threads). Threads are part of a process, so they are also called lightweight or lightweight processes.

Memory allocation: Threads of the same process share the address space and resources of the process, while the address space and resources of the process are independent of each other

Impact relationship: the crash of one process in protected mode has no impact on other processes, but the crash of one thread kills the entire process. So multi-processing is more robust than multi-threading.

Execution: Each independent process has entry points for program execution, sequential execution sequences, and program exits. However, threads cannot be executed independently and must be dependent on the application, which provides control over the execution of multiple threads, both of which can be executed concurrently

11. What is context switching?

In multithreaded programming, the number of threads is generally greater than the number of CPU cores, and a CPU core can only be used by one thread at any time. In order to make these threads can be effectively executed, the CPU adopts the strategy of allocating time slices for each thread and rotating them. When a thread runs out of time, it is ready to be used by another thread. This process is a context switch.

To summarize, the current task saves its state before switching to another task after executing the CPU time slice, so that it can be reloaded when switching back to the task next time. The process from saving to reloading a task is a context switch.

Context switching is usually computationally intensive. In other words, it requires a significant amount of processor time, with each switch taking nanosecond of tens or hundreds of times per second. Therefore, context switching means consuming a lot of CPU time for the system, in fact, it may be the most time consuming operation in the operating system.

One of the many advantages Linux has over other operating systems, including other Unix-like systems, is that context switching and mode switching require very little time.

12. What is the difference between daemon threads and user threads?

Daemon threads and user threads

  • User thread: it runs in the foreground and performs specific tasks, such as the main thread of the program and the subthreads connected to the network
  • Daemon threads: Run in the background and serve other foreground threads. In other words, daemon threads are the servants of non-daemon threads in the JVM. Once all user threads have finished running, the daemon thread ends with the JVM

The thread in which main is started is a user thread, and many daemon threads, such as the garbage collector thread, are also started inside the JVM.

One of the more obvious differences is that the user thread terminates and the JVM exits, regardless of whether or not a daemon thread is running at this point. Daemon threads do not affect JVM exit.

Matters needing attention:

  1. setDaemon(true)Must be instart()Method, otherwise thrownIllegalThreadStateExceptionabnormal
  2. A new thread created in a daemon thread is also a daemon thread
  3. Not all tasks, such as read and write operations or computational logic, can be assigned to daemons
  4. The contents of a finally block cannot be relied on ina Daemon thread to ensure that the logic to close or clean up a resource is performed. Because we also mentioned above that once all user threads have finished running, the Daemon thread terminates with the JVM, so the finally block in the Daemon thread may not be executed.

13. How do I find which thread is the most CPU efficient on Windows and Linux?

14. What is a thread deadlock

15. What are the four necessary conditions for a deadlock

  • Mutually exclusive condition: A resource is occupied by only one process at a time. If there are other processes requesting the resource at this time, they can only wait until the process holding the resource is free.
  • Possessive-and-wait condition: a process that has held at least one resource and then requests a new resource that has been occupied by another process. In this case, the requesting process blocks but does not release other resources that it has obtained.
  • Non-preemption condition: someone else already has a resource, you can’t take it from someone else just because you need it.
  • Circular waiting condition: a circular waiting resource relationship is formed between several processes. (For example, A set of processes, A waiting for B, B waiting for C, C waiting for A)

16. How do I avoid thread deadlocks

  1. Avoid one thread acquiring multiple locks at the same time
  2. Avoid a thread occupying multiple resources in a lock at the same time. Try to ensure that each lock occupies only one resource
  3. Try using timing locks, using lock.tryLock(timeout) instead of using internal locking

17. Four ways to create a thread

  • Inheriting Thread class;
public class MyThread extends Thread { @Override public void run() { System.out.println(Thread.currentThread().getName() + "The run() method is executing..." ); }Copy the code
  • Implement Runnable interface;
public class MyRunnable implements Runnable { @Override public void run() { System.out.println(thread.currentThread ().getName() + "run(); ); }Copy the code
  • Callable interface;
public class MyCallable implements Callable<Integer> { @Override public Integer call() { System.out.println(thread.currentThread ().getName() + "Call () method executing..." ); return 1; }Copy the code
  • Use the anonymous inner class approach
Public class CreateRunnable {public static void main(String[] args) {// Create Thread Thread = new Thread(new) Runnable() { public void run() { for (int i = 0; i < 10; i++) { System.out.println("i:" + i); }}}); thread.start(); }}Copy the code

18. What is the difference between runnable and callable

19. What is the difference between run() and start() for a thread?

  • Each Thread completes its operations through the run() method corresponding to a particular Thread object, called the Thread body. Start a Thread by calling the start() method of the Thread class.
  • The start() method is used to start the thread, and the run() method is used to execute the thread’s runtime code. Run () can be called repeatedly, whereas start() can only be called once.
  • The start() method is used to start a thread, truly implementing multithreading. Calling the start() method does not wait for the run body to finish executing, but can continue to execute other code. The thread is in the ready state and is not running. The Thread then completes its running state by calling the run() method through the Thread class. The run() method ends and the Thread terminates. The CPU then schedules other threads.
  • The run() method is local to the thread, just a function in the thread, not multithreaded. If you call run() directly, it is just like calling a normal function. If you call run() directly, you have to wait for the run() method to complete before you can execute the following code. Therefore, there is only one execution path, and there is no thread characteristic at all. So use the start() method instead of the run() method for multithreaded execution.

20. Why do we call the run() method when we call the start() method, and why can’t we call the run() method directly?

21. What are Callable and Future?

  • The Callable interface is similar to Runnable, as the name suggests, but Runnable does not return a result and cannot throw an exception that returns a result. Callable is more powerful, and when executed by a thread, it can return a value, which can be retrieved by the Future. That is, the Future can get the return value of the asynchronously executed task.
  • The Future interface represents an asynchronous task and is the result of an asynchronous task that may not have completed. So Callable is used to produce results and Future is used to get results.

22. What is FutureTask

  • FutureTask represents a task for asynchronous computation. FutureTask can pass in a concrete implementation class of Callable, which can wait for the result of the asynchronous operation, determine whether the task has been completed, and cancel the task. The result can only be retrieved when the operation is complete, and the GET method will block if the operation is not complete. A FutureTask object can wrap Callable and Runnable objects, and since FutureTask is also an implementation class of the Runnable interface, FutureTask can also be placed in a thread pool.

23. Thread status

24. What is the thread scheduling algorithm used in Java?

25. Scheduling policies for threads

26. What are Thread schedulers and Time Slicing?

27. Name methods related to thread synchronization and thread scheduling.

28. What’s the difference between sleep() and wait()?

29. How do you call wait()? If block or loop? Why is that?

30. Why are the thread communication methods wait(), notify(), and notifyAll() defined in the Object class?

31. Why must wait(), notify(), and notifyAll() be called in synchronized methods or synchronized blocks?

32. What is the use of the yield method in Thread?

33. Why are Thread’s sleep() and yield () methods static?

34. What is the difference between a thread’s sleep() method and its yield() method?

35. How do I stop a running thread?

What is the difference between the interrupted and isInterrupted methods in Java?

37. What are blocking methods?

38. How do you wake up a blocked thread in Java?

What is the difference between notify() and notifyAll()?

40. How do I share data between two threads?

41. How does Java implement communication and collaboration between multiple threads?

42. Which is a better choice, synchronization method or synchronization block?

43. What are thread synchronization and thread exclusion, and how can they be implemented?

44. How is thread synchronization done inside a Monitor? What level of synchronization should the program do?

45. What happens if the thread pool queue is full when you submit a task

46. What is thread safety? Are servlets thread-safe?

47. How to ensure the safety of multithreading in Java program?

48. What is your understanding of thread priority?

49. The constructor of the thread class, the static block, is called by which thread

50. How to obtain a thread dump file in Java? How do you get a thread stack in Java?

  • Dump files are memory mirrors of processes. The execution state of a program can be saved to a dump file using the debugger.
  • On Linux, you can run the kill -3 PID command to obtain the dump file of the Java application.
  • On Windows, you can get it by pressing Ctrl + Break. The JVM then prints the thread’s dump file to standard output or an error file, either in the console or in a log file, depending on the configuration of the application.

51. What happens when an exception occurs while a thread is running?

  • The thread will stop execution if the exception is not caught. Thread. UncaughtExceptionHandler is used for uncaught exception handling Thread sudden interruption of an embedded interface. When an uncaught exception will interrupt the thread, The JVM will use Thread. GetUncaughtExceptionHandler () to query the Thread UncaughtExceptionHandler Thread and abnormal passed as a parameter to the handler UncaughtException () method.

52. What exceptions can be caused by too many Java threads?

53. Common methods of multithreading

Second, concurrency theory

1. What is the purpose of garbage collection in Java? When is garbage collection?

  • Garbage collection occurs when there are unreferenced objects in memory or objects that are out of scope.
  • The purpose of garbage collection is to identify and discard objects that are no longer used by applications to free and reuse resources.

2. How do threads communicate and synchronize with each other

  • In concurrent programming, we need to deal with two key issues: how threads communicate with each other and how threads synchronize with each other. Communication refers to how threads exchange information. There are two common communication mechanisms between threads: shared memory and message passing.
  • Concurrency in Java uses a shared memory model, where communication between Java threads is always implicit and completely transparent to the programmer. Java programmers writing multithreaded programs are likely to encounter all sorts of strange memory visibility problems if they don’t understand how implicit communication between threads works.

3. Java memory model

  • The shared Memory model refers to the Java Memory model (JMM), which determines that a shared variable written by one thread can be visible to another thread. From an abstract point of view, JMM defines an abstract relationship between threads and main memory: Shared variables between threads are stored in main memory, and each thread has a private local memory where it stores copies of shared variables to read/write. Local memory is an abstraction of the JMM and does not really exist. It covers caches, write buffers, registers, and other hardware and compiler optimizations.

4. If a reference to an object is set to NULL, does the garbage collector immediately free the memory occupied by the object?

  • No, this object will be recyclable in the next garbage callback cycle.
  • This means that the memory is not immediately collected by the garbage collector, but is released at the next garbage collection.

5. When is the finalize() method called? What is the purpose of finalization?

6. What is reordering

7. Reorder the actual command steps

8. Rules for reordering

9. The difference between as-if-serial and happens-before rules

10. Synchronized?

11. Describe how you use the word synchronized in your project

12. Do you understand the singleton pattern? Explain to me how double checked locking implements the singleton pattern!”

13. Talk about the underlying implementation of synchronized.

14. The principle of synchronized reentrant

15. What is spin

16. What is the principle of synchronized lock escalation in multi-threading?

17. How does thread B know that thread A has changed A variable

  • (1) Volatile modifiers
  • (2) synchronized
  • (3) wait/notify
  • (4) while polling

18. When A thread enters the synchronized method A of an object, can other threads enter the synchronized method B of the object?

19. Comparison of synchronized, volatile and CAS

  • (1) Synchronized is a pessimistic lock, which belongs to preemption and will cause other threads to block.
  • (2) Volatile provides multithreaded shared variable visibility and disallows instruction reordering optimization.
  • (3) CAS is optimistic lock based on conflict detection (non-blocking)

20. What’s the difference between synchronized and Lock?

  • Synchronized is a built-in Java keyword, and Lock is a Java class at the JVM level.
  • Synchronized locks classes, methods, and code blocks; Lock can only lock a block of code.
  • Synchronized does not require manual lock acquisition and lock release. It is simple to use and automatically releases the lock when exceptions occur without causing deadlocks. A lock needs to lock and release itself, and if used incorrectly without unLock() to release the lock, a deadlock can occur.
  • Lock can tell if a Lock has been acquired successfully, whereas synchronized cannot.

21. What is the difference between synchronized and ReentrantLock?

22. The role of the volatile keyword

23. Can Volatile arrays be created in Java?

24. What is the difference between volatile variables and atomic variables?

25. Can volatile make a nonatomic operation atomic?

26. What is the difference between synchronized and volatile?

27. Final immutable objects, how does it help write concurrent applications?

28. What are the advantages of Lock interface compared with synchronized?

29. Understanding and implementation of optimistic lock and pessimistic lock, and what are the implementation methods?

30. What is CAS

31. What problems will arise with CAS?

32. What is an atomic class

33. Common classes for atomic classes

  • AtomicBoolean
  • AtomicInteger
  • AtomicLong
  • AtomicReference

34. How does Atomic work?

Atomic package basic feature is the class in a multithreaded environment, when there are multiple threads at the same time for a single (including basic types and reference types) variables, exclusive, when multiple threads on the value of the variable is updated at the same time, there is only one thread can be successful, but not the thread can to spin locks to success, keep trying, Wait until the execution succeeds.

35. The difference between a deadlock and a live lock, a deadlock and starvation?

Thread pools

What is a thread pool?

2. Thread pool function?

3. What are the advantages of thread pools?

4. What is ThreadPoolExecutor?

5. What is Executors?

6. What are the four ways to create a thread pool?

7. The difference between Executor and Executors in Java?

8. What are the differences and characteristics of the four kinds of thread pool construction?

What are the states of the thread pool?

10. What is the difference between submit() and execute() methods in the thread pool?

11. What are thread groups and why are they not recommended in Java?

12. What are the ThreadPoolExecutor saturation strategies?

13. How do I customize the thread pool?

14. How does thread pooling work?

15. How to allocate thread pool size properly?

4. Concurrent containers

1. What concurrent containers do you often use, and why?

  • A: Vector, ConcurrentHashMap, and HasTable
  • The most common containers used in software development are HashMap, ArrayList, LinkedList, and so on
  • However, in multi-threaded development, you should not mess with containers, and if you use unlocked (asynchronous) collections, your data will be very messy. Therefore, the containers used in multithreaded development must be locked (synchronized) containers.

2. What is Vector

3. What’s the difference between ArrayList and Vector?

4. Why is HashTable thread-safe?

5. How does ConcurrentHashMap differ from HashTable?

6. What is collections.synchronized *?

7. What is the concurrency of ConcurrentHashMap in Java?

8. What is the implementation of concurrent containers?

9. What is the difference between synchronous and concurrent collections in Java?

10. What is the difference between SynchronizedMap and ConcurrentHashMap?

11. What is CopyOnWriteArrayList?

12. Usage scenarios for CopyOnWriteArrayList?

Suitable for scenarios where you read more and write less.

13. Disadvantages of CopyOnWriteArrayList?

14. Design idea of CopyOnWriteArrayList?

5. Concurrent queues

1. What is a concurrent queue:

  • Message queue Many people know: message queue is an important component in distributed system, is the direct communication between systems
  • What is a concurrent queue: an important component of a concurrent queue where multiple threads share data in an orderly fashion

2. The difference between concurrent queues and concurrent collections:

  • Queues follow the “first in, first out” rule, can be thought of as queue check-in, queue is generally used to solve the large amount of data collection and processing and display.
  • Concurrent collections share data across multiple threads

3. How to determine whether a concurrent queue is a blocking queue or a non-blocking queue

On concurrent queues, the JDK provides a Queue interface, a BlockingQueue represented by the BlockingQueue interface under the Queue interface, and a high-performance (non-blocking) Queue.

4. Difference between blocking queue and non-blocking queue

  • Queue blocking When the queue is empty, fetching elements from the queue will be blocked.
  • Or if the blocking queue is full, adding elements to the queue will be blocked.
  • Or a thread trying to fetch an element from an empty blocking queue will be blocked until another thread inserts a new element into the empty queue.
  • A thread that tries to add new elements to a full blocking queue is also blocked until another thread makes the queue empty again

5. Introduction of common concurrent formation:

A common approach to concurrent queues

Concurrency tools

1. What are the common concurrency tool classes?

[Java concurrent programming interview question [attached answer analysis]

The last

Xiaobian article to share here is over, tidy up is not easy, welcome everyone to exchange, like xiaobian article to share remember to pay attention to me like yo, thank you for your support!