相关疑难解决方法(0)

为什么parseInt警告使用valueOf

在查看Integer.parseInt(String s, int radix)(java 8,1.8.0_131)的源代码时,我发现了以下注释块:

/*
* WARNING: This method may be invoked early during VM initialization
* before IntegerCache is initialized. Care must be taken to not use
* the valueOf method.
*/
Run Code Online (Sandbox Code Playgroud)

虽然我理解了关于IntegerCache的第一部分,但我不明白为什么会出现这样的警告valueOf,以及为什么会出现这种情况.

我看到这valueOf()依赖parseInt(),但我仍然不明白为什么会有这个警告.

有人可以解释一下这个评论的确切含义(以及不应该使用valueOf的上下文),以及可能出现的问题.

编辑:

Integer.valueOf(int i)中的代码似乎已经改变,因为下面的评论中的其他问题被问到,现在是

public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}
Run Code Online (Sandbox Code Playgroud)

并且应该从之前的断言错误中保存.

java

51
推荐指数
2
解决办法
2961
查看次数

整数缓存有多大?

Integer具有缓存,缓存Integer值.因此,如果我使用方法valueOf或收件箱,新值将不会被实例化,而是从缓存中获取.

我知道默认缓存大小是127因为VM设置而可以扩展.我的问题是:在这些设置中缓存大小的默认值有多大,我可以操纵这个值吗?这个值取决于我使用的是哪个VM(32位还是64位)?

我现在正在调整遗留代码,可能需要从int转换为Integer.

澄清:遵循我在Java源代码中找到的代码

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) {
            int i = parseInt(integerCacheHighPropValue);
            i = Math.max(i, 127);
            // Maximum array size is Integer.MAX_VALUE
            h = Math.min(i, Integer.MAX_VALUE - (-low));
        }
        high = h;

        cache = …
Run Code Online (Sandbox Code Playgroud)

java boxing integer

8
推荐指数
1
解决办法
5754
查看次数

标签 统计

java ×2

boxing ×1

integer ×1