Java Multithreading and Concurrency basics interview questions and Answers
Original link: http://ifeve.com/java-multi-threading-concurrency-interview-questions-with-answers/
Multithreading and concurrency issues are among the questions that interviewers prefer to ask in a Java technology interview. Here, the most important questions are listed from the interview point of view, but you should still have a solid grasp of the basics of Java multithreading to match the problems you encounter later. ( proof Note: Very much agree with this view )Java Multithreading interview question 1. What is the difference between a process and a thread?
A process is a standalone (self contained) operating environment that can be viewed as a program or an application. A thread is a task that executes in a process. The Java Runtime environment is a single process that contains different classes and programs. Threads can be called lightweight processes. Threads require fewer resources to create and reside in a process, and can share resources in a process.2. What are the benefits of multithreaded programming?
In multithreaded programs, multiple threads are executed concurrently to improve the efficiency of the program, and the CPU does not go idle because a thread needs to wait for resources. Multiple threads share heap memory, so creating multiple threads to perform some tasks is better than creating multiple processes. For example, Servlets is better than CGI because Servlets supports multithreading and CGI does not support it.3. What is the difference between a user thread and a daemon thread?
When we create a thread in a Java program, it is called a user thread. A daemon thread is a thread that executes in the background and does not prevent the JVM from terminating. When no user thread is running, the JVM shuts down the program and exits. A daemon thread creates a child thread that is still a daemon thread.4. How do we create a thread?
There are two ways to create a thread: one is to implement the Runnable interface, then pass it to the constructor of thread, create a thread object, and inherit the thread class directly. To learn more, read this article on how to create threads in Java.5. What are the different thread lifecycles?
When we create a new thread in a Java program, its state is new. when we call the thread's start () method, the state is changed to Runnable. The thread scheduler allocates CPU time to threads in the Runnable thread pool and says their state changes to Running. Other thread states also have waiting,blocked and Dead. Read this article to learn more about the thread life cycle.6. Can I call the run () method of the thread class directly?
Sure, but if we call the thread's run () method, it behaves like a normal method, and in order to execute our code in a new thread, the Thread.Start () method must be used.7. How do I get a running thread to pause for a while?
We can use the sleep () method of the thread class to suspend a thread for a while. It is important to note that this does not cause the thread to terminate, and once the thread is awakened from hibernation, the state of the thread will be changed to Runnable, and it will be executed according to the thread dispatch.8. What is your understanding of thread priorities?
Each thread has a priority, in general, a high-priority thread will have priority at run time, but this depends on the implementation of the thread schedule, which is operating system-related (OS dependent). We can define the priority of threads, but this does not guarantee that high-priority threads will be executed before the low-priority thread. The thread priority is an int variable (from 1-10), 1 represents the lowest priority, and 10 represents the highest priority.9. What is thread Scheduler (threads Scheduler) and time slicing?
The thread scheduler is an operating system service that is responsible for allocating CPU time to threads in the Runnable state. Once we create a thread and start it, its execution depends on the implementation of the thread scheduler. Time sharding refers to the process of allocating available CPU time to available Runnable threads. The allocated CPU time can be based on the thread priority or the time the thread waits. Thread scheduling is not controlled by the Java Virtual machine, so it is better to control it by the application (i.e. don't let your program depend on the priority of the thread).10. What is context switching (context-switching) in multi-threading?
Context switching is the process of storing and recovering CPU state, which enables thread execution to resume execution from a breakpoint. Context switching is a fundamental feature of multitasking operating systems and multithreaded environments.11. How do you make sure that the thread on which the main () method resides is the last thread that the Java program ends?
We can use the joint () method of the thread class to ensure that all program-created threads end before the main () method exits. Here is an article about the joint () method of the thread class.12. How are the threads communicating?
When resources are shared between threads, inter-thread communication is an important means of reconciling them. The Wait () \notify () \notifyall () method in the object class can be used to communicate between threads about the state of a lock on a resource. Click here for more on thread wait, notify and Notifyall.13. Why is the thread communication method Wait (), notify (), and notifyall () defined in the object class?
Every object in Java has a lock (monitor, can also be a monitor) and wait (), notify (), and so on to wait for the object's lock or to notify other thread objects that the monitor is available. There are no locks and synchronizers available for any object in Java threads. That's why these methods are part of the object class, so that every class in Java has a basic method for inter-thread communication14. Why wait (), notify (), and Notifyall () must be called in the synchronization method or in the synchronization block?
When a thread needs to invoke the object's Wait () method, the thread must have a lock on the object, and then it will release the object lock and enter the wait state until the other thread calls the Notify () method on the object. Similarly, when a thread needs to invoke the object's notify () method, it releases the lock on the object so that other waiting threads can get the object lock. Since all of these methods require a thread to hold the lock on the object, this can only be done by synchronization, so they can only be called in a synchronous method or in a synchronous block.15. Why is the sleep () and yield () method of the thread class static?
The sleep () and yield () methods of the thread class will run on the currently executing thread. So it makes no sense to raise these methods on other waiting threads. That's why these methods are static. They can work in the currently executing thread and prevent programmers from mistakenly thinking that these methods can be called on other non-running threads.16. How to ensure thread safety?
There are many ways to ensure thread safety in Java-synchronization, using atomic classes (atomic concurrent classes), implementing concurrent locks, using the volatile keyword, and using immutable classes and thread-safe classes. You can learn more in the thread safety tutorial.How does the volatile keyword work in Java?
When we use the volatile keyword to modify a variable, the thread will read the variable directly and not cache it. This ensures that the variables read by the thread are consistent with the memory.18. What is the better choice for synchronous and synchronous blocks?
Synchronizing a block is a better choice because it does not lock the entire object (you can, of course, lock the entire object). The synchronization method locks the entire object, even if there are multiple unrelated synchronization blocks in the class, which usually causes them to stop executing and to wait for a lock on the object.19. How do I create a daemon thread?
Using the Setdaemon (true) method of the thread class to set the thread as the daemon thread, it is important to note that this method needs to be called before the start () method is called, or the illegalthreadstateexception exception will be thrown.20. What is Threadlocal?
Threadlocal is used to create local variables for threads, we know that all threads of an object share its global variables, so these variables are not thread-safe and we can use synchronous technology. But when we don't want to use synchronization, we can choose the threadlocal variable.
Each thread will have their own thread variable, which can use the Get () \set () method to get their default values or change their values inside the thread. Threadlocal instances are typically the private static property that you want them to associate with the thread state. In the threadlocal example this article you can see a little program about threadlocal.21. What is the thread Group? Why not recommend using it?
Threadgroup is a class whose purpose is to provide information about thread groups.
The Threadgroup API is weak, and it does not provide more functionality than thread. It has two main functions: one is to get the list of active threads in the thread group, and the other is to set the uncaught exception handler (Ncaught exception handler) to the thread setting. But in Java 1.5 The thread class also added the setuncaughtexceptionhandler (Uncaughtexceptionhandler eh) method, so Threadgroup is obsolete, Continued use is not recommended.?
A thread dump is a list of JVM active threads, which is useful for parsing system bottlenecks and deadlocks. There are many ways to get a thread dump--using the profiler,kill-3 command, Jstack tools, and so on. I prefer the Jstack tool because it is easy to use and comes with a JDK. Since it is a terminal-based tool, we can write some scripts to generate thread dumps periodically for analysis. Read this document to learn more about generating thread dumps.23. What is a deadlock (Deadlock)? How do I analyze and avoid deadlocks?
Deadlocks are situations in which more than two threads are permanently blocked, which results in a minimum of two threads and more than two resources.
Parsing deadlocks, we need to look at thread dumps for Java applications. We need to identify the threads that are blocked and the resources they wait for. Each resource has a unique ID, which we can use to find out which threads already have their object locks.
Avoid nested locks, use locks only where needed, and avoid waiting indefinitely is the usual way to avoid deadlocks, read this article to learn how to analyze deadlocks.24. What is the Java Timer class? How do I create a task with a specific time interval?
Java.util.Timer is a tool class that can be used to schedule a thread to execute at a specific time in the future. The timer class can be used to schedule one-time tasks or periodic tasks.
Java.util.TimerTask is an abstract class that implements the Runnable interface, and we need to inherit the class to create our own timed task and use the timer to schedule its execution.
Here's an example of a Java timer.25. What is a thread pool? How do I create a Java thread pool?
A thread pool manages a set of worker threads, and it also includes a queue that is used to place tasks that are waiting to be executed.
Java.util.concurrent.Executors provides an implementation of the Java.util.concurrent.Executor interface for creating a thread pool. The thread pool example shows how to create and use a thread pool, or read the Scheduledthreadpoolexecutor example to learn how to create a periodic task.Java concurrency interview question 1. What is atomic manipulation? What are the atomic classes (atomic classes) in the Java Concurrency API?
An atomic operation is an operation task unit that is not affected by other operations. Atomic manipulation is a necessary means of avoiding data inconsistency in a multithreaded environment.
Int++ is not an atomic operation, so when one thread reads its value and adds 1 o'clock, another thread may read the previous value, which raises an error.
In order to solve this problem, it is necessary to ensure that the increment operation is atomic, and we can use synchronous technology to do this before JDK1.5. To the Jdk1.5,java.util.concurrent.atomic package provides an int and a long type of class, which can be automatically guaranteed to be atomic for their operations and do not require synchronous use. You can read this article to learn about Java's Atomic class.2. What is the lock interface (lock interface) in the Java Concurrency API? What are the advantages of comparing synchronization?
The lock interface provides a more scalable lock operation than synchronous methods and synchronization blocks. They allow more flexible structures, can have completely different properties, and can support multiple related classes of conditional objects.
It has the following advantages:
Read more about the lock example3. What is the executors framework?
The Executor framework is introduced in Java 5 with the Java.util.concurrent.Executor interface. The executor framework is a framework for invoking, dispatching, executing, and controlling asynchronous tasks based on a set of execution policies.
Unlimited creation of threads can cause application memory overflow. So creating a thread pool is a better solution because you can limit the number of threads and recycle those threads. Using the executors framework makes it very easy to create a thread pool, read this article to learn how to use the executor framework to create a pooling of threads.4. What is a blocking queue? How do I use a blocking queue to implement a producer-consumer model?
The Java.util.concurrent.BlockingQueue feature is that when the queue is empty, the operation to get or delete elements from the queue is blocked, or when the queue is full, the operation to add elements to the queue is blocked.
The blocking queue does not accept null values, and when you try to add null values to the queue, it throws nullpointerexception.
The implementation of the blocking queue is thread-safe, and all query methods are atomic and use internal locks or other forms of concurrency control.
The Blockingqueue interface is part of the Java Collections Framework and is primarily used to implement producer-consumer issues.
Read this article to learn how to use a blocking queue to implement producer-consumer issues.5. What is callable and future?
Java 5 introduces the Java.util.concurrent.Callable interface in the concurrency package, which is similar to the Runnable interface, but it can return an object or throw an exception.
The callable interface uses generics to define its return type. The Executors class provides some useful ways to perform tasks within a callable in a thread pool. Since the callable task is parallel, we must wait for it to return the result. The Java.util.concurrent.Future object solves this problem for us. After the online pool submits the callable task, a future object is returned, using which we can know the status of the callable task and get the result of the execution callable returned. The future provides a get () method so that we can wait for callable to end and get its execution results.
Read this article to learn more about the callable,future example.6. What is Futuretask?
Futuretask is a fundamental implementation of the future, and we can use it with executors to handle asynchronous tasks. Usually we do not need to use the Futuretask class, it becomes very useful when we intend to rewrite some methods of the future interface and keep the original base implementation. We can just inherit from it and rewrite the methods we need. Read the Java futuretask example to learn how to use it.7. What is the implementation of concurrent containers?
Java collection classes are fast failures, which means that when a collection is changed and a thread iterates through the collection using Iterators, the next () method of the iterator throws a Concurrentmodificationexception exception.
Concurrent containers support concurrent traversal and concurrent updates.
The main classes are Concurrenthashmap, copyonwritearraylist and Copyonwritearrayset, read this article to learn how to avoid concurrentmodificationexception.8. What is the Executors class?
Executors provides some tool methods for the Executor,executorservice,scheduledexecutorservice,threadfactory and callable classes.
Executors can be used for convenient creation of thread pools9. Why is it that Concurrenthashmap is weak and consistent? And why is concurrentmodificationexception not reported when multiple threads modify Concurrenthashmap concurrently?
Java Multithreading and Concurrency basics interview questions and Answers