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 Pragmatic topics Top

iPaul
page 37 ANTLRInputStream input = new ANTLRInputStream(is); as of ANTLR 4 .8 should be: CharStream stream = CharStreams.fromStream(i...
New
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
lirux
Hi Jamis, I think there’s an issue with a test on chapter 6. I own the ebook, version P1.0 Feb. 2019. This test doesn’t pass for me: ...
New
AleksandrKudashkin
On the page xv there is an instruction to run bin/setup from the main folder. I downloaded the source code today (12/03/21) and can’t see...
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
brunogirin
When installing Cards as an editable package, I get the following error: ERROR: File “setup.py” not found. Directory cannot be installe...
New
mert
AWDWR 7, page 152, page 153: Hello everyone, I’m a little bit lost on the hotwire part. I didn’t fully understand it. On page 152 @rub...
New
Keton
When running the program in chapter 8, “Implementing Combat”, the printout Health before attack was never printed so I assumed something ...
New
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

Other popular topics Top

Devtalk
Hello Devtalk World! Please let us know a little about who you are and where you’re from :nerd_face:
New
Exadra37
I am thinking in building or buy a desktop computer for programing, both professionally and on my free time, and my choice of OS is Linux...
New
dasdom
No chair. I have a standing desk. This post was split into a dedicated thread from our thread about chairs :slight_smile:
New
PragmaticBookshelf
Design and develop sophisticated 2D games that are as much fun to make as they are to play. From particle effects and pathfinding to soci...
New
AstonJ
We have a thread about the keyboards we have, but what about nice keyboards we come across that we want? If you have seen any that look n...
New
PragmaticBookshelf
Learn different ways of writing concurrent code in Elixir and increase your application's performance, without sacrificing scalability or...
New
PragmaticBookshelf
Build highly interactive applications without ever leaving Elixir, the way the experts do. Let LiveView take care of performance, scalabi...
New
husaindevelop
Inside our android webview app, we are trying to paste the copied content from another app eg (notes) using navigator.clipboard.readtext ...
New
DevotionGeo
I have always used antique keyboards like Cherry MX 1800 or Cherry MX 8100 and almost always have modified the switches in some way, like...
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

Latest in PragProg

View all threads ❯