-
Notifications
You must be signed in to change notification settings - Fork 0
Synchronized keyword in java
Devrath edited this page Feb 14, 2024
·
8 revisions
- About Synchronization
- How to synchronize in android using kotlin
- Synchronisation: Using the class instance as monitor object
- Java
Synchronized
block is a block of Java code that can be executed by only one thread at a time. - Monitor object ensures that no two threads can access a block of code, If that scenario arises, The monitor object makes it synchronised
- Assume that There are two methods in a class say getter & setter methods, and both the functions are
synchronised
in the samemonitor
object. Now if one thread is trying to access one of the functions, another thread is not able to access both of the functions in the class. - Also remember if two separate instances are created for two different objects and the monitor object is on the instance of the created objects, the accessibility of threads depends on the instance.
- Using the @Synchronized annotation:
@Synchronized
annotation
This annotation marks a method as synchronized, ensuring that only one thread can execute it at a time. It acts as a shorthand for using a synchronized block with this object as the lock.
class MyClass {
@Synchronized
fun synchronizedFunction() {
// Code that needs to be synchronized
}
}
- Using a synchronized block: This approach provides more control over synchronization. You explicitly specify a lock object, and only one thread can acquire the lock and execute the code within the block at a time.
class MyClass {
private val lock = Any() // Use a dedicated lock object
fun synchronizedFunction() {
synchronized(lock) {
// Code that needs to be synchronized
}
}
}