Java Synchronized Block — Java Technical Interview Questions & Answers
Java Synchronized Block
Java Synchronized Block
- Synchronized Block is part of Java concurrency. A thread is a path of work inside a process. Create with Thread or Runnable, then call start() — not run(). run() only runs on the same thread.
- For Synchronized Block: if two threads share data, synchronize or the result can be wrong. sleep pauses. join waits for another thread to finish. daemon threads die when all user threads finish.
- Synchronized Block deadlock: two threads wait for each other’s lock forever. Avoid by locking in the same order. Don’t guess thread order — it can change every run.
- Let's take this on the board with one tiny Main class — no extra files. Java Synchronized Block — output: 2000. Two threads each inc 1000 times. synchronized keeps the count exact — without it, you can get less than 2000. Start from main, go line by line, and stop at each print. That output is the proof for Synchronized Block.
Technical Interview Tip: Define deadlock with a 2-lock A/B story.
Code Examples for Java Synchronized Block
Example
class Counter {
private int n;
synchronized void inc() { n++; }
synchronized int get() { return n; }
}
public class Main {
public static void main(String[] args) throws Exception {
Counter c = new Counter();
Thread t1 = new Thread(() -> { for (int i = 0; i < 1000; i++) c.inc(); });
Thread t2 = new Thread(() -> { for (int i = 0; i < 1000; i++) c.inc(); });
t1.start(); t2.start();
t1.join(); t2.join();
System.out.println(c.get()); // 2000
}
}Java Synchronized Block — output: 2000. Two threads each inc 1000 times. synchronized keeps the count exact — without it, you can get less than 2000.
How to Explain Java Synchronized Block to an Interviewer
What is Synchronized Block?
Synchronized Block — thread = one path of work. start() schedules it. run() does not. Synchronized Block — shared data needs synchronization. Synchronized Block — sleep = pause. join = wait for other thread.
Why do we use Synchronized Block in Java?
Makes the program clearer or safer Synchronized Block — thread = one path of work. start() schedules it. run() does not.
Write one small example of Synchronized Block.
Show syntax Say what prints
What mistake do beginners make with Synchronized Block?
Only the name, no example Synchronized Block — calling run() instead of start(). Deadlock = locks in wrong order.
Where is Synchronized Block used in a real program?
Day-to-day Java code