I found this stack overflow question from 2010: Lock or Pin java process into memory
Basically it says the way to lock a java process to memory is by using JNI. The example it points to is a broken link. Now that it's 2013 my question is.. Is there a better way? And is there an example somewhere of someone using mlock in Java? I'm extremely inexperienced with JNI and with C code in general, but quite familiar with Java (although I've NEVER used JNI).
Thanks
I'm wondering if there's a good java solution that doesn't involve JNI if possible.
There isn't. Pinning an application in memory is operating system specific, and not supported by the standard JVM APIs.
Pinning a rather dangerous thing to do ... because of the potential for serious impact on overall system performance. And consequently, it should require root privilege (or the equivalent) on any system that supports it.
I personally wouldn't try to do this, and would be very hesitant to use an application that did this. What ever it is that you are trying to achieve would (probably) better be done in some other way ...
I want to do it for security reasons.
Oh. So what you are actually trying to do is to stop "super secret" stuff being written to the swap/page space on disc?
I'm not convinced that mlock would prevent stuff being written to swap.
If someone can get access to the swap disc, the chances are that they can use other mechanisms to extract the data; e.g. by using "/dev/mem" or the equivalent to read stuff out of physical memory or the processes virtual memory.
The normal way to address the problem of "super secret" stuff on the swap disc is to use char arrays instead of strings to hold the stuff, and manually overwrite them with zeros as soon as they are done with.
Or investigate disc-level encryption.
I was looking for something similar and found this:
https://github.com/LucidWorks/mlockall-agent/
It appears to be a really nice solution to the problem of pinning Java memory. If you use it, make sure that your initial heap size (-XMs) is set to the same as your maximum heap size (-Xmx) - the documentation says that if you don't do this, any memory allocated after the initial heap will not be locked.
来源:https://stackoverflow.com/questions/14968942/how-to-lock-java-process-to-memory-mlock