Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Java 技巧—懒加载 #29

Open
BingLau7 opened this issue Oct 25, 2017 · 0 comments
Open

Java 技巧—懒加载 #29

BingLau7 opened this issue Oct 25, 2017 · 0 comments

Comments

@BingLau7
Copy link
Owner

BingLau7 commented Oct 25, 2017

package io.github.binglau;

import java.util.function.Supplier;

/**
 * 文件描述: 懒加载大对象 Heavy
 * 利用类加载机制达到 LazyLoad 为单例
 */

public final class LazyLoad {
    private LazyLoad() {
    }

    private static class Holder {
        private static final LazyLoad INSTANCE = new LazyLoad();
    }

    public static final LazyLoad getInstance() {
        return Holder.INSTANCE;
    }

    private Supplier<Heavy> heavy = this::createAndCacheHeavy;
    private Normal normal = new Normal();

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

    public Normal getNormal() {
        return normal;
    }

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

    public static void main(String[] args) throws InterruptedException {
        LazyLoad.getInstance().getNormal();
        LazyLoad.getInstance().getHeavy();
    }

}

class Heavy {
    public Heavy() {
        System.out.println("Creating Heavy ...");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("... Heavy created");
    }
}

class Normal {
    public Normal() {
        System.out.println("Creating Normal ...");
        System.out.println("... Normal created");
    }
}
@BingLau7 BingLau7 changed the title 垃圾回收与内存分配策略 Java 技巧 —— 懒加载 Nov 1, 2017
@BingLau7 BingLau7 changed the title Java 技巧 —— 懒加载 Java 技巧—懒加载 Nov 1, 2017
@BingLau7 BingLau7 reopened this Nov 1, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant