Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Kotlin object/singleton's methods synchronized?

Tags:

android

kotlin

Does it make any sense to add the @Synchronized annotation to an object's methods to make them atomic or it isn't needed?

For example:

object Singleton {

    var field1: Int = 0
        private set

    var field2: Int = 0
        private set

    @Synchronized fun updateFields(f1: Int, f2: Int) {
        field1 = f1
        field2 = f2
    }

}

I want to ensure that all the fields are updated when I read them from other objects. Should I keep the @Synchronized annotation?

like image 428
nitrico Avatar asked May 23 '16 08:05

nitrico


1 Answers

If you wish to achieve @Synchronized semantics you need to add it explicitly - as in your example.

The object Singleton {} is no different in this matter from an object created with e.g. val obj = Singleton().

One other way to ensure the fields are in sync is to model it explicitly e.g.:

object Singleton {
    @Volatile var state = State(0, 0)

    val field1: Int get() = state.field1
    val field2: Int get() = state.field2

    data class State(val field1: Int, val field2: Int)
}

And use Singleton.state = Singleton.state.copy(field2 = 3) to update the value. This obviously does not behave exactly the same as @Synchronized but is more explicit on the caller side that the values are to be in sync.

like image 130
miensol Avatar answered Oct 04 '22 01:10

miensol