Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does FileChannel.map take up to Integer.MAX_VALUE of data?

Tags:

java

io

nio

I am getting following exception when using FileChannel.map

Exception in thread "main" java.lang.IllegalArgumentException: Size exceeds Integer.MAX_VALUE
    at sun.nio.ch.FileChannelImpl.map(Unknown Source)
    at niotest.NioTest.readUsingNio(NioTest.java:38)
    at niotest.NioTest.main(NioTest.java:64)

Quickly looking into OpenJdk implementation shows that the method map(..) in FileChannelImpl takes size of type long as input. But inside the body, it compares it with Integer.MAX_VALUE and throws error if its greater than that. Why take long size as input but limit it to max integer length?

Anyone knows specific reason behind this implementation? or is it some kind of bug?

Source URL - http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/sun/nio/ch/FileChannelImpl.java

I am running this program using 64bit JRE on 64bit Windows-2k8

like image 568
siddharth178 Avatar asked Nov 10 '11 08:11

siddharth178


People also ask

How does FileChannel work JAVA?

Reads a sequence of bytes from this channel into the given buffer, starting at the given file position. This method works in the same manner as the read(ByteBuffer) method, except that bytes are read starting at the given file position rather than at the channel's current position.

What is a Filechannel?

A file channel is a SeekableByteChannel that is connected to a file. It has a current position within its file which can be both queried and modified . The file itself contains a variable-length sequence of bytes that can be read and written and whose current size can be queried.


1 Answers

It's not an implementation specific bug. The size is defined in the FileChannel.map as long, but...

size - The size of the region to be mapped; must be non-negative and no greater than Integer.MAX_VALUE

All compliant JVM implementations will be this way. I suspect the reason is a combination of history (who would need to access a file larger than 2GB? ;) and trying to push things forward in later versions of Java (it will be easier to allow values larger than Integer.MAX than it will be to change the data type from int to long.)

A lot of people find this int-based thinking in the Java API regarding anything File very confounding and short sighted. But remember, Java start development in 1995! I'm sure 2GB seemed like a relatively safe value at the time.

like image 164
Stu Thompson Avatar answered Nov 06 '22 04:11

Stu Thompson