[Go to site: main page, start]

0% found this document useful (0 votes)
7 views9 pages

Java Multithreading Concepts Explained

The document provides a comprehensive overview of Java multithreading, covering key concepts such as thread lifecycle, synchronization, thread safety, and various thread creation techniques. It explains the differences between processes and threads, the importance of multithreading for application performance, and common issues like deadlock and race conditions. Additionally, it includes a section with 30 interview questions and answers related to multithreading concepts.

Uploaded by

saddubuddu1
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)
7 views9 pages

Java Multithreading Concepts Explained

The document provides a comprehensive overview of Java multithreading, covering key concepts such as thread lifecycle, synchronization, thread safety, and various thread creation techniques. It explains the differences between processes and threads, the importance of multithreading for application performance, and common issues like deadlock and race conditions. Additionally, it includes a section with 30 interview questions and answers related to multithreading concepts.

Uploaded by

saddubuddu1
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 MULTITHREADING

[Link]

Thread

• A thread is the smallest unit of execution in Java.


• Multiple threads run inside a single process and share heap memory.
• Each thread has its own stack (local variables, method calls).
• Threads are lightweight compared to processes, so context switching is faster.

Process vs Thread

• Process has its own memory space.


• Threads share memory inside the same process.
• Communication between threads is faster than communication between processes.
• Sharing memory improves performance but introduces concurrency issues.

Why Multithreading is Required

• Improves application responsiveness (UI + background work).


• Better CPU utilization on multi-core systems.
• Enables parallel task execution.
• Essential for server-side and real-time applications.

Thread Lifecycle

• New – Thread object created.


• Runnable – Thread is ready to run, waiting for CPU.
• Running – Thread is executing.
• Blocked / Waiting – Waiting for lock or signal.
• Timed Waiting – Waiting for fixed time.
• Terminated – Execution finished.
Thread Creation Techniques

• Extending Thread class.


• Implementing Runnable (preferred for flexibility).
• Implementing Callable for returning values.
• Using ExecutorService for thread pooling.

Thread Safety

• Code is thread-safe if it works correctly when accessed by multiple threads.


• Thread safety can be achieved by:

• Synchronization

• Thread confinement

• Immutability

• Proper locking strategies

Synchronization

• Ensures only one thread accesses critical code at a time.


• Prevents data inconsistency and race conditions.
• Implemented using:

• synchronized methods

• synchronized blocks

Intrinsic (Monitor) Lock

• Every Java object has a built-in monitor lock.


• synchronized internally uses this monitor.
• Only one thread can hold the monitor at a time.

Race Condition

• Occurs when multiple threads modify shared data without synchronization.


• Output depends on execution timing.
• Leads to inconsistent or incorrect results.
Deadlock

• Two or more threads wait forever for each other’s locks.


• Occurs due to circular dependency.
• Causes application freeze.

Starvation

• A thread never gets CPU time due to scheduling or lock priority issues.

Executor Framework

• High-level API for managing threads.


• Separates task submission from thread execution.
• Improves scalability and performance.

Thread Pool

• Fixed number of reusable threads.


• Prevents overhead of thread creation.
• Controls resource usage.

Callable and Future

• Callable returns a result and throws checked exceptions.


• Future represents result of asynchronous computation.

CompletableFuture

• Supports asynchronous task chaining.


• Allows combining multiple async tasks.
• Helps write non-blocking code.
Concurrent Collections

• Designed for safe access by multiple threads.


• Avoid full synchronization overhead.
• Examples:

o ConcurrentHashMap

o CopyOnWriteArrayList

o BlockingQueue

ThreadLocal

• Provides thread-specific variables.


• Each thread gets its own copy.
• Eliminates synchronization for shared data.

BlockingQueue

• Thread-safe queue.
• Automatically handles thread waiting.
• Used in producer-consumer problems.

Locks ([Link])

• Explicit locking mechanism.


• More flexible than synchronized.
• Supports fairness, timeout, interruptibility.

2. INTERNAL WORKING OF MULTITHREADING

Thread Scheduling

• JVM delegates scheduling to OS.


• Uses time slicing.
• Thread execution order is not guaranteed.
How synchronized Works Internally

• JVM uses MonitorEnter and MonitorExit instructions.


• Object header stores lock state.
• Other threads block until lock is released.

Context Switching

• CPU saves current thread state.


• Loads another thread state.
• Frequent switching reduces performance.

Lock Contention

• Multiple threads competing for same lock.


• Leads to blocking and reduced throughput.
• Must be minimized by reducing synchronized scope.

3. TOP 30 CONCEPT INTERVIEW QUESTIONS (WITH DETAILED ANSWERS)

Q1. What is multithreading in Java?

Multithreading allows multiple threads to execute concurrently within a single process. It


improves performance by utilizing CPU cores efficiently and improves responsiveness by
separating tasks such as I/O, computation, and UI handling.

Q2. Difference between process and thread?

A process has its own memory space, whereas threads share memory within the same process.
Threads are lightweight and faster but require synchronization to avoid data inconsistency.

Q3. Explain thread lifecycle.

A thread moves through New, Runnable, Running, Waiting/Blocked, and Terminated states.
Understanding lifecycle helps debug deadlocks and performance issues.
Q4. Why Runnable is preferred over Thread?

Runnable allows separation of task logic from thread management and supports inheritance from
other classes.

Q5. What is synchronization and why is it needed?

Synchronization ensures mutual exclusion so that shared resources are accessed safely,
preventing race conditions.

Q6. What is a race condition?

A race condition occurs when multiple threads access shared data simultaneously and the final
output depends on execution timing.

Q7. Explain deadlock with example.

Deadlock occurs when two threads hold locks needed by each other, causing indefinite waiting.

Q8. How can deadlock be prevented?

By lock ordering, avoiding nested locks, using timeout-based locks, or designing lock-free
algorithms.

Q9. What is livelock?

Threads are not blocked but continuously change state in response to each other without making
progress.

Q10. What is starvation?

A thread never gets CPU time due to scheduling or priority imbalance.


Q11. What is thread safety?

Thread safety ensures correctness of program execution under concurrent access.

Q12. Difference between synchronized method and block?

Synchronized block provides finer-grained locking and better performance.

Q13. What is ExecutorService?

ExecutorService manages thread pools and executes tasks asynchronously, improving scalability.

Q14. Why thread pools are important?

They reduce thread creation overhead and control system resource usage.

Q15. What is Callable?

Callable represents a task that returns a value and can throw checked exceptions.

Q16. What is Future?

Future represents the result of an asynchronous task and allows blocking or polling.

Q17. What is CompletableFuture?

CompletableFuture supports asynchronous pipelines, chaining, and non-blocking execution.

Q18. What is ThreadLocal and where is it used?

ThreadLocal provides per-thread variables, commonly used in security context and database
transactions.
Q19. Difference between wait() and sleep()?

wait() releases lock and waits for notification; sleep() pauses execution without releasing lock.

Q20. Why wait() must be called inside synchronized block?

Because wait() operates on object’s monitor lock.

Q21. What is BlockingQueue?

A queue that blocks threads automatically during insert or remove operations.

Q22. Producer-consumer problem solution in Java?

Solved using BlockingQueue which handles synchronization internally.

Q23. What is ReentrantLock?

A flexible lock supporting fairness, timeout, and interruptible locking.

Q24. Difference between synchronized and ReentrantLock?

ReentrantLock provides more control and flexibility.

Q25. What is ForkJoinPool and where is it used?

ForkJoinPool is a specialized thread pool designed for divide-and-conquer algorithms.


It breaks large tasks into smaller subtasks (fork), executes them in parallel, and then combines
the results (join).
It uses a work-stealing algorithm, where idle threads steal tasks from busy threads, improving
CPU utilization.
ForkJoinPool is commonly used in parallel streams and recursive algorithms.
Q26. What is the difference between notify() and notifyAll()?

notify() wakes up only one waiting thread on the object’s monitor.


notifyAll() wakes up all waiting threads, reducing the risk of deadlock.

Q27. What is context switching?

CPU switches between threads by saving and restoring states.

Q28. What are daemon threads?

Background threads that do not prevent JVM shutdown.

Q29. Why concurrency bugs are difficult to debug?

They depend on timing, thread interleaving, and CPU scheduling.

Q30. When should synchronization be avoided?

When using immutable objects, thread confinement, or concurrent utilities.

You might also like