英文:
can Java nio FileLock give the same guarantee as mlock system call?
问题
Java的nio(New I/O)的FileLock能否提供与mlock系统调用相同的保证?我正在寻找一种可以防止内存区域被交换出或交换入的方法(换句话说,类似关系型数据库缓冲池通常所做的固定操作)。
我看到mlock系统调用可以锁定虚拟页面,使其不会被交换出或交换入。因此,我正在寻找在纯Java中实现类似功能的方法,但不通过JNI/JNA。
英文:
can Java nio FileLock give the same guarantee as mlock system call? looking for something that can keep a memory region from being swapped out or swapped in (other words pinning like rdbms buffer pools normally do)
I see that mlock system call can lock a virtual page such that it won't be swapped out or in. so looking for something similar in plain Java but not through JNI/JNA.
答案1
得分: 1
> Java NIO的FileLock
能否提供与mlock
系统调用相同的保证?
不能。FileLock
为文件或文件区域实现了“互斥”锁定。这是不同的。它相当于flock
系统调用的模拟。可以将man 2 flock
与man 2 mlock
进行比较。
> 我看到mlock
系统调用可以锁定虚拟页面,使其不会被交换出或交换入。我在普通的Java中寻找类似的功能,但不通过JNI/JNA实现。
在Java中,没有办法在不涉及自定义或第三方本机代码调用的情况下实现这一点。
另一点需要注意的是,mlock
系统调用要求完整的“root”特权或CAP_IPC_LOCK特权。
最后,通常你无法对Java对象在内存中的位置有足够的控制权,因此页面锁定不是明智的方法。堆中的任何对象都有可能在没有任何通知的情况下被GC重新定位。GC不会了解页面锁定的任何信息...因此,你的对象最终可能不再是页面锁定的,而锁定的页面中可能包含其他不相关的对象。因此,这只对堆外内存节点有用...而要创建这些节点通常需要使用JNI / JNA。
英文:
> Can Java NIO's FileLock
give the same guarantee as a mlock
system call?
No. FileLock
implements "mutual exclusion" locking for a file or a region of a file. It is something different. (It is the analog of the flock
syscall. Compare man 2 flock
with man 2 mlock
.)
> I see that mlock
system call can lock a virtual page such that it won't be swapped out or in. I am looking for something similar in plain Java but not through JNI/JNA.
There is no way to do it in Java that doesn't involve calls to custom or 3rd-party native code.
The other thing to note is that the mlock
system call requires either full "root" privilege or the CAP_IPC_LOCK privilege.
Finally, you typically don't have enough control over where Java objects are located in memory for page locking to be a sensible approach. Any object in the heap is liable to be relocated by the GC without any notice. The GC would not know anything the page locks ... so you would end up with the object no longer page locked, and other unrelated objects in the locked page. So this would only be useful for off-heap memory nodes ... and you typically need to use JNI / JNA to create those.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论