WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Kotlin · Advanced · question 51 of 100

What is the purpose of the @Synchronized annotation in Kotlin? When should you use it?

📕 Buy this interview preparation book: 100 Kotlin questions & answers — PDF + EPUB for $5

In Kotlin, the ‘@Synchronized‘ annotation is used to declare a function or a block of code as synchronized. Synchronization is used to prevent multiple threads from simultaneously accessing the same block of code, in order to avoid data races, race conditions and other concurrency issues.

When a function or block of code is marked with the ‘@Synchronized‘ annotation, only one thread at a time can execute the synchronized code. Other threads that try to access it while the synchronization is still in place will be blocked or put on hold until the synchronized code is released by the first thread.

Here’s an example:

class Counter {
    private var count = 0

    @Synchronized
    fun increment() {
        count++
    }

    @Synchronized
    fun decrement() {
        count--
    }

    fun getCount() = count
}

In this example, we have a simple ‘Counter‘ class that has two synchronized methods: ‘increment()‘ and ‘decrement()‘. These methods modify the ‘count‘ variable, which is a shared variable that could be accessed by multiple threads concurrently.

By marking these methods as synchronized, we ensure that only one thread at a time can modify the ‘count‘ variable, preventing race conditions and other concurrency issues.

It is important to note that the ‘@Synchronized‘ annotation can have a performance impact, as it introduces a lock that can slow down the program. Therefore, it’s important to use it only when necessary, for example, when working with shared data structures that are accessed by multiple threads.

In general, it’s a good practice to minimize the use of synchronized code, and to avoid blocking threads for long periods of time, in order to maintain a responsive and efficient program.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Kotlin interview — then scores it.
📞 Practice Kotlin — free 15 min
📕 Buy this interview preparation book: 100 Kotlin questions & answers — PDF + EPUB for $5

All 100 Kotlin questions · All topics