dtonhofer

dtonhofer

Functional Programming in Java, Second Edition: p 125: Going all the way with createCacheAndHeavy()

The example on page 125 comes closest to the mythical “self-modifying code” (a completely useless concept as modifying the data structure that the code works on is much easier, as seen here, but I digress!)

We can go one step further it seems and replace the anonymous class in createAndCacheHeavy() with another lambda (truly a closure that wraps around the Heavy instance) that matches Supplier<Lambda>. As we have no immediate way of testing the actual type of of the synthesized class that underpins a lambda (I think), we need to add a boolean to decide on whether we already did the replacement or not. This boolean does not need to be volatile or an AtomicBoolean as it is accessed from with synchronized code by the few earliest threads only. I hope I’m right about this.

Here we go:

class Holder {

    private Supplier<Heavy> heavy = () -> createAndCacheHeavy();
    private boolean firstCall = true;

    public Holder() {
        System.out.println("Holder created");
    }

    public Heavy getHeavy() {
        return heavy.get();
    }

    // We replace the supplier in the form of a lambda creating the Heavy instance
    // with another lambda that just returns the firstly created instance

    private synchronized Heavy createAndCacheHeavy() {
        if (firstCall) {
            System.out.println("First call to createAndCacheHeavy()");
            Heavy heavyInstance = new Heavy();
            heavy = () -> heavyInstance;
            firstCall = false;
        }
        else {
            System.out.println("Just another call to createAndCacheHeavy()");
            // Only happens if there was another thread that was queued on the
            // initial "Supplier" while the first thread performed the action
            // in the "firstCall" branch above. That initial "Supplier" has
            // already been replaced by the "Supplier" just returning
            // "heavyInstance". As this is a synchronized call, said "Supplier"
            // should be visible to this thread, so heavy.get() will do
            // what we expect.
        }
        return heavy.get();
    }
}

Where Next?

Popular Pragmatic Bookshelf topics Top

jesse050717
Title: Web Development with Clojure, Third Edition, pg 116 Hi - I just started chapter 5 and I am stuck on page 116 while trying to star...
New
jeremyhuiskamp
Title: Web Development with Clojure, Third Edition, vB17.0 (p9) The create table guestbook syntax suggested doesn’t seem to be accepted ...
New
New
jskubick
I think I might have found a problem involving SwitchCompat, thumbTint, and trackTint. As entered, the SwitchCompat changes color to hol...
New
brunogirin
When I run the coverage example to report on missing lines, I get: pytest --cov=cards --report=term-missing ch7 ERROR: usage: pytest [op...
New
brunogirin
When installing Cards as an editable package, I get the following error: ERROR: File “setup.py” not found. Directory cannot be installe...
New
s2k
Hi all, currently I wonder how the Tailwind colours work (or don’t work). For example, in app/views/layouts/application.html.erb I have...
New
rainforest
Hi, I’ve got a question about the implementation of PubSub when using a Phoenix.Socket.Transport behaviour rather than channels. Before ...
New
jwandekoken
Book: Programming Phoenix LiveView, page 142 (157/378), file lib/pento_web/live/product_live/form_component.ex, in the function below: d...
New
dachristenson
I just bought this book to learn about Android development, and I’m already running into a major issue in Ch. 1, p. 20: “Update activity...
New

Other popular topics Top

Rainer
My first contact with Erlang was about 2 years ago when I used RabbitMQ, which is written in Erlang, for my job. This made me curious and...
New
AstonJ
I ended up cancelling my Moonlander order as I think it’s just going to be a bit too bulky for me. I think the Planck and the Preonic (o...
New
AstonJ
This looks like a stunning keycap set :orange_heart: A LEGENDARY KEYBOARD LIVES ON When you bought an Apple Macintosh computer in the e...
New
AstonJ
If you are experiencing Rails console using 100% CPU on your dev machine, then updating your development and test gems might fix the issu...
New
New
First poster: joeb
The File System Access API with Origin Private File System. WebKit supports new API that makes it possible for web apps to create, open,...
New
PragmaticBookshelf
Author Spotlight: VM Brasseur @vmbrasseur We have a treat for you today! We turn the spotlight onto Open Source as we sit down with V...
New
PragmaticBookshelf
Author Spotlight: Peter Ullrich @PJUllrich Data is at the core of every business, but it is useless if nobody can access and analyze ...
New
First poster: bot
zig/http.zig at 7cf2cbb33ef34c1d211135f56d30fe23b6cacd42 · ziglang/zig. General-purpose programming language and toolchain for maintaini...
New
CommunityNews
A Brief Review of the Minisforum V3 AMD Tablet. Update: I have created an awesome-minisforum-v3 GitHub repository to list information fo...
New

Latest in Functional Programming in Java, Second Edition

Functional Programming in Java, Second Edition Portal

Sub Categories: