Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synchronize access to mutable fields with Kotlin's map delegation

Is this implementation safe to synchronize the access to the public fields/properties?

class Attributes(
    private val attrsMap: MutableMap<String, Any?> = Collections.synchronizedMap(HashMap())
) {

    var attr1: Long? by attrsMap
    var attr2: String? by attrsMap
    var attr3: Date? by attrsMap
    var attr4: Any? = null
    ...
}
like image 493
Akaki Kapanadze Avatar asked Feb 21 '26 22:02

Akaki Kapanadze


1 Answers

Mostly.

Because the underlying map is is only accessible via the synchronised wrapper, you can't have any issues caused by individual calls, such as simultaneous gets and/or puts (which is the main cause of race conditions): only one thread can be making such a call, and the Java memory model ensures that the results are then visible to all threads.

You could have race conditions involving a sequence of calls, such as iterating through the map, or a check followed by a modify, if the map could be modified in between.  (That sort of problem can occur even on a single thread.)  But as long as the rest of your class avoided such sequences, and didn't leak a reference to the map, you'd be safe.

And because the types Long, String, and Date are immutable, you can't have any issues with their contents being modified.

That is a concern with the Any parameter, though.  If it stored e.g. a StringBuilder, one thread could be modifying its contents while another was accessing it, with hilarious consequences.  There's not much you can do about that in a wrapper class, though.

By the way, instead of using a synchronised wrapper, you could use a ConcurrentHashMap, which would avoid the synchronisation in most cases (at the cost of a bit more memory).  It also provides many methods which can replace call sequences, such as getOrPut(); it's a really powerful tool for writing high-performance multithreaded code.

like image 177
gidds Avatar answered Feb 25 '26 06:02

gidds



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!