- 1Java Exceptions
- 2Java Keywords
- 3Java abstract Keyword
- 4Java assert Keyword
- 5Java boolean Keyword
- 6Java break Keyword
- 7Java byte Keyword
- 8Java case Keyword
- 9Java catch Keyword
- 10Java char Keyword
- 11Java class Keyword
- 12Java const Keyword
- 13Java continue Keyword
- 14Java default Keyword
- 15Java do Keyword
- 16Java double Keyword
- 17Java else Keyword
- 18Java enum Keyword
- 19Java extends Keyword
- 20Java final Keyword
- 21Java finally Keyword
- 22Java float Keyword
- 23Java for Keyword
- 24Java goto Keyword
- 25Java if Keyword
- 26Java implements Keyword
- 27Java import Keyword
- 28Java instanceof Keyword
- 29Java int Keyword
- 30Java interface Keyword
- 31Java long Keyword
- 32Java native Keyword
- 33Java new Keyword
- 34Java null Keyword
- 35Java package Keyword
- 36Java private Keyword
- 37Java protected Keyword
- 38Java public Keyword
- 39Java return Keyword
- 40Java short Keyword
- 41Java static Keyword
- 42Java strictfp Keyword
- 43Java super Keyword
- 44Java switch Keyword
- 45Java synchronized Keyword
- 46Java this Keyword
- 47Java transient Keyword
- 48Java try Keyword
- 49Java void Keyword
- 50Java volatile Keyword
- 51Java while Keyword
- 52Java String Methods - Syntax and Description
- 53Java String
charAt()
method - 54Java String
codePointAt()
method - 55Java String
codePointBefore()
method - 56Java String
codePointCount()
method - 57Java String
compareTo()
method - 58Java String
compareToIgnoreCase()
method - 59Java String
concat()
method - 60Java String
contains()
method - 61Java String
contentEquals()
method - 62Java String
copyValueOf()
method - 63Java String
endsWith()
method - 64Java String
equals()
method - 65Java String
equalsIgnoreCase()
method - 66Java String
format()
method - 67Java String
getBytes()
method - 68Java String
getChars()
method - 69Java String
hashCode()
method - 70Java String
indexOf()
method - 71Java String
intern()
method - 72Java String
isEmpty()
method - 73Java String
join()
method - 74Java String
lastIndexOf()
method - 75Java String
length()
method - 76Java String
matches()
method - 77Java String
offsetByCodePoints()
method - 78Java String
regionMatches()
method - 79Java String
replace()
method - 80Java String
replaceAll()
method - 81Java String
replaceFirst()
method - 82Java String
split()
method - 83Java String
startsWith()
method - 84Java String
subSequence()
method - 85Java String
substring()
method - 86Java String
toCharArray()
method - 87Java String
toLowerCase()
method - 88Java String
toString()
method - 89Java String
toUpperCase()
method - 90Java String
trim()
method - 91Java String
valueOf()
method - 92Java ArrayList Methods - Complete Reference with Syntax and Description
- 93Java LinkedList Methods - Complete Reference with Syntax and Description
- 94Java HashMap Methods - Syntax and Descriptions
Java synchronized Keyword
Usage and Examples
synchronized
Keyword in Java
The synchronized
keyword in Java is a powerful tool used to control access to critical sections of code when multiple threads are involved. It ensures that only one thread can access a block or method at a time, helping to avoid thread interference and memory consistency issues.
Why Synchronization Is Needed
In a multi-threaded environment, when multiple threads try to modify shared data simultaneously, unexpected results can occur. This is called a race condition. Synchronization provides a mechanism to prevent race conditions by allowing only one thread to access a critical section at a time.
Types of Synchronization
- Method Synchronization – Using
synchronized
in method declarations - Block Synchronization – Synchronizing a specific portion of code inside a method
- Static Synchronization – Synchronizing static methods, which lock on the class object
1. Synchronized Instance Method
A synchronized instance method locks the current object (i.e., this
) so that only one thread at a time can execute any of its synchronized methods.
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
}
Explanation:
Here, the increment()
method is synchronized. If two threads try to call it at the same time on the same object, only one will succeed at a time.
2. Synchronized Block
Use synchronized blocks when you want to synchronize only a portion of the method instead of the entire method. This gives better performance by reducing lock scope.
class Printer {
public void printDoc(String docName) {
synchronized(this) {
System.out.println("Printing: " + docName);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Done Printing: " + docName);
}
}
}
Explanation:
The synchronized(this)
block ensures that only one thread can print a document at a time using the same Printer
object.
3. Synchronized Static Method
When you declare a static method as synchronized, the lock is applied on the class object, not the instance.
class Logger {
public static synchronized void log(String msg) {
System.out.println("Logging: " + msg);
}
}
Explanation:
If multiple threads call Logger.log()
at the same time, only one can execute it at a time, regardless of instance.
Real-World Example: Bank Account
This example shows how synchronization can prevent inconsistencies when multiple threads try to deposit money into a shared bank account.
class BankAccount {
private int balance = 0;
public synchronized void deposit(int amount) {
balance += amount;
}
public int getBalance() {
return balance;
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
BankAccount account = new BankAccount();
Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) account.deposit(1);
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) account.deposit(1);
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Final balance: " + account.getBalance());
}
}
Final balance: 2000
Without Synchronization
If we remove the synchronized
keyword from the deposit()
method, the output may vary:
Final balance: 1724 (or some other incorrect number)
Do's and Don'ts
- Use
synchronized
to protect shared resources - Use block synchronization to improve performance
- Don't overuse synchronization; it can lead to deadlocks and performance issues
- Avoid synchronizing on publicly accessible objects (like strings)
Common Interview Questions
- What is the purpose of the
synchronized
keyword? - What’s the difference between synchronized method and synchronized block?
- What happens if two threads call a synchronized method on different objects?
- What is the difference between object lock and class lock in Java?