Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"but the compiler doesn't know this" - what's the sense?

Tags:

java

java-9

I've met a such kind of code and comments in the java.util.ImmutableCollections class:

static final class List0<E> extends AbstractImmutableList<E> {
    ...
    @Override
    public E get(int index) {
        Objects.checkIndex(index, 0); // always throws IndexOutOfBoundsException
        return null;                  // but the compiler doesn't know this
    } 
    ...
}

Why not just throw new IndexOutOfBoundsException(...)? What's the reason?

like image 502
Andremoniy Avatar asked Jan 11 '18 19:01

Andremoniy


2 Answers

Perhaps, it is just an avoiding of a code duplication, because otherwise it would be something like:

new IndexOutOfBoundsException(outOfBoundsMessage(..., ...)) 

but outOfBounds* methods are private, so by design somebody should call wrappers like return Preconditions.checkIndex(index, length, null)

like image 190
Andremoniy Avatar answered Sep 20 '22 15:09

Andremoniy


The implementation seems more design-oriented than just functionality here.

The reasons for the same could primarily be that the Preconditions.checkIndex is marked as an @HotSpotIntrinsicCandidate which means a code performance improvement is sought while this method is used internally.

Also, can notice that all the immutable list - containing 0(empty),1, 2 or N elements, created using the factory method of makes use of the Objects.checkIndex(int index, int length) which eventually relies on the above method call to possibly make some internal optimisations.


Brief over HotSpotIntrinsicCandidate from the library :-

The @HotSpotIntrinsicCandidate annotation is specific to the HotSpot Virtual Machine. It indicates that an annotated method may be (but is not guaranteed to be) intrinsified by the HotSpot VM.

A method is intrinsified if the HotSpot VM replaces the annotated method with hand-written assembly and/or hand-written compiler IR -- a compiler intrinsic -- to improve performance.

The @HotSpotIntrinsicCandidate annotation is internal to the Java libraries and is therefore not supposed to have any relevance for application code.

like image 33
Naman Avatar answered Sep 19 '22 15:09

Naman