Rodrigo R
Rodrigo R

Reputation: 351

Synchronized annotation doens't working in Kotlin

I've a foreground service and i'm executing this method:

Controller().threadTest()
Controller().threadTest()

And my Controller class is:

class Controller{
    
        fun threadTest(){
            Thread(Runnable{
                threadOperation()
            }).start()
    
        }
    
        @Synchronized
        private fun threadOperation(){
            println("Thread start")
            Thread.sleep(3000)
            println("Thread finish")
        }
}

But the @Synchronized isn't working, because my log is:

Thread start
Thread start
Thread finish
Thread finish

What i'm doing wrong?

Upvotes: 2

Views: 1248

Answers (1)

hotkey
hotkey

Reputation: 148169

The @Synchronized annotation only prevents concurrent execution of a function in calls on the same instance. In your case, you are creating two instances of Controller().

You will get the expected behavior (calls execution one-by-one) if you modify the calling code so that it creates only one instance of your class, for example:

val controller = Controller()
controller.threadTest()
controller.threadTest()

Or, if you need mutual exclusion of concurrent calls on multiple Controller instances, you have to either move @Synchronized to another class whose instance both Controllers will reference or use other concurrency utilities, such as withLock calls on a shared lock.

Upvotes: 4

Related Questions