We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
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"); } }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
The text was updated successfully, but these errors were encountered: