Coroutines

Sabine Vogel
Sep 2, 2018 · 2 min read

After learning the optimization of using a direct buffer for JNI access to avoid an extra copy from the JVM, I was excited to use it for large calculations in native code. I wanted to extend it to garbage free structures I learned about in Java, which are fast and GC free.

I found that libgdx, a gaming platform, was using a similar technique. This finding pointed out that using allocateDirect would still create memory on the Java heap. They solved it by creating a native object using malloc and managing the memory manually.

I then watched this googleIO17 talk and realized the java pointer will still be a problem with regard to improbable but possible GC. Enter this article from Eclipse which shows how to reference a C++ object using a reinterpret_cast. I could always operate on the object entirely from native methods, without even saving a pointer by using a global reference.

https://www.deviantart.com/inpbo/art/Mechanic-Owl-GIF-457470356

​​

I wanted a cache that would be hidden from the GC and fast. I was ready to try a native object but all the cross reaching was just going to slow me down.

Then the deciding factor arose again — -Android has the weakness that when a user force stops the app or it crashes unexpectedly there is no hook into a callback to tell the developer and all code terminates right there. If it stops that way, I cannot react.(unless I figure out how to patch it someday).

For caching, this means you need to be constantly persisting, and thereby all design is ruled by this need, even if it only happens very rarely. I am not optimistic that reaching across, even without the copy, plus persistence could be faster than just staying within java.

When I found this great article about coroutines and serialization in Kotlin it turned things around. A fast and lightweight thread certainly looks promising. I hope to find more gems like this!

I am going to delve deeper into C++, write entirely (NDK) native apps, and maybe stumble on something new — I have not given up on finding new areas of optimizations. In the meanwhile I am grateful to have finally found something new and useful for my toolbox.

Sabine Vogel

https://play.google.com/store/apps/dev?id=6427509609988261930

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade