Saul Lawliet bio photo

Saul Lawliet

Everything's gonna be OK.

Email Github

没有见过的用法,做个记录。

...

public class Holder {
    private Supplier<Heavy> heavy = () -> createAndCacheHeavy();

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

    private synchronized Heavy createAndCacheHeavy() {

        class HeavyFactory implements Supplier<Heavy> {
            private final Heavy heavyInstance = new Heavy();
            @Override
            public Heavy get() {
                return heavyInstance;
            }
        }

        if (!HeavyFactory.class.isInstance(heavy)) {
            heavy = new HeavyFactory();
        }

        return heavy.get();
    }
}