Apollo Kotlin: New Multiplatform Memory Manager
Benoit Lubek
Back in May, we shared about how Apollo Kotlin started supporting the Hierarchical project structure. Following the Kotlin Multiplatform ecosystem, here is some more news, this time about the new Memory Manager.
Kotlin Native’s Memory Manager
Since its early days, Kotlin Native has had specific rules regarding multithreading and immutability:
- objects could only be accessed from the thread they were created in
- unless they had been “frozen”, in which case they could be accessed by multiple threads, but became immutable
These native-specific restrictions have been a source of friction in writing and sharing code among targets.
In Apollo Kotlin, following these rules meant that the library had to be accessed strictly from the Main thread on Apple targets, which was a hindrance.
Kotlin Native’s new memory manager (now beta) removes these specificities and with it, native code can for the most part be written like JVM code when it comes to concurrency. After some months of being opt-in, it will be the default starting with Kotlin 1.7.20.
Apollo Kotlin made the switch in version 3.5.0.
What does it mean for you?
- If your Multiplatform / Native project hasn’t yet switched to the new MM, you will need to do so before upgrading to 3.5.0:
// build.gradle.kts
kotlin.targets.withType(KotlinNativeTarget::class.java) {
binaries.all {
binaryOptions["memoryModel"] = "experimental"
}
}
- Calling the library exclusively from the Main thread on Apple is no longer required *
- You can now use Kotlin’s
runTest
in all unit tests - Initial benchmarks indicate that performance is improved by up to 45% under the new memory manager!
*Suspend functions still need to be run from the Main thread from Swift / Objective C code – see KT-51297 for more information.
Conclusion
Kotlin Multiplatform continues to evolve, and with its new Memory Manager, it is becoming easier to use. By adopting it in its codebase, Apollo Kotlin 3.5.0 is able to get rid of a few threading and testing-related intricacies. We will continue to closely follow Kotlin Multiplatform’s evolutions so you can take advantage of it in your projects! As always, we love to hear your feedback, on GitHub, the Apollo Community, or the Kotlin Slack.