Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java unsafe memory allocation limit

Tags:

java

Does Java sun Unsafe.allocateMemory has any limitation? I know that it's off heap so it's not subject to GC. But can we limit allocation size by JVM command like :

-XX:MaxDirectMemorySize
like image 614
Fatih Donmez Avatar asked Nov 20 '25 00:11

Fatih Donmez


1 Answers

The Unsafe#allocateMemory method is native, and the native implementation of Unsafe#allocateMemory directly calls os::malloc, delegating the work for the allocation to the underlying system. There is some bookkeeping and some debugging options, but it seems that there is no built-in mechanism for limiting the allocation size.

Depending on the application case, you might consider wrapping the Unsafe#allocateMemory call into an own method, that does a check for a size limit based on a command line parameter, as you suggested.

If your intention was to prevent a third party library (that uses Unsafe#allocateMemory internally) from allocating too much memory, I think there will be no reasonable way to achieve this.

like image 76
Marco13 Avatar answered Nov 22 '25 12:11

Marco13