Skip to content

Synchronized keyword in java

Devrath edited this page Feb 13, 2024 · 8 revisions

Java Synchronized block is a block of Java code that can be executed by only one thread at a time.

Here's how you can synchronize a function in Kotlin Android:

  1. 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
    }
}
  1. 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
        }
    }
}