Kubernate

Thread # Multithreading + Concurrency + Java 8

Multithreading + Concurrency + Java 8 questions and answers.


TOP MULTITHREADING INTERVIEW QUESTIONS & ANSWERS (With Java 8)

(Short, powerful, and expected in interviews)


🔹 1. What is a Thread in Java?

A thread is the smallest unit of execution inside a process.
Java supports multithreading using Thread class, Runnable, and Executors.


🔹 2. Difference between Process vs Thread

Process Thread
Independent memory Shares memory of process
Heavyweight Lightweight
Slow context-switching Fast switching

🔹 3. Ways to create a thread in Java

  1. Extend Thread

  2. Implement Runnable

  3. Implement Callable

  4. Using ExecutorService

  5. Using Java 8 CompletableFuture


🔹 4. Runnable vs Callable

Runnable Callable
No return value Returns value
No checked exception Can throw exception
Used with Thread Used with ExecutorService

🔹 5. What is Executor Framework?

A framework to manage thread pools.
Prevents creating many threads manually.

Example:

ExecutorService executor = Executors.newFixedThreadPool(10);
executor.submit(() -> System.out.println("Task executed"));

🔹 6. What is Thread Pooling & Why?

Instead of creating new threads every time, reuse existing threads.

Benefits:
✔ Avoids overhead
✔ Improves performance
✔ Stable under heavy load


🔹 7. Types of Thread Pools

  • FixedThreadPool

  • CachedThreadPool

  • ScheduledThreadPool

  • SingleThreadExecutor

  • WorkStealingPool (Java 8)


🔹 8. What is Synchronization?

A mechanism to control multiple threads accessing shared resources.

Ways:

  • synchronized keyword

  • ReentrantLock

  • Atomic classes

  • synchronized blocks


🔹 9. synchronized method vs synchronized block

synchronized method synchronized block
Locks entire method Locks only specific code
Less efficient More efficient
Easy to use More control

🔹 10. What is ReentrantLock? Why better?

ReentrantLock is an advanced lock mechanism.

Benefits:

  • TryLock()

  • Lock interruptibility

  • Fairness policy

  • Better performance under contention

Example:

lock.lock();
try {
    // critical section
} finally {
    lock.unlock();
}

🔹 11. What is volatile?

volatile ensures:

✔ Visibility of changes across threads
✔ Prevents caching variables inside thread-local memory

But volatile does NOT ensure atomicity.


🔹 12. What is Atomic package?

java.util.concurrent.atomic
Provides lock-free thread-safe operations.

Example:

AtomicInteger counter = new AtomicInteger();
counter.incrementAndGet();

🔹 13. What is Deadlock?

When two threads wait forever for each other’s lock.


🔹 14. What is Livelock?

Threads keep running but make no progress (continuously responding to each other).


🔹 15. What is Starvation?

Low-priority thread never gets CPU because high-priority threads always run.


🔹 16. What is ThreadLocal?

Provides thread-specific variable.

Example:

ThreadLocal<String> tl = ThreadLocal.withInitial(() -> "default");

Used in:

  • Per-request context

  • Tenant context

  • Security context


🔹 17. Difference between wait(), sleep(), yield()?

Method Belongs Releases lock? Purpose
wait() Object YES Thread communication
sleep() Thread NO Pause thread
yield() Thread NO Hint to scheduler

🔹 18. What is Thread.join()?

Makes one thread wait for another to complete.


🔹 19. What is Future & FutureTask?

Represents result of async computation.


🔹 20. CompletableFuture (Java 8)

Provides powerful async programming.

Example:

CompletableFuture.supplyAsync(() -> "Hello")
                 .thenApply(String::toUpperCase)
                 .thenAccept(System.out::println);

Features:

  • async pipelines

  • chaining

  • exception handling

  • combining tasks


🔹 21. Parallel Streams (Java 8 Multithreading)

list.parallelStream()
    .map(e -> e * 2)
    .forEach(System.out::println);

Uses ForkJoinPool (common pool) internally.

Warning:

Not good for:

  • I/O tasks

  • Stateful operations

  • Shared mutable data


🔹 22. What is ForkJoinPool?

A pool using work-stealing algorithm.
Used for parallel streams, RecursiveTask, RecursiveAction.


🔹 23. What is CountDownLatch?

Allows threads to wait until other threads complete.

Example:

CountDownLatch latch = new CountDownLatch(3);
latch.await();

🔹 24. What is CyclicBarrier?

Lets threads wait for each other repeatedly.


🔹 25. Difference between CountDownLatch vs CyclicBarrier

CountDownLatch CyclicBarrier
One-time use Reusable
One thread waits All threads wait

🔹 26. Semaphore

Controls number of threads accessing a resource.


🔹 27. ReadWriteLock

Allows:

  • multiple readers

  • one writer

Better performance for read-heavy systems.


🔹 28. What is concurrency vs parallelism?

Concurrency Parallelism
Multiple tasks progressing Multiple tasks running at same time
Single CPU possible Requires multiple CPUs

🔹 29. What is Immutable Object?

Thread-safe because state cannot change.

Examples:
String, Integer, LocalDate


🔹 30. Best practices for multithreading

✔ Use ExecutorService → not “new Thread()”
✔ Avoid shared mutable state
✔ Prefer immutability
✔ Use locks only when required
✔ Avoid parallelStream if your use case is I/O
✔ Always shutdown executor
✔ Handle exceptions in CompletableFuture



No comments:

Post a Comment

Spring Boot - Bean LifeCycle

 Here is a clear, step-by-step lifecycle of a Spring Boot application , explained in a simple + interview-ready way. 🔄 Spring Boot Applica...

Kubernate