Integer面试连环炮以及源码分析

2022-10-17,,,,

场景:

  昨天有位朋友去面试,我问他面试问了哪些问题,其中问了integer相关的问题,以下就是面试官问的问题,还有一些是我对此做了扩展。

问:两个new integer 128相等吗?

答:不。因为integer缓存池默认是-127-128;

问:可以修改integer缓存池范围吗?如何修改?

答:可以。使用-djava.lang.integer.integercache.high=300设置integer缓存池大小

问:integer缓存机制使用了哪种设计模式?

答:亨元模式;

问:integer是如何获取你设置的缓存池大小?

答:sun.misc.vm.getsavedproperty("java.lang.integer.integercache.high");

问:sun.misc.vm.getsavedpropertysystem.getproperty有啥区别?

答:唯一的区别是,system.getproperty只能获取非内部的配置信息;例如java.lang.integer.integercache.highsun.zip.disablememorymappingsun.java.launcher.diagsun.cds.enablesharedlookupcache等不能获取,这些只能使用sun.misc.vm.getsavedproperty获取

integer初始化源码分析

private static class integercache {
    static final int low = -128;
    static final int high;
    static final integer cache[];

    static {
        // high value may be configured by property
        int h = 127;
        string integercachehighpropvalue =
            sun.misc.vm.getsavedproperty("java.lang.integer.integercache.high");
        if (integercachehighpropvalue != null) {
            try {
                int i = parseint(integercachehighpropvalue);
                i = math.max(i, 127);
                // maximum array size is integer.max_value
                h = math.min(i, integer.max_value - (-low) -1);
            } catch( numberformatexception nfe) {
                // if the property cannot be parsed into an int, ignore it.
            }
        }
        high = h;

        cache = new integer[(high - low) + 1];
        int j = low;
        for(int k = 0; k < cache.length; k++)
            cache[k] = new integer(j++);

        // range [-128, 127] must be interned (jls7 5.1.7)
        assert integercache.high >= 127;
    }

    private integercache() {}
}

vm.class源码分析:

初始化:

static {
    allowarraysyntax = defaultallowarraysyntax;
    savedprops = new properties();
    finalrefcount = 0;
    peakfinalrefcount = 0;
    initialize();
}

getsavedproperty方法:

public static string getsavedproperty(string var0) {
    if (savedprops.isempty()) {
        throw new illegalstateexception("should be non-empty if initialized");
    } else {
        return savedprops.getproperty(var0);
}    

savedprops.getproperty方法:

public string getproperty(string key) {
    object oval = super.get(key);
    string sval = (oval instanceof string) ? (string)oval : null;
    return ((sval == null) && (defaults != null)) ? defaults.getproperty(key) : sval;
}

system.java源码分析:

/**
 * 初始化系统类。 线程初始化后调用。
 */
private static void initializesystemclass() {

    /**
     * vm可能会调用jnu_newstringplatform()来在“props”初始化期间设置那些编码敏感属性(user.home,user.name,boot.class.path等),
     * 它们可能需要通过system.getproperty()进行访问, 在初始化的早期阶段已经初始化(放入“props”)的相关系统编码属性。
     * 因此,请确保初始化时可以使用“props”,并直接将所有系统属性放入其中。
     */
    props = new properties();
    initproperties(props);  // initialized by the vm

    /**
     * 某些系统配置可以由vm选项控制,例如用于支持自动装箱的对象标识语义的最大直接内存量和整数高速缓存大小。 通常,库将获得这些值
     * 来自vm设置的属性。 如果属性是
     * 仅限内部实现使用,应从系统属性中删除这些属性。
     *
     *   请参阅java.lang.integer.integercache和
     *   例如,sun.misc.vm.saveandremoveproperties方法。
     *
     *   保存系统属性对象的私有副本,该副本只能由内部实现访问。 去掉
     * 某些不适合公共访问的系统属性。
     */
    sun.misc.vm.saveandremoveproperties(props);


    lineseparator = props.getproperty("line.separator");
    sun.misc.version.init();

    fileinputstream fdin = new fileinputstream(filedescriptor.in);
    fileoutputstream fdout = new fileoutputstream(filedescriptor.out);
    fileoutputstream fderr = new fileoutputstream(filedescriptor.err);
    setin0(new bufferedinputstream(fdin));
    setout0(newprintstream(fdout, props.getproperty("sun.stdout.encoding")));
    seterr0(newprintstream(fderr, props.getproperty("sun.stderr.encoding")));

    /**
     * 现在加载zip库,以防止java.util.zip.zipfile稍后尝试使用它来加载此库。
     */
    loadlibrary("zip");

    // 为hup,term和int(如果可用)设置java信号处理程序。
    terminator.setup();

    /**
     * 初始化需要为类库设置的任何错误的操作系统设置。
     * 目前,除了在使用java.io类之前设置了进程范围错误模式的windows之外,这在任何地方都是无操作的。
     */
    sun.misc.vm.initializeosenvironment();

    /**
     * 主线程没有像其他线程一样添加到其线程组中; 我们必须在这里自己做。
     */
    thread current = thread.currentthread();
    current.getthreadgroup().add(current);

    // 注册共享秘密
    setjavalangaccess();

    /**
     * 在初始化期间调用的子系统可以调用sun.misc.vm.isbooted(),以避免执行应该等到应用程序类加载器设置完毕的事情。
     * 重要信息:确保这仍然是最后一次初始化操作!
     */
    sun.misc.vm.booted();
}

重点看这句:sun.misc.vm.saveandremoveproperties(props);他会移除系统内部使用的配置,咱们来看看源码是如何操作的。

sun.misc.vm.saveandremoveproperties方法:

public static void saveandremoveproperties(properties var0) {
    if (booted) {
        throw new illegalstateexception("system initialization has completed");
    } else {
        savedprops.putall(var0);
        string var1 = (string)var0.remove("sun.nio.maxdirectmemorysize");
        if (var1 != null) {
            if (var1.equals("-1")) {
                directmemory = runtime.getruntime().maxmemory();
            } else {
                long var2 = long.parselong(var1);
                if (var2 > -1l) {
                    directmemory = var2;
                }
            }
        }

        var1 = (string)var0.remove("sun.nio.pagealigndirectmemory");
        if ("true".equals(var1)) {
            pagealigndirectmemory = true;
        }

        var1 = var0.getproperty("sun.lang.classloader.allowarraysyntax");
        allowarraysyntax = var1 == null ? defaultallowarraysyntax : boolean.parseboolean(var1);
        //移除内部使用的配置,不应该让看到这些配置信息
        var0.remove("java.lang.integer.integercache.high");
        var0.remove("sun.zip.disablememorymapping");
        var0.remove("sun.java.launcher.diag");
        var0.remove("sun.cds.enablesharedlookupcache");
    }
}

《Integer面试连环炮以及源码分析.doc》

下载本文的Word格式文档,以方便收藏与打印。