Skip to content

Instantly share code, notes, and snippets.

@matsuhiro
Created April 9, 2020 15:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matsuhiro/bbb81b71c613800ea85ccfbbc8da6e03 to your computer and use it in GitHub Desktop.
Save matsuhiro/bbb81b71c613800ea85ccfbbc8da6e03 to your computer and use it in GitHub Desktop.
/***
* Excerpted from "Functional Programming in Java",
* published by The Pragmatic Bookshelf.
* Copyrights apply to this code. It may not be used to create training material,
* courses, books, articles, and the like. Contact us if you are in doubt.
* We make no guarantees that this code is fit for any purpose.
* Visit http://www.pragmaticprogrammer.com/titles/vsjava8 for more book information.
***/
package fpij;
import java.util.function.Supplier;
public class Holder {
private Supplier<Heavy> heavy = () -> createAndCacheHeavy();
public Holder() {
System.out.println("Holder created");
}
public Heavy getHeavy() {
return heavy.get();
}
//...
private synchronized Heavy createAndCacheHeavy() {
class HeavyFactory implements Supplier<Heavy> {
private final Heavy heavyInstance = new Heavy();
public Heavy get() { return heavyInstance; }
}
if(!HeavyFactory.class.isInstance(heavy)) {
heavy = new HeavyFactory();
}
return heavy.get();
}
public static void main(final String[] args) {
final Holder holder = new Holder();
System.out.println("deferring heavy creation...");
System.out.println(holder.getHeavy());
System.out.println(holder.getHeavy());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment