Java Multithreading and Concurrency basics interview questions and Answers

Source: Internet
Author: User
Tags thread class unique id concurrentmodificationexception

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 communication

14. 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 is it recommended to use 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.

12345678 t1.setUncaughtExceptionHandler(newUncaughtExceptionHandler(){ @Overridepublic void uncaughtException(Thread t, Throwable e) {System.out.println("exception occured:"+e.getMessage());}});
22. What is a Java thread dump (thread dump) and how do I get it?

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:

    • Can make the lock more fair
    • Allows threads to respond to interrupts while waiting for a lock
    • Allows a thread to attempt to acquire a lock and return immediately or wait for a period of time when the lock cannot be acquired
    • Locks can be acquired and released in different order in different ranges

Read more about the lock example

3. 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 to create a thread pool conveniently.

15 Java Multi-threaded face questions

Multithreading and concurrency issues are an essential part of any Java interview. If you want to get the front desk information for any stock investment bank, you should prepare a lot of questions about multithreading. Multithreading and concurrency are a very popular topic in the investment banking business, especially in the development of electronic transactions. They will ask the interviewer many confusing Java threading issues. The interviewer just wants to make sure that the interviewer has enough knowledge of Java threading and concurrency, because many of the candidates are floating on the surface. High-capacity and low-latency electronic trading systems for direct market-oriented trading are inherently concurrent. Here are some Java threading issues I like to ask at different times and locations. I did not provide the answer, but whenever possible I will give you clues, sometimes these clues enough to answer the question. There is an increasing number of problems referring to JAVA5 and the contract for concurrent tools and concurrent collections. The threadlocal, Blocking Queue, counting semaphore and Concurrenthashmap are popular among those issues.

15 Java Multithreading questions and answers

1) Now there are T1, T2, T3 three threads, how do you ensure that the T2 after the T1 execution, T3 after the implementation of T2 execution?

This thread problem is usually asked during the first or phone interview phase to detect whether you are familiar with the join method. This multithreading problem is relatively simple and can be implemented using the Join method.

2) What are the advantages of the lock interface in Java than the synchronized block? You need to implement an efficient cache that allows multiple users to read, but only one user is allowed to write in order to maintain its integrity, how will you implement it?

The biggest advantage of the lock interface in multi-threaded and concurrent programming is that they provide a lock for both read and write, which satisfies high-performance data structures and conditional blocking that you write like Concurrenthashmap. The question of a Java thread interview is increasingly based on the interviewer's answer. I strongly recommend that you read locks carefully before you go to a multi-threaded interview, as it is currently heavily used to build the client cache and transaction connection space for the electronic trading final.

3) What is the difference between the wait and sleep methods in Java?

Frequently asked questions about a Java thread interview in a phone interview. The biggest difference is that wait waits for the lock to be released while sleep holds the lock. Wait is typically used for inter-thread interaction, and sleep is typically used to pause execution.

4) block queues with Java implementation.

This is a relatively difficult multi-threaded interview problem, it can achieve a lot of purposes. First, it can detect whether the candidate can actually write programs with Java threads, and second, can detect the candidate's understanding of the concurrency scenario, and you can ask many questions according to this. If he uses the Wait () and notify () methods to implement the blocking queue, you can ask him to write again with the concurrency class in the latest Java 5.

5) Write code in Java to solve producer-consumer problems.

Similar to the question above, but the problem is more classic, sometimes the interview will ask the following questions. How to solve the producer-consumer problem in Java, of course there are a lot of solutions, I have shared a blocking queue implementation method. Sometimes they even ask how to make the Philosopher's meal a problem.

6) How will you solve a program that will lead to deadlocks in Java?

This is my favorite Java thread interview problem, because even deadlock problems are common when writing multithreaded concurrent programs, but many candidates are not able to write deadlock free code (no deadlock codes?). ), they struggled. Just tell them that you have n resources and n threads, and you need all the resources to complete an operation. For the sake of simplicity here the n can be replaced with 2, and the larger the data will make the problem look more complicated. Get more information about deadlocks by avoiding deadlocks in Java.

7) What is atomic manipulation and what is atomic manipulation in Java?

A very simple Java thread interview problem, the next problem is that you need to synchronize an atomic operation.

8) What is the key to volatile in Java? How to use it? How does it differ from the synchronized method in Java?

Thread issues based on volatile keywords have become more prevalent since the Java 5 and Java memory models have changed. Be prepared to answer questions about how volatile variables ensure visibility, sequencing, and consistency in a concurrency environment.

9) What are the competitive conditions? How do you find and solve competition?

This is an issue that appears in the advanced stages of a multithreaded interview. Most interviewers will ask about the competitive conditions you've met recently and how you've solved them. Some time they will write simple code, and then let you detect the code's competitive conditions. You can refer to the article I published earlier about the Java competition criteria. In my opinion this is one of the best Java thread interview questions that can be used to accurately detect candidates ' experience in solving competitive conditions, or writing code which is free of data race or any other race condition. The best book on this is "Concurrency practices in Java".

10) How will you use thread dump? How would you analyze thread dump?

In Unix you can use kill-3, then thread dump will print the log and you can use "Ctrl+break" in Windows. Very simple and professional thread interview questions, but if he asks you how to analyze it, it will be tricky.

11) Why do we not call the run () method directly when we call the start () method?

This is another very classic Java multithreading interview problem. It was also a puzzle when I first started writing a thread. Now this question is usually asked in the first round of a phone interview or in the middle of a junior Java interview. The answer to this question should be that when you call the start () method you will create a new thread and execute the code in the Run () method. But if you call the run () method directly, it does not create a new thread and does not execute code that invokes the thread. Read the "Start and run method differences" Article I wrote earlier to get more information.

How do you wake up a blocked thread in Java?

This is a tricky problem with threading and blocking, and it has a lot of workarounds. If the thread encounters IO blocking, I do not think there is a way to abort the thread. If the thread is blocking because of a call to wait (), sleep (), or the Join () method, you can break thread and wake it up by throwing interruptedexception. I've written earlier how to deal with blocking methods in Java has a lot of information about handling thread blocking.

13) What is the difference between Cyclibarriar and Countdownlatch in Java?

This threading problem is primarily used to detect if you are familiar with the concurrent packages in JDK5. The difference between the two is that cyclicbarrier can reuse the barriers that have been passed, while Countdownlatch cannot be reused.

14) What is an immutable object and how does it help with writing concurrent applications?

Another multithreaded classic interview problem is not directly related to threads, but indirectly helps a lot. This Java interview problem can be tricky, if he asks you to write an immutable object, or asks you why the string is immutable.

15) What are the common problems you encounter in a multithreaded environment? How did you deal with it?

Memory-interface, race conditions, deadlocks, live locks, and starvation are often encountered in multithreaded and concurrent programs. The problem is endless, and if you get it wrong, it will be hard to find and debug. This is most of the interview-based, not the actual application-based Java threading problem.

A few additional questions to add:

    • 1) What is the difference between a green thread and a local thread in Java?
    • 2) What is the difference between threads and processes?
    • 3) What is context switching in multi-threading?
    • 4) What is the difference between a deadlock and a live lock, the difference between a deadlock and a pie?
    • 5) What is the thread scheduling algorithm used in Java?
    • 6) What is thread scheduling in Java?
    • 7) How do you handle non-catching exceptions in the thread?
    • 8) What is a thread group and why is it not recommended in Java?
    • 9) Why is it better to use the executor framework than to create and manage threads with apps?
    • 10) What is the difference between executor and executors in Java?
    • 11) How do I find which thread is using the longest CPU time on Windows and Linux?

Java Multithreading and Concurrency basics interview questions and Answers

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.