[Go to site: main page, start]

0% found this document useful (0 votes)
9 views13 pages

Java Threading Interview Guide

The document provides a comprehensive overview of Java threading concepts, including the definition of threads, methods for creating threads, thread lifecycle, synchronization, and common threading issues like race conditions and deadlocks. It also covers advanced topics such as the Executor Framework, thread pooling, and handling exceptions in threads. Each concept is explained with examples and comparisons to enhance understanding.

Uploaded by

21113002
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views13 pages

Java Threading Interview Guide

The document provides a comprehensive overview of Java threading concepts, including the definition of threads, methods for creating threads, thread lifecycle, synchronization, and common threading issues like race conditions and deadlocks. It also covers advanced topics such as the Executor Framework, thread pooling, and handling exceptions in threads. Each concept is explained with examples and comparisons to enhance understanding.

Uploaded by

21113002
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Threading – Complete

Interview Answers
🧠Answers
Java Threading – Complete Interview

1️⃣ What is a Thread in Java?


A thread is a lightweight sub-process or the smallest unit of execution.
It allows multiple parts of a program to run concurrently, improving performance
and responsiveness — especially in I/O or CPU-bound tasks.
Java provides built-in support for threads via the [Link] class and the
Runnable interface.

2️⃣ Difference between start() and run() method

Method Description
start() Creates a new thread and then calls the run() method in that new thread.
run() Executes the code in the current thread (does NOT start a new one).

🧩 Example:
[Link](); // new thread
[Link](); // runs like a normal method

3️⃣ How can you create a thread in Java?


There are two main ways:

1. By extending Thread class

Java Threading – Complete Interview Answers 1


class MyThread extends Thread {
public void run() {
[Link]("Thread running");
}
}
new MyThread().start();

2. By implementing Runnable interface

class MyRunnable implements Runnable {


public void run() {
[Link]("Runnable running");
}
}
new Thread(new MyRunnable()).start();

✅ Prefer Runnable — because Java supports multiple interfaces but single


inheritance.

4️⃣ What is the lifecycle of a Thread?


1. New – Thread object created.

2. Runnable – After calling start() .

3. Running – Scheduler picks thread to run.

4. Waiting/Blocked/Sleeping – Temporarily paused.

5. Terminated/Dead – run() completed or exited.

5️⃣ What is a Daemon Thread?


A daemon thread is a background thread that provides services to user threads
(like the Garbage Collector).

It terminates automatically when all user threads finish.

Java Threading – Complete Interview Answers 2


Example:

Thread t = new Thread(() -> [Link]("Daemon"));


[Link](true);
[Link]();

6️⃣ What is Synchronization in Java? Why is it needed?


Synchronization ensures that only one thread accesses a shared resource at a
time — preventing race conditions and data inconsistency.

Example:

synchronized void increment() { count++; }

It can be applied to:

Methods ( synchronized void foo() )

Code blocks ( synchronized(object){ ... } )

7️⃣ What is a Race Condition?


A race condition occurs when multiple threads access and modify the same
shared data at the same time, causing unexpected results.
Synchronization prevents race conditions.

Example:
Two threads incrementing a shared counter simultaneously → wrong value.

8️⃣ What is?the difference between


notifyAll()
wait() , notify() , and

Java Threading – Complete Interview Answers 3


Method Description

Causes current thread to release the lock and go to waiting state until
wait()
notified.
notify() Wakes up one waiting thread.
notifyAll() Wakes up all waiting threads.

➡️ Used for inter-thread communication, typically inside synchronized blocks.


Example:

synchronized(obj) {
[Link]();
[Link]();
}

9️⃣ Difference between sleep() and wait()

Aspect sleep() wait()

Package Thread class Object class

Lock Does not release lock Releases lock

Usage Used to pause thread Used for inter-thread communication

Needs synchronized? No Yes

🔟 What is a Deadlock?
Deadlock occurs when two or more threads are waiting for each other to release
locks, and none ever proceed.

Example:

Thread 1 locks A, waits for B


Thread 2 locks B, waits for A

✅ Avoid by:
Java Threading – Complete Interview Answers 4
Acquiring locks in a fixed order

Using tryLock() from ReentrantLock

Minimizing synchronized blocks

1️⃣1️⃣ What is the volatile keyword?


volatile ensures visibility of changes made by one thread to another.

When a variable is declared volatile, threads always read its latest value from
main memory, not cache.

Example:

volatile boolean running = true;

1️⃣2️⃣ What is the difference between Runnable and Callable ?

Aspect Runnable Callable

Return type void Returns a value (generic type)

Exception Cannot throw checked exception Can throw checked exception

Method run() call()

Usage With Thread With ExecutorService

Example:

Callable<Integer> task = () -> 5;


Future<Integer> f = [Link](task);

1️⃣3️⃣ What is Thread Pooling?


Creating a thread for every task is expensive.
Thread pooling reuses a fixed number of threads to execute many tasks
efficiently.

Java Threading – Complete Interview Answers 5


Implemented via Executor Framework ( ExecutorService , Executors ).
Example:

ExecutorService pool = [Link](3);


[Link](() -> [Link]("Task"));
[Link]();

1️⃣4️⃣ What is the Executor Framework?


Introduced in Java 5 — provides a high-level API to manage threads using thread
pools.

It replaces manual thread creation.


Classes:

Executor

ExecutorService

Executors

Callable , Future

1️⃣5️⃣ What is a Future in Java?


A Future represents the result of an asynchronous computation.

You can:

Check if it’s done ( isDone() )

Wait for result ( get() )

Cancel it ( cancel() )

Example:

Future<Integer> result = [Link](() -> 10);


[Link]([Link]());

Java Threading – Complete Interview Answers 6


1️⃣6️⃣ What is ConcurrentHashMap ?
A thread-safe version of HashMap where multiple threads can read and write
concurrently without blocking the entire map.
✅ Uses segment locking (not full map locking).
✅ Performs better than synchronized . HashMap

1️⃣7️⃣ What is the difference between concurrency and


parallelism?
Concurrency → Multiple tasks make progress in overlapping time (can run on
a single CPU).

Parallelism → Tasks run simultaneously on multiple CPUs or cores.

1️⃣8️⃣ What is the difference between


interface?
synchronized and Lock

Feature synchronized Lock (ReentrantLock)

Type Keyword Interface

Flexibility Automatic lock release Manual lock/unlock

Try lock No Yes ( tryLock() )

Fairness No fairness Supports fairness policy

1️⃣9️⃣ What are common thread states in [Link] enum?


NEW

RUNNABLE

BLOCKED

WAITING

TIMED_WAITING

Java Threading – Complete Interview Answers 7


TERMINATED

2️⃣0️⃣ How do you handle exceptions in threads?


Use try-catch inside run() or implement an UncaughtExceptionHandler:

[Link]((thread, e) -> {
[Link]("Error in " + [Link]() + ": " + e);
});

🧠 Java Threading – Complete Interview Answers


1️⃣ What is a Thread in Java?
A thread is a lightweight sub-process and the smallest unit of execution. It allows
multiple parts of a program to run concurrently, improving performance and
responsiveness, especially in I/O or CPU-bound tasks.

Java provides built-in support via [Link] and the Runnable interface.

2️⃣ Difference between start() and run()


start() creates a new thread and then calls run() in that new thread.

run() executes in the current thread and does not start a new one.

Example:

Thread t = new Thread(() -> [Link]("Hello"));


[Link](); // new thread

// This just calls run() like a normal method in the current thread
[Link]();

3️⃣ How can you create a thread in Java?


1. By extending Thread class

Java Threading – Complete Interview Answers 8


class MyThread extends Thread {
public void run() {
[Link]("Thread running");
}
}
new MyThread().start();

1. By implementing Runnable interface

class MyRunnable implements Runnable {


public void run() {
[Link]("Runnable running");
}
}
new Thread(new MyRunnable()).start();

✅ Prefer Runnable because Java supports multiple interfaces but single


inheritance.

4️⃣ Lifecycle of a Thread


1. New – Thread object created

2. Runnable – After calling start()

3. Running – Scheduler picks thread to run

4. Waiting/Blocked/Sleeping – Temporarily paused

5. Terminated/Dead – run() completed or exited

5️⃣ What is a Daemon Thread?


A daemon thread is a background thread that provides services to user threads
(for example, the Garbage Collector). It terminates automatically when all user
threads finish.

Java Threading – Complete Interview Answers 9


Thread t = new Thread(() -> [Link]("Daemon"));
[Link](true);
[Link]();

6️⃣ What is Synchronization in Java? Why is it needed?


Synchronization ensures that only one thread accesses a shared resource at a
time, preventing race conditions and data inconsistencies.

synchronized void increment() { count++; }

It can be applied to methods or code blocks: synchronized(obj) { ... }

7️⃣ What is a Race Condition?


A race condition occurs when multiple threads access and modify the same
shared data concurrently, leading to unexpected results. Synchronization prevents
race conditions.

Example: Two threads incrementing a shared counter simultaneously can produce


the wrong value.

8️⃣ Difference between wait() , notify() , and notifyAll()


wait() releases the lock and causes the current thread to wait until notified.

notify() wakes up one waiting thread.

notifyAll() wakes up all waiting threads.

Typically used inside synchronized blocks.

synchronized (obj) {
[Link]();
[Link]();
}

Java Threading – Complete Interview Answers 10


9️⃣ sleep() vs wait()
Package: sleep() is in Thread ; wait() is in Object

Lock: sleep() does not release the lock; wait() releases the lock

Usage: sleep() pauses a thread; wait() is for inter-thread communication

Synchronized needed: sleep() no; wait() yes

🔟 What is a Deadlock?
A deadlock occurs when two or more threads are waiting for each other to
release locks, and none can proceed.

Avoid by:

Acquiring locks in a fixed order

Using tryLock() from ReentrantLock

Minimizing synchronized blocks

1️⃣1️⃣ What is the volatile keyword?


ensures visibility of changes made by one thread to others. Variables
volatile

declared volatile are read from and written to main memory directly.

volatile boolean running = true;

1️⃣2️⃣ Runnable vs Callable


Return type: Runnable returns void; Callable<T> returns a value

Exceptions: Runnable cannot throw checked exceptions; Callable can

Method: run() vs call()

Usage: Runnable with Thread ; Callable with ExecutorService

Callable<Integer> task = () -> 5;


Future<Integer> f = [Link](task);

Java Threading – Complete Interview Answers 11


1️⃣3️⃣ What is Thread Pooling?
Creating a thread per task is expensive. Thread pooling reuses a fixed number of
threads to execute many tasks efficiently. Implemented via the Executor
Framework.

ExecutorService pool = [Link](3);


[Link](() -> [Link]("Task"));
[Link]();

1️⃣4️⃣ What is the Executor Framework?


Introduced in Java 5, it provides a high-level API to manage threads using thread
pools and replaces manual thread creation.
Core types: Executor , ExecutorService , Executors , Callable , Future .

1️⃣5️⃣ What is a Future in Java?


A Future represents the result of an asynchronous computation.

Check if done: isDone()

Wait for result: get()

Cancel: cancel()

Future<Integer> result = [Link](() -> 10);


[Link]([Link]());

1️⃣6️⃣ What is ConcurrentHashMap ?


A thread-safe HashMap that allows concurrent reads and writes without locking the
entire map, performing better than a synchronized HashMap .

1️⃣7️⃣ Concurrency vs Parallelism


Concurrency: Multiple tasks make progress in overlapping time. Can run on a
single CPU.

Java Threading – Complete Interview Answers 12


Parallelism: Tasks run simultaneously on multiple CPUs or cores.

1️⃣8️⃣ synchronized vs Lock (e.g., ReentrantLock )


Type: synchronized is a keyword; Lock is an interface

Flexibility: synchronized auto-releases; Lock requires manual unlock

Try lock: synchronized no; Lock supports tryLock()

Fairness: synchronized none; ReentrantLock supports fairness policy

1️⃣9️⃣ Common [Link] values


NEW , RUNNABLE , BLOCKED , WAITING , TIMED_WAITING , TERMINATED

2️⃣0️⃣ Handling exceptions in threads


Use try-catch inside run() or set an UncaughtExceptionHandler .

Thread t = new Thread(() -> { throw new RuntimeException("boom"); });


[Link]((thread, e) -> {
[Link]("Error in " + [Link]() + ": " + e);
});
[Link]();

Java Threading – Complete Interview Answers 13

You might also like