Optimizing InputStream.skip(long)

- liangchenblue at gmail.com
Sun Oct 10 23:39:21 UTC 2021

On GitHub, xenoamess sent a pull request [1] that optimizes skipBuffer
array used by InputStream.skip by caching one for each InputStream
instance (static ones are unsafe per bug 7000600) like the
java.io.Reader class does (the reader one is behind a lock, while this
one is possibly concurrent).

Pros: Input streams that inherit the default skip logic can reduce
buffer array creation by reusing the compatible old array when the
skip method is called multiple times.

Cons: This adds a field to InputStream; the array cannot be GC'd until
the InputStream is GC'd. (But it has a length limit and the impact is

Additional Info: Most JDK InputStream implementations already
overrides this method to offer a more efficient implementation as
suggested in the Javadocs. Reader.skip(long) calls Reader.read(char[],
int, int), and this change doesn't affect the Reader class.

I wonder if this idea is worthy of a JDK issue so this patch may
eventually be accepted. Feel free to post any feedback, too!

[1]: https://git.openjdk.java.net/jdk/pull/5872

More information about the jdk-dev mailing list