Java Multithreading and Concurrency basics interview questions and Answers

Source: Internet
Author: User
Tags thread class

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.

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

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.

What are the different thread life cycles?
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.

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.

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.

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.

What is thread scheduler and time shards?
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).

In multi-threading, what is context switching?
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.

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.

How do I 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 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.

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.

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. The executors framework makes it very easy to create a thread pool.

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.

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.

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.

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.

Java Multithreading and Concurrency basics interview questions and Answers

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.