Fatih Donmez
Fatih Donmez

Reputation: 4347

Java unsafe memory allocation limit

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

Upvotes: 3

Views: 1056

Answers (1)

Marco13
Marco13

Reputation: 54709

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.

Upvotes: 4

Related Questions