⬅ Previous Topic
Java switch KeywordNext Topic ⮕
Java this Keyword⬅ Previous Topic
Java switch KeywordNext Topic ⮕
Java this Keywordsynchronized
Keyword in JavaThe 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.
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.
synchronized
in method declarationsA 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;
}
}
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.
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);
}
}
}
The synchronized(this)
block ensures that only one thread can print a document at a time using the same Printer
object.
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);
}
}
If multiple threads call Logger.log()
at the same time, only one can execute it at a time, regardless of instance.
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
If we remove the synchronized
keyword from the deposit()
method, the output may vary:
Final balance: 1724 (or some other incorrect number)
synchronized
to protect shared resourcessynchronized
keyword?⬅ Previous Topic
Java switch KeywordNext Topic ⮕
Java this KeywordYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.