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

telemachus
Python Testing With Pytest - Chapter 2, warnings for “unregistered custom marks” While running the smoke tests in Chapter 2, I get these...
New
brianokken
Many tasks_proj/tests directories exist in chapters 2, 3, 5 that have tests that use the custom markers smoke and get, which are not decl...
New
sdmoralesma
Title: Web Development with Clojure, Third Edition - migrations/create not working: p159 When I execute the command: user=&gt; (create-...
New
AndyDavis3416
@noelrappin Running the webpack dev server, I receive the following warning: ERROR in tsconfig.json TS18003: No inputs were found in c...
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
AufHe
I’m a newbie to Rails 7 and have hit an issue with the bin/Dev script mentioned on pages 112-113. Iteration A1 - Seeing the list of prod...
New
taguniversalmachine
It seems the second code snippet is missing the code to set the current_user: current_user: Accounts.get_user_by_session_token(session["...
New
creminology
Skimming ahead, much of the following is explained in Chapter 3, but new readers (like me!) will hit a roadblock in Chapter 2 with their ...
New
EdBorn
Title: Agile Web Development with Rails 7: (page 70) I am running windows 11 pro with rails 7.0.3 and ruby 3.1.2p20 (2022-04-12 revision...
New
dachristenson
@mfazio23 Android Studio will not accept anything I do when trying to use the Transformations class, as described on pp. 140-141. Googl...
New

Other popular topics Top

siddhant3030
I’m thinking of buying a monitor that I can rotate to use as a vertical monitor? Also, I want to know if someone is using it for program...
New
AstonJ
SpaceVim seems to be gaining in features and popularity and I just wondered how it compares with SpaceMacs in 2020 - anyone have any thou...
New
DevotionGeo
I know that -t flag is used along with -i flag for getting an interactive shell. But I cannot digest what the man page for docker run com...
New
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
PragmaticBookshelf
Rust is an exciting new programming language combining the power of C with memory safety, fearless concurrency, and productivity boosters...
New
Margaret
Hello everyone! This thread is to tell you about what authors from The Pragmatic Bookshelf are writing on Medium.
1143 25816 759
New
PragmaticBookshelf
Build efficient applications that exploit the unique benefits of a pure functional language, learning from an engineer who uses Haskell t...
New
AstonJ
If you want a quick and easy way to block any website on your Mac using Little Snitch simply… File &gt; New Rule: And select Deny, O...
New
PragmaticBookshelf
Author Spotlight: Karl Stolley @karlstolley Logic! Rhetoric! Prag! Wow, what a combination. In this spotlight, we sit down with Karl ...
New
PragmaticBookshelf
Author Spotlight: Tammy Coron @Paradox927 Gaming, and writing games in particular, is about passion, vision, experience, and immersio...
New

Latest in Functional Programming in Java, Second Edition

Functional Programming in Java, Second Edition Portal

Sub Categories: