WeakReference by delegate in Kotlin

We have implemented AtomicReference using delegate feature of kotlin in the previous blog post. In a similar in this blog post, we will implement a weak reference delegate in Kotlin in a idiomatic way.

What is a weak reference anyways and why is it so important?

Weak reference objects, which do not prevent their referents from being made finalizable, finalized, and then reclaimed. Weak references are most often used to implement canonicalizing mappings.

Suppose that the garbage collector determines at a certain point in time that an object is weakly reachable. At that time it will atomically clear all weak references to that object and all weak references to any other weakly-reachable objects from which that object is reachable through a chain of strong and soft references. At the same time it will declare all of the formerly weakly-reachable objects to be finalizable. At the same time or at some later time it will enqueue those newly-cleared weak references that are registered with reference queues.

Accidental leakage of objects in Java can cause memory leak and you don’t want your app or server program to ever crash. Even though garbage collection is automatic in Java, it works on a feature called reference count check. When pressed for memory, GC will kick in and try to recover memory from unused objects.

It will look at unreferenced objects and deallocate memory for them. But let's say there are cross-references between objects it can end up in a deadlock and never GC’ed.

To avoid this, weak reference can help.

How to implement WeakReference Java API?

Instead of using the object directly, you wrap it around a WeakReference object.

Let’s be honest, this implementation comes with a lot of boilerplate and does not look simpler.

Like earlier, we use kotlin delegates feature to delegate the weak reference binding to an underlying WeakReference object. But the getters and setters look simple and unlike the annoying get() method as seen in the above example.

In this blog we are implementing both weak reference and soft reference as a delegate. The main method contains example usage of the delegate that we implemented.

I hope this helps someone looking at weak referencing something in their kotlin code.

Spread the kotlin love and leave your comments so that we can improvise this further.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store