Advanced Multithreading
Thread के 5 states होते हैं: New, Runnable, Running, Waiting/Blocked, Terminated।
wait()/notify() threads को एक दूसरे के signal का इंतज़ार करने देते हैं। ExecutorService thread pool manage करता है — नए threads manually बनाने के बजाय, ready threads reuse होते हैं।
Deadlock तब होता है जब दो threads एक-दूसरे के पास जो resource है उसका इंतज़ार करते रह जाते हैं, और कोई आगे नहीं बढ़ता — जैसे दो लोग एक ही दरवाज़े पर एक-दूसरे को पहले जाने दे रहे हों, हमेशा के लिए।
ExecutorService pool = Executors.newFixedThreadPool(2);
pool.submit(() -> System.out.println("Task running!"));
pool.shutdown();synchronized method (poora method lock ho jaata hai) simple hai lekin poore method ko lock karta hai, chahe sirf ek chhota hissa critical ho — isse unnecessary blocking ho sakti hai (doosre threads jo unrelated kaam karna chahte hain, wo bhi wait karenge).
synchronized block (synchronized(obj) { ... }) sirf zaroori hisse ko lock karta hai — better performance, kyunki baaki code parallel chal sakta hai. Har object ka apna "monitor lock" hota hai jo synchronized use karta hai.
synchronized void increment() { count++; } // poora method locked
void increment2() {
// ... non-critical code, parallel chal sakta hai
synchronized(this) {
count++; // sirf ye critical section locked
}
}Ye teeno Object class ke methods hain (har object par available), aur sirf synchronized block ke andar hi use ho sakte hain (warna IllegalMonitorStateException aayegi). wait() current thread ko "sula" deta hai (aur lock chhod deta hai) jab tak koi doosra thread notify() na kare.
Classic use-case: Producer-Consumer pattern, jaha consumer wait() kare jab tak producer kuch produce na kare aur notify() na kare. notifyAll() sab waiting threads ko jagata hai (sirf ek nahi), jo safer hota hai jab multiple threads wait kar rahe ho.
Har thread apne "life" mein 5 states se guzarta hai, New se shuru hoke Terminated tak. Ye samajhna zaroori hai debugging ke liye — jaise agar tumhara thread "stuck" lag raha hai, uski state check karke pata chal sakta hai wo Waiting mein hai ya Blocked mein.
| State | Matlab |
|---|---|
| New | Thread object bana, lekin start() nahi hua |
| Runnable | start() call ho gaya, CPU milne ka wait/chal raha hai |
| Running | Abhi CPU par actually chal raha hai |
| Waiting/Blocked | wait(), sleep(), ya lock ka intezaar |
| Terminated | run() complete ho gaya, thread khatam |
Manually thread banate rehna expensive hai (har thread banana OS resources leta hai). ExecutorService thread pool manage karta hai: newFixedThreadPool(n) — fixed number of reusable threads, jaise n workers hamesha ready. newCachedThreadPool() — zaroorat ke hisaab se badhता-ghatता pool, kaam khatam hote hi idle threads free ho jaate hain. newScheduledThreadPool() — delay ya repeat interval par tasks chalane ke liye.
ExecutorService pool = Executors.newFixedThreadPool(4);
pool.submit(() -> doTask());
pool.shutdown(); // naye tasks accept karna band, purane complete hongeDeadlock tab hota hai jab Thread A, Lock-1 pakad ke Lock-2 ka wait kare, aur Thread B, Lock-2 pakad ke Lock-1 ka wait kare — dono hamesha ke liye ruk jaate hain, kyunki dono ek-doosre ke paas jo hai uska intezaar kar rahe hain.
Prevention: hamesha locks ko *same order* mein acquire karo saare threads mein (jaise hamesha pehle Lock-1, phir Lock-2, kabhi ulta nahi) — isse "circular wait" hi possible nahi hota. Ya timeout wale locks (tryLock(timeout)) use karo, jisse thread hamesha ke liye atakta nahi, timeout ke baad give up kar deta hai.
Multi-threaded environment mein har thread ki apni CPU cache ho sakti hai ek variable ki "local copy" (performance ke liye) — isliye ek thread ka change turant doosre thread ko na dikhe, ye possible hai.
volatile keyword guarantee deta hai ki variable ki reads/writes hamesha main memory se hon, cache se nahi — isse ek thread ka change turant doosre threads ko dikhta hai. Ye synchronization jaisa mutual-exclusion (ek waqt sirf ek thread) NAHI deta, sirf "visibility" guarantee deta hai — agar count++ jaisi compound operation hai, volatile kaafi nahi hai, synchronized/Atomic chahiye.