BIG Thanks to geeksforgeeks
In Java, a Lock (also called a Monitor) is an internal entity associated with every object. It is the mechanism that actually enforces synchronization.
Example
VotingSystem.Java
/**
* Real-World Example: Electronic Voting Booth
* Concept: Synchronized Block
* * Scenario: Multiple voters enter different booths at a polling station.
* 1. Parallel: Reading instructions and thinking about who to vote for.
* 2. Serial: The exact moment the vote is cast, it updates a central
* 'totalVotes' counter. This specific update must be synchronized.
*/
class VoteCounter {
int totalVotes = 0;
public void castVote(String voterName) {
// --- 1. Non-Synchronized Zone (Parallel) ---
// Voters are inside the booth thinking. This doesn't need to block others.
System.out.println(voterName + " has entered the booth and is reviewing candidates...");
try {
Thread.sleep(1000); // Simulate decision making time
} catch (InterruptedException e) { e.printStackTrace(); }
// --- 2. Synchronized Block (Critical Section) ---
// Only one vote can be added to the official counter at a time to prevent data loss.
synchronized (this) {
System.out.println(">> " + voterName + " is pressing the VOTE button.");
totalVotes++;
System.out.println("Vote Cast! Total Votes: " + totalVotes);
System.out.println("<< " + voterName + " left the booth.\n");
}
}
}
class Voter extends Thread {
VoteCounter counterRef;
String name;
Voter(VoteCounter counter, String name) {
this.counterRef = counter;
this.name = name;
}
public void run() {
counterRef.castVote(name);
}
}
public class VotingSystem {
public static void main(String[] args) {
VoteCounter centralCounter = new VoteCounter();
// 4 Voters voting simultaneously
Voter v1 = new Voter(centralCounter, "Voter_Alice");
Voter v2 = new Voter(centralCounter, "Voter_Bob");
Voter v3 = new Voter(centralCounter, "Voter_Charlie");
Voter v4 = new Voter(centralCounter, "Voter_Dave");
v1.start();
v2.start();
v3.start();
v4.start();
}
}
Here is how it relates to Synchronization and example of VotingSystem code:
1. Every Object has a Lock In Java, every single object (like a centralCounter instance) has a built-in lock. Usually, this lock is "open" or free.
2. Synchronization = Acquiring the Lock When a thread encounters the synchronized keyword, it attempts to "acquire" or "hold" the lock of the specified object.
If the lock is free: The thread takes the lock, enters the block, and executes the code.
If the lock is taken: The thread waits (blocks) outside until the lock is released.
3. In the VotingSystem Example: When you wrote synchronized(this) inside the VoteCounter class:
The Object:
thisrefers to thecentralCounterobject you created inmain.The Action:
Voter_Alice reaches line 24. She grabs the lock for
centralCounter.She enters the critical section (lines 25-30).
Voter_Bob reaches line 24. He tries to grab the lock for
centralCounter, but Alice has it.Bob is forced to wait outside the block.
Alice finishes line 30. The lock is automatically released.
Bob grabs the lock and enters.
In synchronization, there are two types of locks on threads:
- Object-level lock: Every object in java has a unique lock.
- Class level lock: Every class in Java has a unique lock which is nothing but a class level lock.
Summary Synchronization is the concept of coordinating threads. The Lock is the actual tool Java uses behind the scenes to make that coordination happen. You can think of the lock as the physical "key" to the room (the synchronized block).