- What is Thread in Java?
- Threads are basically the lightweight and smallest unit of processing that can be managed independently by a scheduler.
- Threads are referred to as parts of a process that simply let a program execute efficiently with other parts or threads of the process at the same time.
- Using threads, one can perform complicated tasks in the easiest way.
- It is considered the simplest way to take advantage of multiple CPUs available in a machine. They share the common address space and are independent of each other.
- What are the benefits of using Multithreading?
- Allow the program to run continuously even if a part of it is blocked.
- Improve performance as compared to traditional parallel programs that use multiple processes.
- Allows writing effective programs that utilize maximum CPU time Improves the responsiveness of complex applications or programs.
- Increase use of CPU resources and reduce costs of maintenance.
- Saves time and parallelism tasks.
- If an exception occurs in a single thread, it will not affect other threads as threads are independent.
- Less resource-intensive than executing multiple processes at the same time.
- What's the difference between thread and process?
- What's the difference between the User thread and the Daemon thread?
- User Thread (Non-Daemon Thread):
- In Java, user threads have a specific life cycle and their life is independent of any other thread.
- JVM (Java Virtual Machine) waits for any of the user threads to complete its tasks before terminating it.
- When user threads are finished, JVM terminates the whole program along with associated daemon threads.
- Daemon Thread:
- In Java, daemon threads are basically referred to as a service provider that provides services and support to user threads.
- There are basically two methods available in thread class for daemon thread: setDaemon() and isDaemon().
- How can we create daemon threads?
- We can create daemon threads in java using the thread class setDaemon(true).
- It is used to mark the current thread as daemon thread or user thread.
- isDaemon() method is generally used to check whether the current thread is daemon or not.
- If the thread is a daemon, it will return true otherwise it returns false.
- What is Runnable and Callable Interface? Write the difference between them.
- Explain thread pool
- A Thread pool is simply a collection of pre-initialized or worker threads at the start-up that can be used to execute tasks and put back in the pool when completed.
- It is referred to as pool threads in which a group of fixed-size threads is created.
- By reducing the number of application threads and managing their lifecycle, one can mitigate the issue of performance using a thread pool.
- Using threads, performance can be enhanced and better system stability can occur. To create the thread pools, java.util.concurrent.Executors class usually provides factory methods.
- What’s the purpose of the join() method?
- join() method is generally used to pause the execution of a current thread unless and until the specified thread on which join is called is dead or completed.
- To stop a thread from running until another thread gets ended, this method can be used. It joins the start of a thread execution to the end of another thread’s execution.
- It is considered the final method of a thread class.
- What do you mean by garbage collection?
- Garbage collection is basically a process of managing memory automatically.
- It uses several GC algorithms among which the popular one includes Mark and Sweep.
- The process includes three phases i.e., marking, deletion, and compaction/copying.
- In simple words, a garbage collector finds objects that are no longer required by the program and then delete or remove these unused objects to free up the memory space.
- How do threads communicate with each other?
- Threads can communicate using three methods i.e., wait(), notify(), and notifyAll().
- What is the synchronization process? Why use it?
- Synchronization is basically a process in java that enables a simple strategy for avoiding thread interference and memory consistency errors.
- This process makes sure that resources will be only used one thread at a time when one thread tries to access a shared resource.
- It can be achieved in three different ways as given below:
- By the synchronized method
- By synchronized block
- By static synchronization
- What are synchronized methods and synchronized blocks? Which one should be preferred?
- Synchronized Method:
- In this method, the thread acquires a lock on the object when they enter the synchronized method and releases the lock either normally or by throwing an exception when they leave the method.
- No other thread can use the whole method unless and until the current thread finishes its execution and release the lock.
- It can be used when one wants to lock on the entire functionality of a particular method.
- Synchronized Block:
- In this method, the thread acquires a lock on the object between parentheses after the synchronized keyword and releases the lock when they leave the block.
- No other thread can acquire a lock on the locked object unless and until the synchronized block exists.
- It can be used when one wants to keep other parts of the programs accessible to other threads.
- Synchronized blocks should be preferred more as it boosts the performance of a particular program. It only locks a certain part of the program (critical section) rather than the entire method and therefore leads to less contention
- Can you start a thread twice?
- No, it's not at all possible to restart a thread once a thread gets started and completes its execution.
- Thread only runs once and if you try to run it for a second time, then it will throw a runtime exception i.e., java.lang.IllegalThreadStateException.
- What do you mean by inter-thread communication?
- As the name suggests, inter-thread communication is a process or mechanism using which multiple threads can communicate with each other.
- It is especially used to avoid thread polling in java and can be obtained using wait(), notify(), and notifyAll() methods.
- What is Thread Scheduler and Time Slicing?
- Thread Scheduler:
- It is a component of JVM that is used to decide which thread will execute next if multiple threads are waiting to get the chance of execution.
- By looking at the priority assigned to each thread that is READY, the thread scheduler selects the next run to execute.
- To schedule the threads, it mainly uses two mechanisms: Preemptive Scheduling and Time slicing scheduling.
- Time Slicing:
- It is especially used to divide CPU time and allocate them to active threads.
- In this, each thread will get a predefined slice of time to execute.
- When the time expires, a particular thread has to wait till other threads get their chances to use their time in a round-robin fashion.
- Every running thread will get executed for a fixed time period.
- Explain thread priority
- Thread priority simply means that threads with the highest priority will get a chance for execution prior to low-priority threads.
- One can specify the priority but it's not necessary that the highest priority thread will get executed before the lower-priority thread.
- Thread scheduler assigns processor to thread on the basis of thread priority.
- The range of priority changes between 1-10 from lowest priority to highest priority.
- Here 3 constants are defined in it namely as follows:
- public static int NORM_PRIORITY
- public static int MIN_PRIORITY
- public static int MAX_PRIORITY
- What is the task of the main thread?
- All Java programs have at least one thread, known as the main thread which is created by JVM at the program start when the main() method is invoked with the main thread.
- How to set the name of the thread?
- We can name a thread by using a method been already up there known as setName() replacing default naming which was ‘Thread-0’, ‘Thread-1’, and so on.
| Thread | Process |
|---|---|
| It is a subset of a subunit of a process. | It is a program in execution containing multiple threads. |
| In this, inter-thread communication is faster, less expensive, easy, and efficient because threads share the same memory address of the process they belong to. | In this, inter-process communication is slower, expensive, and complex because each process has different memory space or address., |
| These are easier to create, lightweight, and have less overhead. | These are difficult to create, heavyweight, and have more overhead. |
| It requires less time for creation, termination, and context switching. | It requires more time for creation, termination, and context switching. |
| Processes with multiple threads use fewer resources. | Processes without threads use more resources. |
| Threads are parts of a process, so they are dependent on each other but each thread executes independently. | Processes are independent of each other. |
| There is a need for synchronization in threads to avoid unexpected scenarios or problems. | There is no need for synchronization in each process. |
| User Thread | Daemon thread |
|---|---|
| JVM waits for user threads to finish their tasks before termination. | JVM does not wait for daemon threads to finish their tasks before termination. |
| These threads are normally created by the user for executing tasks concurrently. | These threads are normally created by JVM. |
| They are used for critical tasks or core work of an application. | They are not used for any critical tasks but to do some supporting tasks. |
| These threads are referred to as high-priority tasks, therefore are required for running in the foreground. | These threads are referred to as low priority threads, therefore are especially required for supporting background tasks like garbage collection, releasing the memory of unused objects, etc. |
| Runnable Interface | Callable Interface |
|---|---|
| It does not return any result and therefore, cannot throw a checked exception. | It returns a result and therefore, can throw an exception. |
| It cannot be passed to invokeAll method. | It can be passed to invokeAll method. |
| It was introduced in JDK 1.0. | It was introduced in JDK 5.0, so one cannot use it before Java 5. |
| It simply belongs to Java.lang. | It simply belongs to java.util.concurrent. |
| It uses the run() method to define a task. | It uses the call() method to define a task. |
| To use this interface, one needs to override the run() method. | To use this interface, one needs to override the call() method. |