1. What is the difference between a process and a thread?
Answer:
- A process is an independent program in execution, containing its own memory space, resources, and CPU time.
- A thread is a subset of a process; it is the smallest unit of execution within a process. Threads share the same memory space and resources of the process, but have their own stack and registers.
2. What are the benefits of using multithreading in Java?
Answer:
- Improved Performance: Utilizing multiple threads can lead to better CPU utilization and improved application performance.
- Responsive UI: In GUI applications, multithreading helps keep the user interface responsive by performing background tasks in separate threads.
- Simplified Modeling: Some problems are more naturally modeled using threads, such as simulation or concurrent tasks.
3. Explain the difference between Runnable and Callable in Java.
Answer:
- Runnable: Represents a task that can be executed by a thread, but does not return a result and cannot throw checked exceptions.
Runnable task = () -> System.out.println("Runnable Task"); - Callable: Similar to
Runnable, but it can return a result and throw checked exceptions.Callable<String> task = () -> "Callable Task";
4. How can you create a thread in Java?
Answer:
- Extending
Threadclass:class MyThread extends Thread { public void run() { System.out.println("Thread running"); } } MyThread thread = new MyThread(); thread.start(); - Implementing
Runnableinterface:class MyRunnable implements Runnable { public void run() { System.out.println("Runnable running"); } } Thread thread = new Thread(new MyRunnable()); thread.start();
5. What is the purpose of the synchronized keyword?
Answer:
The synchronized keyword in Java is used to control access to a critical section of code, ensuring that only one thread can execute the block of code at a time. This helps prevent race conditions and ensures thread safety.
6. What are the different ways to achieve thread synchronization?
Answer:
- Synchronized Methods: Entire methods are synchronized, ensuring only one thread can execute the method at a time.
public synchronized void synchronizedMethod() { // critical section } - Synchronized Blocks: Specific blocks of code are synchronized, providing more fine-grained control.
public void method() { synchronized (this) { // critical section } } - Static Synchronization: Static methods can be synchronized to control access on a class level.
public static synchronized void synchronizedStaticMethod() { // critical section }
7. Explain the use of wait(), notify(), and notifyAll() methods.
Answer:
wait(): Causes the current thread to wait until another thread callsnotify()ornotifyAll()on the same object. It must be called within a synchronized context.synchronized (obj) { obj.wait(); }notify(): Wakes up one waiting thread on the same object. The awakened thread must reacquire the object's monitor before it can proceed.synchronized (obj) { obj.notify(); }notifyAll(): Wakes up all waiting threads on the same object. Each thread will try to reacquire the object's monitor before it can proceed.synchronized (obj) { obj.notifyAll(); }
8. What is a deadlock and how can it be prevented?
Answer:
- Deadlock: A situation where two or more threads are blocked forever, waiting for each other to release resources.
- Prevention Techniques:
- Avoid Nested Locks: Avoid locking multiple resources simultaneously.
- Lock Ordering: Always acquire locks in a consistent order.
- Timeouts: Use
tryLockwith timeouts to avoid waiting indefinitely. - Deadlock Detection: Use tools or algorithms to detect and resolve deadlocks.
9. What is the difference between volatile and synchronized?
Answer:
volatile: Ensures visibility of changes to variables across threads, but does not guarantee atomicity. It is used for simple flags or state variables.private volatile boolean flag = true;synchronized: Ensures both visibility and atomicity by providing exclusive access to a block of code or method.public synchronized void synchronizedMethod() { // critical section }
10. What is the ThreadLocal class and how is it used?
Answer:
The ThreadLocal class provides thread-local variables, where each thread accessing such a variable has its own, independently initialized copy of the variable.
ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 1);
threadLocal.set(42);
int value = threadLocal.get();
11. Explain the ForkJoinPool and its use.
Answer:
ForkJoinPool: A special type of thread pool designed for work-stealing and executing tasks represented asForkJoinTask. It is well-suited for parallel divide-and-conquer algorithms.ForkJoinPool pool = new ForkJoinPool(); pool.invoke(new RecursiveTask<Integer>() { protected Integer compute() { // task implementation return 0; } });
12. What are ConcurrentHashMap and CopyOnWriteArrayList?
Answer:
ConcurrentHashMap: A thread-safe implementation ofHashMapthat allows concurrent reads and writes without locking the entire map.ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>(); map.put("key", 1);CopyOnWriteArrayList: A thread-safe variant ofArrayListwhere all mutative operations (add, set, etc.) are implemented by making a fresh copy of the array.CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>(); list.add("element");
peace of code which has possibility for dead lock, can be called concurrently
race condition
special condition, multiple threads pass to criticla section. not sure when threads will do context switchinig will happen, and when reuslt will come.
deadlock
livelock: same lock to be unlocked by same thread.
mutual exclusion , allows serialized access to critical section
mutex: mutual exclusion, allow only single thread to execute, mutex can be notify
semaphore: mute over multiple shared resources, limiting the resource to limited threads
starvation: a thread couldn't gbet the resource beauseof hte greedy thread
buffer blcoking queue
threadpool: devoupled the task of creating a thread and execution.
use already created thread for further or ful task
benefits: no letency when a new request is received
system willl not go out of memeory
betetr enhancement
void solve haldiram(){
int helpers = 100;
Executor exe = Excetors.newFixedThreadppol(helpers);
while(!shopeClosed){
order = waitForNewOrder();
exe.execute(new Runnable(){ @override public void run(){ order.execute()}});
}
parallelization: due to some cores
inherit blance of cpu vs io in your code:
jvm need to maintain thread stack: thread stack have copy of variable, local information of thread, JVM save these.
Jva has a lot of thread pool implimentation, that can be instantiated, using the factory method of the executor classs
new fixed thread pool:
new single thread executro: if single thread die unexpectely due to exception, so it will create thread again for remaining task
new cached thread pool: whenever old threads are there then use it else create new threads upto some limit , most optimized wat of thread pool
best use: higly unsynchronized, short live task
not use for long time task, larger time frame
KYC bulk verification: shorteer live task Cached thread pool
number of entries in csv(cached thread pool)
live online data coming then use fixed thread pool
every object in java has an associated entity called as a monitor lock
by default all object can accquire locked
public synchroinzed cahngeValue(){
so threads accquire a lock over the objct of the class.
}

