KMM: The New Memory Management Approach

Working with concurrent code in KMM projects hasn’t been fun. This is due to the original Kotlin/Native memory management approach that had limitations when it came to concurrency. This alone has created a lot of problems and led to a steep learning curve for developers trying to share their Kotlin code between iOS and Android.

With the existing memory management approach, developers had to follow two rules for sharing states between threads, to avoid running into runtime exceptions. This approach brought about a new runtime state called frozen, and an extension function freeze(), which freezes an object and everything referenced by the object. I wrote about these and many more in a previous article.

The New Approach

The new memory management approach comes with no restrictions on sharing states between threads. New versions of kotlinx.coroutines can freely launch coroutines using a multithreaded background dispatcher without having to freeze objects that work in background threads.

Giving it a try

The development preview of the new memory management approach is available and can be turned on in your existing KMM project by following a few instructions as described here. With the new approach, you can remove all of the freeze() calls from your code and everything will work as usual.

To see a sample migration process, check out this branch of the TwittaSave project on Github.

NOTEAs of this day, the new memory management is still in the experimental stage. It’s not production-ready.

So, are you gonna give it a try? I think you should, maybe not in a production app yet though. ?

You can read more details about the new memory management approach on the Kotlin Blog.