Why parseInt warns about using valueOf

When looking at the source code for Integer.parseInt(String s, int radix) (java 8, 1.8.0_131), I found the following block of comments:

 /* * WARNING: This method may be invoked early during VM initialization * before IntegerCache is initialized. Care must be taken to not use * the valueOf method. */ 

While I understand the first part of IntegerCache, I don’t understand why there is a warning about valueOf and why in this context.

I see that valueOf() relies on parseInt() , but I still don't understand why this warning.

Can someone explain what exactly the comment warns me (and the context where valueOf should not be used), and what could go wrong.

Edit:

The code in Integer.valueOf (int i) seems to have changed since another question was asked from the comment below, now it

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

and must be saved earlier.

+49
java
Jun 19 '17 at 17:40
source share
2 answers

Can someone explain what exactly the comment warns me (and the context where valueOf should not be used), and what could go wrong.

The Integer class creates and maintains a cache of Integer objects that represent small integer values; by default, values ​​between -128 and 127 are covered (discussed here , here , and many other places). Integer.valueOf() returns an object from this cache when its argument represents a number in a range. The comment warns that parseInt() should not rely on valueOf() , because the former can be called before this cache is populated.

The incorrect behavior that can be expected in this case is not indicated and may possibly vary between versions of Java, but plausible possibilities are that null will be returned or an exception ( NullPointerException , IndexOutOfBoundsException , ...) would be thrown.

In any case, this is an internal comment in the implementation, not a comment for users of the Integer class. By the time any custom code is launched, the necessary cache initialization is complete, and Integer.valueOf() can be relied on to fully behave as in its API documentation .

+53
Jun 19 '17 at 17:53 on
source share

The source code is (almost) for reference only, javadoc does not contain this warning, because it is intended only for developers of Java itself.

This is probably a warning because there was some problem or error caused by someone using the valueOf method to encode the parseInt method, which can be called before the internal cache is initialized.

In other words, this warning is not intended for you unless you change the Integer class!

+36
Jun 19 '17 at 17:52
source share



All Articles