zoukankan      html  css  js  c++  java
  • static inner class 什么时候被加载

    一直认为在加载outer class 的同时也会加载inner class 并且完成静态变量和代码块的初始化,今天在维基百科上面看到 “The static class definitionLazyHolder within it is not initialized until the JVM determines that LazyHolder must be executed”,颠覆了我之前的观点,于是做下列实验来证明一下:

    public class Initialize {
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            // TODO Auto-generated method stub
    
            helper h = new helper();
            
        }
    
    }
    
    class helper{
        static {
            System.out.println("helper is on going");
        }
        private static class holder{
            static {
                System.out.println("hodler is on going");
            }
        }
        holder returnh(){
            return new holder();
        }
    }

    执行的结果为:

    helper is on going

    也就是说只加载了helper 这个outer class 并初始化了静态块,而holder并没有被加载

    public class Initialize {
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            // TODO Auto-generated method stub
    
            helper h = new helper();
            h.returnh();
            
        }
    
    }
    
    class helper{
        static {
            System.out.println("helper is on going");
        }
        private static class holder{
            static {
                System.out.println("hodler is on going");
            }
        }
        holder returnh(){
            return new holder();
        }
    }

    执行结果为:

    helper is on going
    hodler is on going

    也就是说inner static class 和 outer static class 的加载时机是一样的:

    1. 访问静态类中的静态字段

    2. 访问静态类中的静态方法

    3. new 静态类

    基于静态内部类的此种特性可以来实现懒加载的单例模式,而且是线程安全的,实例代码如下:

    public class Something {
        private Something() {}
     
        private static class LazyHolder {
            private static final Something INSTANCE = new Something();
        }
     
        public static Something getInstance() { //只有在调用这个方法的时候才会生成唯一的Something 对象
            return LazyHolder.INSTANCE;
        }
    }
  • 相关阅读:
    Scrum为什么不喜欢“来自客户的频繁变更”?
    [转]SQL Server计算列
    宽容,是创新的土壤
    【转载】《2010年年度总结》
    远程维护需要“千里眼”
    TOP语句放到表值函数外,效率异常低下
    “设计应对变化”实例讲解一个数据同步系统
    “批量少次”还是“少量多次”邮件通信系统效率浅谈
    NYOJ117 求逆序数
    NYOJ92 图像有用区域
  • 原文地址:https://www.cnblogs.com/cruze/p/3725346.html
Copyright © 2011-2022 走看看