preface

Recently in view of the Internet company interview asked knowledge points, summed up the Java programmer interview involves most of the interview questions and answers to share with you, I hope to help you review before the interview and find a good job, but also save you on the Internet to search for information time to learn.

Content covers: Java, MyBatis, ZooKeeper, Dubbo, Elasticsearch, Memcached, Redis, MySQL, Spring, SpringBoot, SpringCloud, RabbitMQ, Kafka, Linux and other technology stacks.

Full version Java interview questions address: Java backend questions integration

1. Three elements of concurrent programming?

### (1) atomicity

Atomicity refers to one or more operations that are either all performed without interruption by other operations, or none performed at all.

### (2) Visibility

Visibility means that when multiple threads operate on a shared variable, when one thread makes changes to the variable, the other threads can see the changes immediately.

(3) Orderliness

Orderliness, that is, the order in which the program is executed is the order in which the code is executed.

2. What are the ways to achieve visibility?

Synchronized or Lock: ensure that only one thread at a time obtains the Lock execution code, and refresh the latest value to the main memory before releasing the Lock to achieve visibility.

3. The value of multithreading?

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

Multi-threaded, can really play the advantages of multi-core CPU, to make full use of the PURPOSE of CPU, using multi-threaded way to complete several things at the same time without mutual interference.

(2) Prevent blocking

From the point of view of program efficiency, single-core CPU will not give full play to the advantages of multithreading, but will cause the thread context switch because of running multithreading on single-core CPU, and reduce the overall efficiency of the program. But with a single-core CPU we still have to apply multithreading just to prevent blocking. Imagine if a single-core CPU uses a single thread, and if that thread blocks, say, reading data remotely, and the peer doesn’t return and doesn’t set a timeout, your entire program will stop running before the data comes back.

Multithreading prevents this problem. Multiple threads are running at the same time, and even if the code in one thread is blocked in reading data, it does not affect the execution of other tasks.

### (3) Easy to model

This is another advantage that is not so obvious. Let’s say you have A big task A, single-threaded programming, and it’s A lot to think about, and it’s A lot of trouble to model the entire program. However, if the big task A is broken down into several small tasks, task B, task C and task D, respectively build the program model, and run these tasks separately through multi-threading, it will be much simpler.

4. What are the ways to create threads?

(1) Create Thread class by inheriting Thread class

(2) Create a thread class through the Runnable interface

(3) Create threads with Callable and Future

(4) Create by thread pool

(5) How do you compare the three ways to create threads? (1) Use Runnable, Callable interface to create multithreading.

Advantages are:

Thread classes simply implement the Runnable or Callable interfaces and can inherit from other classes. In this way, multiple threads can share the same target object, so it is very suitable for the situation of multiple same threads to deal with the same resource, so that the CPU, code and data can be separated, forming a clear model, which better reflects the idea of object-oriented.

Disadvantages are:

Programming is a little more complicated, and if you want to access the currentThread, you must use the thread.currentthread () method. ### (2) Create threads by inheriting the Thread class

Advantages are:

If you need access to the currentThread, use this instead of thread.currentthread ().

Disadvantages are:

Thread classes already inherit from Thread, so they cannot inherit from other parent classes.

(3) Difference between Runnable and Callable

(1) The Callable method is call(), and the Runnable method is run().

(2) Callable tasks can return values after execution, while Runnable tasks cannot return values.

(3) The Call method can throw an exception, but the run method cannot.

(4) Run the Callable task to get a Future object, which represents the result of the asynchronous calculation. It provides methods to check that the calculation is complete, wait for the calculation to complete, and retrieve the results of the calculation. By using the Future object, you can know the execution status of the task, cancel the execution of the task, and obtain the execution result.

6. Thread state flow diagram

The life cycle of a thread and its five basic states:

! [img_2.png][img_2.png]

Java threads have five basic states

(1) New state (New) : When the Thread object pair is created, it enters the New state, such as: Thread t = New MyThread();

(2) ready state (Runnable) : when the thread object’s start() method is called (t.start();) , the thread enters the ready state. When a thread is in the ready state, it is ready to be executed by the CPU, not when t.start() is executed.

(3) Running state (Running state) : when the CPU starts to schedule the thread in the ready state, then the thread can actually execute, that is, enter the Running state. Note: The thread state is the only entry into the running state, that is, to enter the running state execution, the thread must first be in the ready state;

(4) Blocked state: The thread in the running state temporarily gives up the right to use the CPU for some reason and stops execution. At this time, it enters the Blocked state. Until it enters the ready state, it has the chance to be called by the CPU again to enter the running state.

According to different causes of blocking, blocking states can be divided into three types:

(1) Waiting to block: the thread in the running state executes wait() to make the thread enter the waiting state;

(2) Synchronized blocking: a thread fails to acquire a synchronized lock (because the lock is occupied by other threads), and it will enter the synchronized blocking state;

(3) Other blocking: the thread will enter the blocking state by calling its sleep() or join() or issuing an I/O request. When the sleep() state times out, when the join() wait thread terminates or times out, or when I/O processing is complete, the thread goes back to the ready state.

(4) Dead state: the thread completes execution or exits the run() method due to an exception, and the thread ends its life cycle.

What is a thread pool? What are the ways to create it?

A thread pool is a pool of threads that are created in advance. If there is a task that needs to be processed, the threads in the pool will handle the task, and then the thread will not be destroyed. Instead, it will wait for the next task. Since creating and destroying threads consumes system resources, consider using thread pools when you want to create and destroy threads frequently to improve system performance.

Java provides a Java. Util. Concurrent. The realization of the Executor interface is used to create a thread pool.

9. Create thread pools:

(1) newCachedThreadPool creates a cacheable thread pool

(2) newFixedThreadPool creates a fixed length thread pool, which can control the maximum number of concurrent threads.

(3) newScheduledThreadPool Creates a thread pool of fixed length to support scheduled and periodic task execution.

(4) newSingleThreadExecutor creates a single threaded thread pool that only uses a single worker thread to perform tasks.

10. What are the advantages of thread pools?

(1) Reuse existing threads to reduce the overhead of object creation and destruction.

(2) It can effectively control the maximum number of concurrent threads, improve the utilization rate of system resources, and avoid excessive resource competition and blockage.

(3) Provide timing execution, periodic execution, single thread, concurrency control and other functions.

11. What are the common concurrency utility classes?

(1) CountDownLatch

(2) the CyclicBarrier

(3) the Semaphore

(4) Exchanger

12. CyclicBarrier and CountDownLatch

CountDownLatch is simply a thread waiting until all the other threads it is waiting on have completed and the countDown() method is called to issue a notification.

(2) cyclicBarrier means that all threads wait until all threads are ready to enter the await() method, and all threads start executing at the same time!

(3) CountDownLatch’s counter can only be used once. The CyclicBarrier counter can be reset using the reset() method. So CyclicBarrier can handle more complex business scenarios, such as resetting counters and having threads execute again if a calculation goes wrong.

CyclicBarrier also provides other useful methods, such as the getNumberWaiting method to get the number of threads blocked by CyclicBarrier. The isBroken method is used to know if a blocking thread is interrupted.

Returns true if interrupted, false otherwise.

13. The role of synchronized?

In Java, the synchronized keyword is used to control thread synchronization, which prevents synchronized code from being executed by multiple threads in a multithreaded environment.

Synchronized can be added to either a piece of code or a method.

14. The role of the volatile keyword

For visibility, Java provides the volatile keyword to ensure visibility.

When a shared variable is volatile, it guarantees that the value is immediately updated to main memory, and that it will read the new value in memory when another thread needs to read it.

From the point of the practice, is an important role of volatile and CAS, guarantees the atomicity and detail can see Java. Util. Concurrent. The atomic classes under the package, such as AtomicInteger.

15. What is CAS

CAS stands for compare and swap, as we call it.

Cas is a lock-based operation, and it is optimistic locking. In Java, there are optimistic locks and pessimistic locks. Pessimistic locking means that a resource is locked until the next thread can access it after the previous thread has released the lock. Optimistic locking, which takes a broad approach and processes resources in some way without locking, such as fetching data by adding version to records, has a significant performance improvement over pessimistic locking.

The CAS operation contains three operands — the memory location (V), the expected old value (A), and the new value (B). If the value in the memory address is the same as the value of A, then the value in memory is updated to B.

CAS fetches data through an infinite loop. If thread A gets the address in the first loop and the value in the address is changed by thread B, then thread A needs to spin until the next loop is executed.

Java. Util. Concurrent. Atomic package under most of the class is implemented using CAS operation (AtomicInteger AtomicBoolean, AtomicLong).

16. CAS

(1) CAS is easy to cause ABA problems

A thread A changes the value to B and then to A, and CAS thinks it has not changed, but in fact it has changed. The solution to this problem can be identified by the version number, with version incremented by 1 for each operation. In java5, AtomicStampedReference is already provided to solve the problem.

(2) The atomicity of code blocks cannot be guaranteed

The CAS mechanism guarantees atomicity for a variable, but not for an entire code block. For example, synchronized is used to ensure that all three variables are updated atomically.

(3) CAS increases CPU usage

As mentioned earlier, CAS is a circular process. If the thread does not get the state, CPU resources will be occupied.

17, What is Future?

In concurrent programming, we often use the non-blocking model. In the previous three implementations of multithreading, neither inheriting the Thread class nor implementing the Runnable interface was guaranteed to get the results of the previous execution. By implementing the Callback interface and using the Future, you can receive multithreaded execution results.

A Future represents the result of an asynchronous task that may not have completed, to which a Callback can be added to act upon the success or failure of the task.

18. What is AQS

AQS is short for AbustactQueuedSynchronizer, it is a Java improve the bottom of the synchronous tools, expressed in a variable of type int synchronization state, and provides a series of CAS operation to manage the synchronization state.

AQS is a framework for building locks and synchronizers. It is easy and efficient to build a wide range of synchronizers, such as ReentrantLock, Semaphore, and others such as ReentrantReadWriteLock. SynchronousQueue, FutureTask, and so on are all based on AQS.

19. AQS supports two synchronization modes:

(1) Exclusive

(2) Shared

This allows users to implement different types of synchronization components, such as exclusive ReentrantLock, shared Semaphore, CountDownLatch, and combined ReentrantReadWriteLock. In short, AQS provide the underlying support for use, and the user is free to assemble the implementation.

20. What is ReadWriteLock

To be clear, it’s not that ReentrantLock is bad, it’s just that ReentrantLock is sometimes limited. ReentrantLock may be used to prevent data inconsistency caused by thread A writing data and thread B reading data. However, if thread C is reading data and thread D is also reading data, the read data does not change the data. There is no need to lock the data, but the lock is still locked, which reduces the performance of the program. Because of this, the read-write lock ReadWriteLock was born.

ReadWriteLock is a read/write lock interface. ReentrantReadWriteLock is a concrete implementation of the ReadWriteLock interface. It enables read and write separation. Read and write, write and read, and write and write are mutually exclusive, improving read and write performance.

21. What is FutureTask

This was actually mentioned earlier, 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. Of course, since FutureTask is also an implementation class of the Runnable interface, it can also be put into a thread pool.

The difference between synchronized and ReentrantLock

Synchronized is a keyword like if, else, for, and while. ReentrantLock is a class. This is the essential difference between synchronized and while.

Since ReentrantLock is a class, it provides more flexible features than synchronized. It can be inherited, can have methods, and can have a variety of class variables. ReentrantLock has more extensibility than synchronized in several aspects:

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

(2) ReentrantLock can obtain information about various locks

(3) ReentrantLock can flexibly implement multi-way notification

In addition, the locking mechanism is also different. The underlying ReentrantLock is the Unsafe park method, while synchronized is the mark Word object header. I’m not sure.

What is the optimistic lock and pessimistic lock

Optimistic locking (1) : just like its name, for concurrent operation thread safety problem between state, optimistic optimistic locking that competition does not always happen, so it doesn’t need to hold the lock, will compare – to replace the two actions as an atomic operation to try to modify variables in memory, if failure, said conflict, then there should be a corresponding retry logic.

(2) pessimistic locks: or, like its name, for concurrent operation thread safety problem between pessimistic, pessimistic locking think competition is always happen, so every time of operating resources, will hold an exclusive lock, as synchronized, willy-nilly, directly on the lock operation resources.

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

(1) Volatile modifiers

(2) synchronized

(3) wait/notify

(4) while polling

25. 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)

What’s the difference between sleep and wait?

Sleep and wait can both be used to give up the CPU for a certain amount of time. The difference is that if a thread holds the monitor for an object, sleep does not give up the monitor for that object, while wait does

27. What is ThreadLocal? What’s the use?

ThreadLocal is a local thread copy variable utility class. It is mainly used to make a mapping between the private thread and the copy object stored by the thread. The variables between each thread do not interfere with each other. In the high concurrency scenario, stateless call can be realized, especially suitable for the scenario where each thread relies on impassable variable values to complete operations.

Simple said ThreadLocal is a kind of to the practice of trading space for time, in each Thread maintains a method to implement ThreadLocal. With open address ThreadLocalMap, isolating data, data is not Shared, nature is no Thread safety issues.

The JDK forces wait() and notify()/notifyAll() to be called in a synchronized block. Both wait() and notify()/notifyAll() must acquire the lock of an object before being called.

What are the methods of multithreading synchronization?

Synchronized keyword, Lock Lock implementation, distributed Lock and so on.

Thread scheduling policy

The thread scheduler selects the thread with the highest priority to run, but terminates the thread if:

(1) The thread body uses the yield method to yield CPU usage

(2) The thread body calls the sleep method to make the thread enter the sleep state

(3) The thread is blocked due to IO operations

(4) Another thread of higher priority appears

(5) In the system that supports time slice, the time slice of the thread is used up

31. What is the concurrency of ConcurrentHashMap?

ConcurrentHashMap concurrency is the size of the segment. The default value is 16, which means that up to 16 threads can operate the ConcurrentHashMap at the same time. This is also the biggest advantage of ConcurrentHashMap over Hashtable. In any case, can Hashtable have two threads fetching data from Hashtable at the same time?

How do I find which thread uses the longest CPU in Linux?

(1) to obtain the pid of the project, the JSP or ps – ef | grep Java, the front has spoken

(2) Top-H-P PID, the sequence cannot be changed

Java deadlocks and how to avoid them?

A deadlock in Java is a programming condition in which two or more threads are permanently blocked, and a Java deadlock occurs in which at least two threads and two or more resources occur.

The root cause of deadlock in Java is that a cross closed loop application occurs during lock application.

The cause of the deadlock

(1) Multiple threads involve multiple locks, and these locks are crossed, which may lead to a lock-dependent closed loop.

For example, A thread applies for lock B when it has acquired lock A and has not released it. At this point, another thread has acquired lock B and needs to acquire lock A before releasing lock B. Therefore, A closed loop occurs and A deadlock loop occurs.

(2) The default lock request operation is blocked.

So to avoid deadlocks, we need to examine all methods in the classes of multiple objects for the possibility of lock-dependent loops whenever we encounter interlocking situations. In general, try to avoid calling delayed methods and synchronized methods of other objects in a synchronized method.

How do I wake up a blocked thread

If a thread is blocking because it called wait(), sleep(), or join(), you can interrupt it and wake it up by throwing InterruptedException. If the thread encounters AN IO block, there is nothing to be done, because IO is implemented by the operating system, and Java code has no direct access to the operating system.

36. How does immutable objects help multithreading

As mentioned earlier, immutable objects guarantee the memory visibility of objects, and reading immutable objects does not require additional synchronization, which improves code execution efficiency.

What is multithreaded context switching

Context switching in multithreading is the process of switching CPU control from one thread that is already running to another thread that is ready and waiting for CPU execution.

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

(1) If you are using an unbounded queue called LinkedBlockingQueue, that is, an unbounded queue, you can continue to add tasks to the blocking queue for execution, because LinkedBlockingQueue can be thought of as an almost infinite queue that can hold tasks indefinitely

(2) If you use a bounded queue such as ArrayBlockingQueue, the task will be added to the ArrayBlockingQueue first. If the ArrayBlockingQueue is full, the number of threads will be increased according to the value of maximumPoolSize. If the number of threads increases and ArrayBlockingQueue continues to fill up, then the full task will be processed using the RejectedExecutionHandler policy, which is AbortPolicy by default

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

Preemptive. After a thread runs out of CPU, the operating system calculates a total priority based on thread priority, thread hunger, etc., and allocates the next time slice to a particular thread.

What are Thread schedulers and TimeSlicing?

The Thread scheduler is an operating system service that allocates CPU time to Runnable threads. Once we create a thread and start it, its execution depends on the implementation of the thread scheduler. Time sharding is the process of allocating available CPU time to available Runnable threads. CPU time can be allocated based on thread priority or the amount of time a thread waits. Thread scheduling is not controlled by the Java VIRTUAL Machine, so it is better for the application to control it (that is, don’t make your program dependent on thread priority).

What is spin

A lot of synchronized code is just some very simple code, the execution time is very fast, in this case, the waiting thread locking may not be a worthwhile operation, because thread blocking involves user state and kernel state switch issues. Since synchronized code executes so fast, it’s a good idea not to block a thread waiting for a lock, but to do a busy loop at synchronized’s boundary, which is known as spin. It may be a better strategy to block if you do several busy cycles and find that the lock has not been acquired.

Concurrency Is the Java Concurrency API. What is the Lock interface? What are the advantages over synchronization?

The Lock interface provides a more extensible locking operation than synchronized methods and synchronized blocks. They allow for more flexible structures that can have radically different properties, and can support conditional objects of multiple related classes.

Its advantages include:

(1) Can make the lock more fair

(2) The thread can respond to the interrupt while waiting for the lock

(3) You can have the thread attempt to acquire the lock and either return immediately or wait for a period of time if it cannot

(4) Locks can be acquired and released in different order in different ranges

Singleton thread safety

The threadbare issue is that singleton thread-safety means that instances of a class can only be created once in a multithreaded environment. There are several ways to write the singleton pattern, so LET me summarize:

(1) Writing method of Hunhan-style singleton pattern: thread safety

(2) Lazy singleton writing: not thread-safe

(3) Double lock singleton mode writing: thread safety

44. What does Semaphore do

A Semaphore is a Semaphore that limits the number of concurrent requests for a block of code. Semaphore has a constructor that passes in an integer of type n to indicate that a piece of code can be accessed by at most n threads. If more than n is passed, wait until one thread finishes executing the block before the next thread enters. If the Semaphore constructor passes an int n=1, it becomes synchronized.

Executors: What are they?

Executors provide tools and methods for Executor, ExecutorService, ScheduledExecutorService, ThreadFactory, and Callable classes.

Executors can be used to easily create thread pools

46. Which thread calls the static block constructor of a thread class is a tricky and tricky question.

Remember: the thread constructor, the static block, is called by the thread in which the new thread belongs, whereas the code in the run method is called by the thread itself. For example, if Thread1 is new in Thread2 and Thread2 is new in main, then:

Thread2’s constructor, static block, is called by the main thread, and Thread2’s run() method is called by Thread2 itself

(2) The constructor, static block, of Thread1 is called by Thread2, and the run() method of Thread1 is called by Thread1

Which is the better choice, synchronous method or synchronous block?

Synchronized blocks, which means that code outside the synchronized block is executed asynchronously, which is more efficient than synchronizing the entire method. As a rule of thumb, the smaller the scope of synchronization, the better.

48, What is the exception caused by too many Java threads?

(1) Thread lifecycle overhead is very high

(2) Excessive CPU resources are consumed

If the number of runnable threads exceeds the number of available processors, threads will be idle. A large number of idle threads can take up a lot of memory, strain the garbage collector, and there are other performance costs associated with a large number of threads competing for CPU resources.

(3) Reduce stability

The JVM has a limit on the number of threads that can be created. This limit varies from platform to platform and is subject to several factors, including the JVM’s startup parameters, the size of the request stack in the Thread constructor, and Thread restrictions imposed by the underlying operating system. If these restrictions are broken, an OutOfMemoryError may be thrown.