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();
    }
}

Popular Prag Prog topics Top

sdmoralesma
Title: Web Development with Clojure, Third Edition - migrations/create not working: p159 When I execute the command: user=&gt; (create-...
New
rmurray10127
Title: Intuitive Python: docker run… denied error (page 2) Attempted to run the docker command in both CLI and Powershell PS C:\Users\r...
New
gilesdotcodes
In case this helps anyone, I’ve had issues setting up the rails source code. Here were the solutions: In Gemfile, change gem 'rails' t...
New
New
Chrichton
Dear Sophie. I tried to do the “Authorization” exercise and have two questions: When trying to plug in an email-service, I found the ...
New
adamwoolhether
When trying to generate the protobuf .go file, I receive this error: Unknown flag: --go_opt libprotoc 3.12.3 MacOS 11.3.1 Googling ...
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
andreheijstek
After running /bin/setup, the first error was: The foreman' command exists in these Ruby versions: That was easy to fix: gem install fore...
New
bjnord
Hello @herbert ! Trying to get the very first “Hello, Bracket Terminal!" example to run (p. 53). I develop on an Amazon EC2 instance runn...
New
redconfetti
Docker-Machine became part of the Docker Toolbox, which was deprecated in 2020, long after Docker Desktop supported Docker Engine nativel...
New

Other popular topics Top

brentjanderson
Bought the Moonlander mechanical keyboard. Cherry Brown MX switches. Arms and wrists have been hurting enough that it’s time I did someth...
New
AstonJ
Curious to know which languages and frameworks you’re all thinking about learning next :upside_down_face: Perhaps if there’s enough peop...
New
AstonJ
poll poll Be sure to check out @Dusty’s article posted here: An Introduction to Alternative Keyboard Layouts It’s one of the best write-...
New
PragmaticBookshelf
Rust is an exciting new programming language combining the power of C with memory safety, fearless concurrency, and productivity boosters...
New
Exadra37
On modern versions of macOS, you simply can’t power on your computer, launch a text editor or eBook reader, and write or read, without a ...
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
DevotionGeo
The V Programming Language Simple language for building maintainable programs V is already mentioned couple of times in the forum, but I...
New
Margaret
Hello everyone! This thread is to tell you about what authors from The Pragmatic Bookshelf are writing on Medium.
1122 25133 743
New
PragmaticBookshelf
Author Spotlight James Stanier @jstanier James Stanier, author of Effective Remote Work , discusses how to rethink the office as we e...
New
AstonJ
This is a very quick guide, you just need to: Download LM Studio: https://lmstudio.ai/ Click on search Type DeepSeek, then select the o...
New

Latest in PragProg

View all threads ❯