Thread Interview Questions:-

  1. What is Thread in Java?

The thread is an independent path of execution. It's way to take advantage of multiple CPU available in a machine. By employing multiple threads you can speed up CPU bound task. For example, if one thread takes 100 milliseconds to do a job, you can use 10 thread to reduce that task into 10 milliseconds.

Java provides excellent support for multi-threading at the language level, and it's also one of the strong selling points.


  2. How do you implement Thread in Java?

At the language level, there are two ways to implement Thread in Java. An instance of java.lang.Thread represent a thread but it needs a task to execute, which is an instance of interface java.lang.Runnable.

Since Thread class itself implement Runnable, you can override run() method either by extending Thread class or just implementing Runnable interface. For detailed answer and discussion see this article.


  3. What is the difference between start() and run() method of Thread class?

When you call start() method, main thread internally calls run() method to start newly created Thread, so run() method is ultimately called by newly created thread.

When you call run() method main thread rather than starting run() method with newly thread it start run() method by itself.


  4. What is significance of using Volatile keyword?

Java allows threads to access shared variables. As a rule, to ensure that shared variables are consistently updated, a thread should ensure that it has exclusive use of such variables by obtaining a lock that enforces mutual exclusion for those shared variables.

If a field is declared volatile, in that case the Java memory model ensures that all threads see a consistent value for the variable.

NOTE:- (a). Can we have volatile methods in java?

No, volatile is only a keyword, can be used only with variables.

(b). Can we have synchronized variable in java?

No, synchronized can be used only with methods, i.e. in method declaration.


  5. Can you again start Thread?

We cannot start Thread again, doing so will throw runtimeException java.lang.IllegalThreadStateException. The reason is once run() method is executed by Thread, it goes into dead state.


  6. When threads are not lightweight process in java?

Threads are lightweight process only if threads of same process are executing concurrently. But if threads of different processes are executing concurrently then threads are heavy weight process.


  7. How can you say Thread behaviour is unpredictable?

The solution to question is quite simple, Thread behaviour is unpredictable because execution of Threads depends on Thread scheduler, thread scheduler may have different implementation on different platforms like windows, unix etc. Same threading program may produce different output in subsequent executions even on same platform.

To achieve we are going to create two threads on same Runnable Object, create for loop in run() method and start both threads. There is no surety that which threads will complete first, both threads will enter anonymously in for loop.


  8. What is difference between Process and Thread in java?

There are many differences between Thread and Process:-

Thread are subdivision of Process. One or more Threads runs in the context of process. Threads can execute any part of process. And same part of process can be executed by multiple Threads.

Processes have their own copy of the data segment of the parent process while Threads have direct access to the data segment of its process.

Processes have their own address while Threads share the address space of the process that created it.

Process creation needs whole lot of stuff to be done, we might need to copy whole parent process, but Thread can be easily created.

Processes can easily communicate with child processes but interprocess communication is difficult. While, Threads can easily communicate with other threads of the same process using wait() and notify() methods.

In Process all threads share system resource like heap Memory etc. while Thread has its own stack.

Any change made to Process does not affect child processes, but any change made to Thread can affect the behavior of the other threads of the process.


  9. How can you ensure all threads that started from main must end in order in which they started and also main should end in last?

We can use join() method to ensure all threads that started from main must end in order in which they started and also main should end in last.In other words waits for this thread to die. Calling join() method internally calls join(0);


  10. What is race condition in multi-threading and how can we solve it?

When more than one thread try to access same resource without synchronization causes race condition.

So we can solve race condition by using either synchronized block or synchronized method. When no two threads can access same resource at a time phenomenon is also called as mutual exclusion.

NOTE:- (a). What if two threads try to read same resource without synchronization?

When two threads try to read on same resource without synchronization, it's never going to create any problem.

(b). What if two threads try to write to same resource without synchronization?

When two threads try to write to same resource without synchronization, it's going to create synchronization problems.


  11. Why wait(), notify() and notifyAll() are in Object class and not in Thread class?

1. Every Object has a monitor, acquiring that monitors allow thread to hold lock on object. But Thread class does not have any monitors.

2. wait(), notify() and notifyAll() are called on objects only, When wait() method is called on object by thread it waits for another thread on that object to release object monitor by calling notify() or notifyAll() method on that object.

3. When notify() method is called on object by thread it notifies all the threads which are waiting for that object monitor that object monitor is available now. So, this shows that wait(), notify() and notifyAll() are called on objects only.

4. Wait(), notify() and notifyAll() method being in Object class allows all the threads created on that object to communicate with other. [As multiple threads may exist on same object].

5. As multiple threads exists on same object. Only one thread can hold object monitor at a time. As a result thread can notify other threads of same object that lock is available now. But, thread having these methods does not make any sense because multiple threads exists on object its not other way around (i.e. multiple objects exists on thread).

6. Now let's discuss one hypothetical scenario, what will happen if Thread class contains wait(), notify() and notifyAll() methods?

Having wait(), notify() and notifyAll() methods means Thread class also must have their monitor. Every thread having their monitor will create few problems:-

.Thread communication problem.

.Synchronization on object won't be possible:- Because object has monitor, one object can have multiple threads and thread hold lock on object by holding object monitor. But if each thread will have monitor, we won't have any way of achieving synchronization.

.Inconsistency in state of object (because synchronization won't be possible).


  12. Have you ever generated thread dumps or analyzed Thread Dumps?

VisualVM is most popular way to generate Thread Dump and is most widely used by developers. It's important to understand usage of VisualVM for in depth knowledge of VisualVM. I'll recommend every developer must understand this topic to become master in multi threading.

It helps us in analyzing threads performance, thread states, CPU consumed by threads, garbage collection and much more.

jstack is very easy way to generate Thread dump and is widely used by developers. I'll recommend every developer must understand this topic to become master in multi threading. For creating Thread dumps we need not to download any jar or any extra software.


  13.What is life cycle of Thread, explain thread states?

Thread have following states:-

(a). New

(b). Runnable

(c). Running

(d). Waiting/blocked/sleeping

(e). Terminated (Dead)

New : When instance of thread is created using new operator it is in new state, but the start() method has not been invoked on the thread yet, thread is not eligible to run yet.

Runnable : When start() method is called on thread it enters runnable state.

Running : Thread scheduler selects thread to go from runnable to running state. In running state Thread starts executing by entering run() method.

Waiting/blocked/sleeping : In this state a thread is not eligible to run.

.Thread is still alive, but currently it's not eligible to run. In other words.

.How can Thread go from running to waiting state?

By calling wait() method thread go from running to waiting state. In waiting state it will wait for other threads to release object monitor/lock.

.How can Thread go from running to sleeping state?

By calling sleep() method thread go from running to sleeping state. In sleeping state it will wait for sleep time to get over.

Terminated (Dead) : A thread is considered dead when its run() method completes.


  14. Why suspend() and resume() methods are deprecated?

Suspend() method is deadlock prone. If the target thread holds a lock on object when it is suspended, no thread can lock this object until the target thread is resumed. If the thread that would resume the target thread attempts to lock this monitor prior to calling resume, it results in deadlock formation. These deadlocks are generally called Frozen processes.

Suspend() method puts thread from running to waiting state. And thread can go from waiting to runnable state only when resume() method is called on thread. It is deprecated method.

Resume() method is only used with suspend() method that's why it's also deprecated method.


  15. As stop() method is deprecated, How can we terminate or stop infinitely running thread in java?

If the target thread holds a lock on object when it is destroyed, no thread can lock this object (Deadlock formed are similar to deadlock formed when suspend() and resume() methods are used improperly). It results in deadlock formation. These deadlocks are generally called Frozen processes.

It helps us in analyzing threads performance, thread states, CPU consumed by threads, garbage collection and much more.

Additionally you must know calling destroy() method on Threads throw runtimeException i.e. NoSuchMethodError. Destroy() method puts thread from running to dead state.


  16. What are thread priorities?

Thread Priority range is from 1 to 10. Where 1 is minimum priority and 10 is maximum priority.

Thread class provides variables of final static int type for setting thread priority.

Thread with MAX_PRIORITY is likely to get more CPU as compared to low priority threads. But occasionally low priority thread might get more CPU. Because thread scheduler schedules thread on discretion of implementation and thread behaviour is totally unpredictable.

Thread with MIN_PRIORITY is likely to get less CPU as compared to high priority threads. But occasionally high priority thread might less CPU. Because thread scheduler schedules thread on discretion of implementation and thread behaviour is totally unpredictable.

setPriority() method is used for Changing the priority of thread.

getPriority() method returns the thread's priority.


  17. What is ThreadGroup in java, What is default priority of newly created threadGroup, mention some important ThreadGroup methods ?

When program starts JVM creates a ThreadGroup named main. Unless specified, all newly created threads become members of the main thread group.

ThreadGroup is initialized with default priority of 10.

ThreadGroup important methods:-

getName():- name of ThreadGroup.

activeGroupCount():- count of active groups in ThreadGroup.

activeCount():- count of active threads in ThreadGroup.

list():- list() method has prints ThreadGroups information

getMaxPriority():- Method returns the maximum priority of ThreadGroup.

setMaxPriority(int pri):- Sets the maximum priority of ThreadGroup.


  18. What is addShutdownHook method in java?

addShutdownHook method in java:-

. addShutdownHook method registers a new virtual-machine shutdown hook.

. A shutdown hook is a initialized but unstarted thread.

. When JVM starts its shutdown it will start all registered shutdown hooks in some unspecified order and let them run concurrently.

When JVM (Java virtual machine) shuts down:-

. When the last non-daemon thread finishes, or

when the System.exit is called.

Once JVM's shutdown has begun new shutdown hook cannot be registered neither previously-registered hook can be de-registered. Any attempt made to do any of these operations causes an IllegalStateException.


  19. What do you mean by thread starvation?

When thread does not enough CPU for its execution Thread starvation happens.

Thread starvation may happen in following scenarios:-

(a). Low priority threads gets less CPU (time for execution) as compared to high priority threads. Lower priority thread may starve away waiting to get enough CPU to perform calculations.

In deadlock two threads waits for each other to release lock holded by them on resources. There both Threads starves away to get CPU.

Thread might be waiting indefinitely for lock on object's monitor (by calling wait() method), because no other thread is calling notify()/notifyAll() method on object. In that case, Thread starves away to get CPU.

Thread might be waiting indefinitely for lock on object's monitor (by calling wait() method), but notify() may be repeatedly awakening some other threads. In that case also Thread starves away to get CPU.


  20. What is busy spin?

When one thread loops continuously waiting for another thread to signal.

It helps us in analyzing threads performance, thread states, CPU consumed by threads, garbage collection and much more.

Performance point of view:- Busy spin is very bad from performance point of view, because one thread keeps on looping continuously ( and consumes CPU) waiting for another thread to signal.

Solution to busy spin:- We must use sleep() or wait() and notify() method. Using wait() is better option.

Why using wait() and notify() is much better option to solve busy spin?

Because in case when we use sleep() method, thread will wake up again and again after specified sleep time until boolean variable is true. But, in case of wait() thread will wake up only when when notified by calling notify() or notifyAll(), hence end up consuming CPU in best possible manner.


  21. Can you find whether thread holds lock on object or not?

holdsLock(object) method can be used to find out whether current thread holds the lock on monitor of specified object. holdsLock(object) method returns true if the current thread holds the lock on monitor of specified object.


  22. Can a constructor be synchronized?

No, constructor cannot be synchronized. Because constructor is used for instantiating object, when we are in constructor object is under creation. So, until object is not instantiated it does not need any synchronization.

Enclosing constructor in synchronized block will generate compilation error

Using synchronized in constructor definition will also show compilation error.

COMPILATION ERROR = Illegal modifier for the constructor in type ConstructorSynchronizeTest; only public, protected & private are permitted

Though we can use synchronized block inside constructor.


  23. How can you implement your own Thread Pool in java?

What is ThreadPool?

ThreadPool is a pool of threads which reuses a fixed number of threads to execute tasks. At any point, at most nThreads threads will be active processing tasks. If additional tasks are submitted when all threads are active, they will wait in the queue until a thread is available.

ThreadPool implementation internally uses LinkedBlockingQueue for adding and removing tasks.

Need/Advantage of ThreadPool:-

Instead of creating new thread every time for executing tasks, we can create ThreadPool which reuses a fixed number of threads for executing tasks. As threads are reused, performance of our application improves drastically.

Java thread pool manages the collection of Runnable threads and worker threads execute Runnable from the queue. java.util.concurrent.Executors provide implementation of java.util.concurrent.Executor interface to create the thread pool in java.


  24. What is the difference between object lock and class lock?

Difference between Object Lock and Class Lock:-

Object Lock:-

1. Thread can acquire object lock by:-

(a). Entering synchronized block or

(b). By entering synchronized methods.

2. Multiple threads may exist on same object but only one thread of that object can enter synchronized method at a time. Threads on different object can enter same method at same time.

3. Multiple objects of class may exist and every object has it's own lock.

4. Syntax:- public synchronized void method() {}, As soon as thread entered Synchronization method, thread acquired object lock. Thread will leave lock when it exits synchronized method.

Class Lock:-

1. Thread can acquire lock on class's class object by:-

(a). Entering synchronized block or

(b). By entering static synchronized methods.

2. Multiple threads may exist on same or different objects of class but only one thread can enter static synchronized method at a time.

3. Multiple objects of class may exist but there is always one class's class object lock available.

4. Syntax:- synchronized MyClass synchronized (MyClass.class) {}, As soon as thread entered static Synchronization method, thread acquired lock on class's class object. Thread will leave lock when it exits synchronized method.


  25. Does thread leaves object lock when wait() method is called?

When wait() method is called Thread leaves the object lock and goes from running to waiting state. Thread waits for other threads on same object to call notify() or notifyAll() and once any of notify() or notifyAll() is called it goes from waiting to runnable state and again acquires object lock.


  26. Does thread leaves object lock when sleep() method is called?

When sleep() method is called Thread does not leaves object lock and goes from running to waiting state. Thread waits for sleep time to over and once sleep time is up it goes from waiting to runnable state.


  27. What are the differences and similarities between yield() and sleep() ?

Differences between yield() and sleep() :-

1. Definition :- yield() method when called on thread gives a hint to the thread scheduler that the current thread is willing to yield its current use of a processor. The thread scheduler is free to ignore this hint. sleep() methods causes current thread to sleep for specified number of milliseconds (i.e. time passed in sleep method as parameter). Example :- Thread.sleep(10) causes currently executing thread to sleep for 10 millisecond.

2. Thread state :- when sleep() is called on thread it goes from running to waiting state and can return to runnable state when sleep time is up. When yield() method is called on thread it goes from running to runnable state, not in waiting state. Thread is eligible to run but not running and could be picked by scheduler at anytime.

3. Exception :- yield() method need not to catch or throw any exception. But sleep() method must catch or throw compile time exception i.e. InterruptedException.

4. Waiting time :- yield() method stops thread for unpredictable time, that depends on thread scheduler. But sleep() method have got few options.

(a). sleep(long millis) :- Causes the currently executing thread to sleep for the specified number of milliseconds

(b). sleep(long millis, int nanos) :- Causes the currently executing thread to sleep for the specified number of milliseconds plus the specified number of nanoseconds.

Similarity between yield() and sleep() methods :-

1. yield() and sleep() method belongs to java.lang.Thread class.

2. yield() and sleep() method can be called from outside synchronized block.

3. yield() and sleep() method are called on Threads not objects.


  28. Are you aware of preemptive scheduling and time slicing?

In preemptive scheduling, the highest priority thread executes until it enters into the waiting or dead state.

In time slicing, a thread executes for a certain predefined time and then enters runnable pool. Than thread can enter running state when selected by thread scheduler.


  29. What are daemon threads?

Daemon threads are low priority threads which runs intermittently in background for doing garbage collection.

Few salient features of daemon() threads :-

1. Thread scheduler schedules these threads only when CPU is idle.

2. Daemon threads are service oriented threads, they serves all other threads.

3. These threads are created before user threads are created and die after all other user threads dies.

4. Priority of daemon threads is always 1 (i.e. MIN_PRIORITY).

5. User created threads are non daemon threads.

6. JVM can exit when only daemon threads exist in system.

7. We can use isDaemon() method to check whether thread is daemon thread or not.

8. We can use setDaemon(boolean on) method to make any user method a daemon thread.

9. If setDaemon(boolean on) is called on thread after calling start() method than IllegalThreadStateException is thrown.

10. You may like to see how daemon threads work, for that you can use VisualVM or jStack. I have provided Thread dumps over there which shows daemon threads which were intermittently running in background.


  29. What are daemon threads?

Daemon threads are low priority threads which runs intermittently in background for doing garbage collection.

Few salient features of daemon() threads :-

1. Thread scheduler schedules these threads only when CPU is idle.

2. Daemon threads are service oriented threads, they serves all other threads.

3. These threads are created before user threads are created and die after all other user threads dies.

4. Priority of daemon threads is always 1 (i.e. MIN_PRIORITY).

5. User created threads are non daemon threads.

6. JVM can exit when only daemon threads exist in system.

7. We can use isDaemon() method to check whether thread is daemon thread or not.

8. We can use setDaemon(boolean on) method to make any user method a daemon thread.

9. If setDaemon(boolean on) is called on thread after calling start() method than IllegalThreadStateException is thrown.

10. You may like to see how daemon threads work, for that you can use VisualVM or jStack. I have provided Thread dumps over there which shows daemon threads which were intermittently running in background.


  30. What is Multi-Threading in Java?

The process of executing multiple threads simultaneously is known as multi-threading. Java supports multi-threading. The main advantage of multi-threading is reducing CPU idle time and improving the CPU utilization. This makes the job to be completed in less time.


  31. What is difference between user thread and Daemon thread?

By default a thread created in a program is always a user thread, however we can make it daemon by calling setDaemon(true) method, if needed.

A daemon thread runs in a background and it doesn’t prevent JVM from being shutdown. Once all the user thread gets completed the JVM shutdowns without being bothered whether a daemon thread is running or not.


  32. What is deadlock?

A deadlock is a condition when two or more threads are in waiting for each other to release the resources that they need.

For example :-

Thread A holds a resource (resource of A)X and need (resource of B)resource Y whereas Thread B holds a resource Y and need X, in this case both threads are waiting for each other to release the resource and are in blocked condition.


  33. What is Multi-Threading in Java?

The process of executing multiple threads simultaneously is known as multi-threading. Java supports multi-threading. The main advantage of multi-threading is reducing CPU idle time and improving the CPU utilization. This makes the job to be completed in less time.


PHP

PHP is a server-side scripting language designed primarily for web development but is also used as a general-purpose programming language..

Read more