Explain with example to handle synchronization in Java.
Explain with example to handle synchronization in Java.
634
19-Jul-2024
Updated on 19-Jul-2024
Ashutosh Kumar Verma
19-Jul-2024Synchronization 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
synchronized
KeywordSynchronized 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 (
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-
Explanation
Counter
class has a synchronizedincrement()
method.main
class consists of two threads (thread1
andthread2
) that increment theCounter
at the same time.join()
method ensures that the main thread waits forthread1
andthread2
to 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.