Java Multithreading and concurrent basic interview questions and Answers (translation) _java

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

Java Multithreaded interview questions

1. What is the difference between processes and threads?

A process is a stand-alone (self contained) operating environment that can be viewed as a program or an application. A thread is a task that is performed 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 processes, and can share resources in the process.

2. What are the benefits of multithreaded programming?

In multithreaded programs, multiple threads are executed concurrently to increase the efficiency of the program, and the CPU does not get idle because a thread needs to wait for resources. Multiple threads share heap memory (heap memory), so it is better to create multiple threads to perform some tasks than to create multiple processes. For example, Servlets is better than CGI because Servlets supports multithreading and CGI doesn't support it.

3. What is the difference between a user thread and a daemon?

When we create a thread in a Java program, it is called a user thread. A daemon is a thread that executes in the background and does not prevent the JVM from terminating. When no user thread is running, the JVM closes the program and exits. A child thread created by a daemon thread 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 thread's constructor, create a thread object, and second, directly inherit the thread class. For more information, read this article about 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 for threads in the runnable thread pool and says their state changes to running. Other thread states are waiting,blocked and dead. Read this article to learn more about the thread lifecycle.

6. Can I call the run () method of the thread class directly?

Sure, but if we call the thread's run () method, it behaves just like a normal method, and you must use the Thread.Start () method to execute our code in a new thread.

7. How do I suspend a running thread for a period of time?

We can use the sleep () method of the thread class to suspend a thread for a period of time. It should be noted that this does not cause the thread to terminate, and once the thread is awakened from hibernation, the thread's state will be changed to runnable, and it will be executed according to the thread schedule.

8. What is your understanding of thread priority?

Each thread is prioritized and, in general, a high-priority thread has precedence at run time, but this relies on the implementation of the thread schedule, which is related to the operating system (OS dependent). We can define the priority of the thread, 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 the 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 relies on the implementation of the thread scheduler. Time slicing refers to the process of allocating available CPU time to an available runnable thread. The allocation of CPU time can be based on thread priority or time that the thread waits. Thread scheduling is not controlled by the Java Virtual machine, so it is a better choice for the application to control it (that is, don't let your program rely on the priority of the thread).

10. What is context switching (context-switching) in multiple threads?

Context switching is the process of storing and recovering a CPU state that enables thread execution to resume execution from a breakpoint. Context switching is a basic feature of multitasking operating systems and multithreaded environments.

11. How do you make sure that the main () method is in the same thread as the end of the Java program?

We can use the joint () method of the thread class to ensure that threads created by all programs end before the main () method exits. Here is an article about the joint () method of the thread class.

12. How do threads communicate with each other?

When a resource is shared between threads, communication between threads is an important means of reconciling them. The Wait () \notify () \notifyall () method in the object class can be used to communicate the state of a lock on a resource between threads. 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?

Each of the objects in Java has a lock (monitor, also can be monitors) and wait (), notify (), etc. are used for waiting for the lock on the object or for notifying the other thread object that the monitor is available. There is no lock and Synchronizer available for any object in the Java thread. That's why these methods are part of the object class, so that every class in Java has a basic method for communicating between threads

14. Why wait (), notify () and Notifyall () must be called in the Sync method or in the sync block?

When a thread needs to invoke the object's Wait () method, the thread must have a lock on the object, and then it releases the object lock and goes into the waiting state until the other thread calls the Notify () method on the object. Similarly, when a thread needs to invoke the Notify () method of an object, it releases the lock on the object so that other waiting threads can get the object lock. Because all of these methods require that the thread hold the lock of the object so that it can only be implemented through synchronization, they can only be invoked in the synchronization method or in the synchronization 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 increase the use of these methods in other wait-state threads. That's why these methods are static. They can work in the currently executing thread and avoid the programmer's mistaken belief that these methods can be invoked on other non-running threads.

16. How do I ensure thread safety?

There are many ways in Java to ensure thread safety--synchronization, using atomic classes (atomic concurrent classes), implementing concurrent locks, using the volatile keyword, and using invariant classes and thread-safe classes. You can learn more in the thread safety tutorial.

What is the role of the volatile keyword 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 in memory.

18. Sync method and sync block, which is the better choice?

The sync block is a better choice because it doesn't lock the entire object (you can also lock the whole object). The synchronization method locks the entire object, even though there are multiple unrelated synchronization blocks in the class, which usually cause them to stop executing and need to wait for the lock on the object.

19. How do I create a daemon thread?

Using the Setdaemon (true) method of the thread class to set a thread as a daemon, it should be noted that this method is called before the start () method is called, otherwise a Illegalthreadstateexception exception is thrown.

20. What is Threadlocal?

Threadlocal is used to create a local variable for a thread, we know that all threads of an object share its global variables, so these variables are not thread safe and we can use synchronization techniques. But when we don't want to use synchronization, we can choose the threadlocal variable.

Each thread has its own thread variable, which can use the Get () \set () method to obtain their default values or change their values within a thread. Threadlocal instances are typically expected to be associated with thread state as private static properties. In the threadlocal example this article you can see a small program about threadlocal.

21. What is thread Group? Why do you recommend using it?

Threadgroup is a class that is designed to provide information about the thread group.

The Threadgroup API is relatively weak and does not provide more functionality than thread. It has two main functions: one is to get a list of threads that are active in a thread group, and the other is to set up a thread without catching an exception handler (Ncaught exception handler). However, the thread class also adds the Setuncaughtexceptionhandler (Uncaughtexceptionhandler eh) method in Java 1.5, so threadgroup is obsolete and is not recommended for continued use.

T1.setuncaughtexceptionhandler (New Uncaughtexceptionhandler () {
 
@Override public
void Uncaughtexception ( Thread T, Throwable e) {
System.out.println ("Exception occured:" +e.getmessage ());
}
 
});
 

22. What is a Java thread dump (thread dump), how do I get it?

A thread dump is a list of JVM active threads that are useful for analyzing system bottlenecks and deadlocks. There are many ways to get a thread dump-using the profiler,kill-3 command, the Jstack tool, and so on. I prefer the Jstack tool because it is easy to use and is the JDK's own. Since it is a terminal based tool, we can write some scripts to periodically generate thread dumps for analysis. Read this document to learn more about generating thread dumps.

23. What is a deadlock (deadlock)? How to analyze and avoid deadlocks?

A deadlock is a situation in which more than two threads are permanently blocked, which results in a minimum of two threads and more than two resources.

To analyze deadlocks, we need to look at the thread dumps for the Java application. We need to find those threads with blocked status and the resources they wait for. Each resource has a unique ID, and with this ID we can find out which threads already have its object lock.

Avoiding nested locks, using locks only where needed and avoiding indefinite waiting is the usual way to avoid deadlocks, read this article to learn how to analyze deadlocks.

24. What is a Java timer class? How do I create a task that has 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 scheduled with a one-time task or a cycle task.

Java.util.TimerTask is an abstract class that implements the Runnable interface, and we need to inherit this class to create our own timed tasks and use a 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 for placing tasks waiting to be performed.

Java.util.concurrent.Executors provides an implementation of a Java.util.concurrent.Executor interface to create 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 cycle task.

Java Concurrent interview problem

1. What is atomic operation? What are the atomic classes (atomic classes) in the Java Concurrency API?

Atomic operation is an operational task unit that is not affected by other operations. Atomic operation is a necessary means to avoid 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 might read the previous value, which raises an error.

To solve this problem, it is necessary to ensure that the increase is atomic, and we can use synchronization technology to do this before JDK1.5. The jdk1.5,java.util.concurrent.atomic package provides int and long types of loading classes that automatically guarantee that their operations are atomic and do not need to use synchronization. You can read this article to learn about Java's atomic classes.

2. What is the lock interface (lock interface) in the Java concurrency API? Compare sync What's the advantage?

The lock interface provides a more extensible lock operation than the synchronization method and the synchronization block. They allow more flexible structures, can have completely different properties, and can support conditional objects for multiple related classes.

Its advantages are:

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

Read more examples of locks

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 asynchronous tasks that are invoked, dispatched, executed, and controlled according to a set of execution policies.

An unlimited creation thread can cause an application memory overflow. So creating a thread pool is a better solution because you can limit the number of threads and recycle the threads. The executors framework makes it easy to create a thread pool and read this article to learn how to use the executor framework to create one.

4. What is a blocking queue? How do I use blocking queues to implement a producer-consumer model?

The Java.util.concurrent.BlockingQueue feature is that when the queue is empty, fetching or deleting elements from the queue will be blocked, or the operation of adding elements to the queue will be blocked when the queue is full.

A blocking queue does not accept null values, and when you try to add a null value to the queue, it throws a 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, which is used primarily to implement producer-consumer issues.

Read this article to learn how to use blocking queues to implement producer-consumer issues.

5. What are 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 callable in the thread pool. Since the callable task is parallel, we have to wait for the result that it returns. The Java.util.concurrent.Future object solved the problem for us. The online pool submits the callable task and returns a future object that we can use to know the status of the callable task and the results of the execution callable return. Future provides a get () method that allows us to wait for the callable to finish and get its execution results.

Read this article for more examples of callable,future.

6. What is Futuretask?

Futuretask is a basic implementation of future, and we can use it with executors to handle asynchronous tasks. Usually we do not need to use the Futuretask class, and it becomes very useful when we intend to rewrite some of the methods of the future interface and maintain the original base implementation. We can just inherit from it and rewrite the methods we need. Read the Java Futuretask example and learn how to use it.

7. What is the implementation of concurrent containers?

Java collection classes are fast failures, which means that the next () method of the iterator throws a Concurrentmodificationexception exception when the collection is changed and a thread iterates through the collection using an iterator.

Concurrent containers support concurrent traversal and concurrent updates.

The main classes are Concurrenthashmap, copyonwritearraylist and Copyonwritearrayset, reading this article to learn how to avoid concurrentmodificationexception.

8. What is the Executors class?

Executors provides some tools for the executor,executorservice,scheduledexecutorservice,threadfactory and callable classes.

Executors can be used to facilitate the creation of a thread pool.

Original: journaldev.com: Ifeve Translator: Zheng Xudong

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.