Synchronization is used to control access to shared resources between multiple threads to prevent concurrent access that can cause inconsistent or corrupted data If multiple threads access a shared resource at the same time in which synchronization ensures that only one thread can synchronize a piece of code or a method at a time.
Synchronization Using synchronized Keyword
Synchronized Method
public class Program {
private int count;
public synchronized void increment() {
count++;
}
public synchronized int getCount() {
return count;
}
public static void main(String[] arg)
{
Program prog = new Program();
prog.increment();
System.out.println(prog.getCount());
}
}
The increment() and getCount() methods are marked as synchronized, which means that only one thread can execute either of these methods on the same instance of Counter at any given time.
Synchronized Block
public class BankAccount {
private double balance;
public void deposit(double amount) {
synchronized (this) {
balance += amount;
}
}
public void withdraw(double amount) {
synchronized (this) {
if (balance >= amount) {
balance -= amount;
}
}
}
public double getBalance() {
synchronized (this) {
return balance;
}
}
}
In the example above,
The synchronized (this) block is used inside methods to synchronize access to the balance variable.
Each synchronized block ensures that only one thread at a time can execute the code within the block, preventing concurrent access issues.
It is important to note that using synchronized(this) locks the current instance of the class
(this), which means other threads cannot execute synchronized blocks of the same instance simultaneously.
Key Points to Remember
Locking Mechanism- Synchronization in Java is implemented by an internal locking mechanism associated with each object. When a thread enters a synchronized method or block, it acquires a lock on the object, while other threads wait until the lock is released.
Scope- Synchronization can be applied at the method level (synchronized method) or within specific blocks (synchronized (object)).
Performance Considerations- Although synchronization ensures thread safety, it can affect performance due to thread contention (threads waiting for lock). Use synchronization only where necessary and consider options such as
java.util.concurrent package classes for more fine control and performance improvements.
Example-
class Counter {
private int count;
public synchronized void increment() {
count++;
}
public synchronized int getCount() {
return count;
}
}
public class Program {
public static void main(String[] args) {
Counter counter = new Counter();
// Creating multiple threads to increment the counter
Thread thread1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});
Thread thread2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});
// Start the threads
thread1.start();
thread2.start();
// Wait for threads to complete
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
// Print the final count
System.out.println("Final Count: " + counter.getCount());
}
}
Explanation
The Counter class has a synchronized increment() method.
The main class consists of two threads (thread1 and
thread2) that increment the Counter at the same time.
The join() method ensures that the main thread waits for thread1 and
thread2 to finish before publishing the final count.
Without synchronization, the final figure may not always be 2000, but that synchronization ensures that it is correct in concurrent situations.
Synchronization in Java ensures thread safety by simultaneous changes to multiple threads of shared data. It is a basic concept of multithreaded programming in order to maintain consistency and avoid race conditions.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Synchronization in Java
Synchronization is used to control access to shared resources between multiple threads to prevent concurrent access that can cause inconsistent or corrupted data If multiple threads access a shared resource at the same time in which synchronization ensures that only one thread can synchronize a piece of code or a method at a time.
Synchronization Using
synchronizedKeywordSynchronized Method
The
increment()andgetCount()methods are marked as synchronized, which means that only one thread can execute either of these methods on the same instance of Counter at any given time.Synchronized Block
In the example above,
synchronized (this)block is used inside methods to synchronize access to the balance variable.synchronized(this)locks the current instance of the class(this), which means other threads cannot execute synchronized blocks of the same instance simultaneously.Key Points to Remember
Locking Mechanism- Synchronization in Java is implemented by an internal locking mechanism associated with each object. When a thread enters a synchronized method or block, it acquires a lock on the object, while other threads wait until the lock is released.
Scope- Synchronization can be applied at the method level (
synchronizedmethod) or within specific blocks (synchronized (object)).Performance Considerations- Although synchronization ensures thread safety, it can affect performance due to thread contention (threads waiting for lock). Use synchronization only where necessary and consider options such as
java.util.concurrentpackage classes for more fine control and performance improvements.Example-
Explanation
Counterclass has a synchronizedincrement()method.mainclass consists of two threads (thread1andthread2) that increment theCounterat the same time.join()method ensures that the main thread waits forthread1andthread2to finish before publishing the final count.2000, but that synchronization ensures that it is correct in concurrent situations.Synchronization in Java ensures thread safety by simultaneous changes to multiple threads of shared data. It is a basic concept of multithreaded programming in order to maintain consistency and avoid race conditions.
Also, Read: Explain the concept of functional interfaces with examples in Java.