问题描述
我在使用 FileChannel.map 时遇到以下异常
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)
快速查看 OpenJdk 实现表明 FileChannelImpl
中的方法 map(..) 将 long
类型的 size
作为输入.但是在主体内部,它会将其与 Integer.MAX_VALUE
进行比较,如果大于该值则抛出错误.为什么将 long
大小作为输入,但将其限制为最大 integer
长度?
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?
我在 64 位 Windows-2k8 上使用 64 位 JRE 运行这个程序
I am running this program using 64bit JRE on 64bit Windows-2k8
推荐答案
这不是特定于实现的错误.大小在 FileChannel.map 一样长,但是...
It's not an implementation specific bug. The size is defined in the FileChannel.map as long, but...
size - 要映射的区域的大小;必须为非负且不大于 Integer.MAX_VALUE
所有兼容的 JVM 实现都将采用这种方式.我怀疑原因是历史的组合(谁需要访问大于 2GB 的文件?;)并试图在 Java 的更高版本中推动事情的发展(允许大于 Integer.MAX 的值会更容易)
而不是将数据类型从 int
更改为 long
.)
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
.)
很多人在 Java API 中发现这种基于 int 的思想对于任何文件非常令人困惑和短视.但请记住,Java 开发始于 1995 年!我确信 2GB 在当时似乎是一个相对安全的值.
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.
这篇关于为什么 FileChannel.map 最多占用 Integer.MAX_VALUE 的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!