thread-safe lazy getter

65 views
Skip to first unread message

Pawel Veselov

unread,
Apr 14, 2023, 3:31:00 PM4/14/23
to Project Lombok
Hello.

I have a lot of these in a particular part of the code:
    public Value getValue() {
        if (value != null) { return value; }
        return value = makeNewValue()
    }

I'd love to replace them with the lazy getter, but the lazy getter is thread safe, which comes at a (certain) cost, which I don't want to pay, because all of this business happens inside a thread local variable as it is.

Would it be reasonable to ask for an additional annotation indicating that the access is thread-safe, and therefore adding the locking code is not needed?

Thank you,
  Pawel.

Reinier Zwitserloot

unread,
Apr 30, 2023, 12:29:39 PM4/30/23
to Project Lombok
I'd like to see a report about how expensive the thread safe aspect really is. From what I have read and the few times I've done some JMH work to check, if there is no thread contention happening, the thread safety mechanisms cost _very_ little time.

Pawel Veselov

unread,
May 2, 2023, 9:36:36 PM5/2/23
to project...@googlegroups.com
The cost is very low (I've had an email from somebody from the JVM
team stating that 15+ years ago).
However, it's still there (plus the cost of running extra VM instructions).
And those are linearly amplified by use (unless hotspot can optimize
those calls out all together)
This is, ATM, a balance between:
* paying the runtime cost (linear growth though)
* having bulkier code (engineering time cost, project dependent)
* maintaining thread-unsafe variant of lazy getter (Lombok devs
engineering time cost) PLUS juniors misinterpreting the
"thread-unsafe" flag, causing project engineering time cost.

Btw, there is an additional cost for handling nulles - the memory cost
of carrying an XReference instance, plus the GC cost to release that.
That cost is unnecessary if expensive() would never produce nulls.
Throw a "nullable=false" in for good measure?
Reply all
Reply to author
Forward
0 new messages