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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With