Java Lambda and the Garbage Collector [part 2]

Tan Bui
2 min readJun 27, 2020

In Part 1, I discussed stateful vs stateless lambdas and how different they are in memory. In this part, we will verify that understanding with some Garbage Collector test cases.

The scenario to test if an object is garbage-collected is:

  • Step 1: having a variable which refers to the target instance. The instance could be a normal object or a lambda instance in the Heap.
  • Step 2: create a WeakReference of that instance
  • (Call your logic to work with the instance)
  • Step 3: remove the reference of the variable in step 1. If your logic doesn’t leak any reference to the target instance, there should be only one weak reference now.
  • Step 4: run the Garbage Collectors which should clear the instance, and the weak reference in step 2 should no longer hold the reference to the instance.

Here is the full example of testing stateful and stateless lambda:

To understandisGarbageCollected method more, please check its source from Vaadin Flow.

The result after executing this code is

Stateless: false
Stateful (local var): true

It means the stateful lambda is actually an instance in the Heap which is garbage-collected as usual by GC, while the stateless one isn’t.

These days I’ve been working a lot with Functional Interfaces in Java. So I’m making an aggressive investigation to understand it more, trying to map the Object-oriented programming mindset into lambda — Functional programming in Java. By writing this article early, I hope it will cover as much fundamental knowledge as possible when my mind is still fresh.

My future investigation of Lambda could be how it works with concurrent/parallel processing.

Thank you and have a nice day!

--

--

Tan Bui

Software Engineer @Smartly.io, phototaker, naturelover.