Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java memory allocation alignment

I know this is a weird question to ask in Java, but is there a way to let Java dynamic memory allocation be aligned with some alignment constraints? For example, is it possible to dynamically allocate objects that are aligned with the page size?

The reason I want to do this is because I'm going to access the Java object from native code through JNI interface, and the native code library requires the object to be aligned.

Thanks.

like image 221
Neo Hpcer Avatar asked Mar 11 '11 01:03

Neo Hpcer


People also ask

What is Java memory alignment?

You might assume that reducing the size of a struct or class saves the same amount of memory. However due to memory alignment in memory allocators it can make no difference, or perhaps more difference than you might expect. This is because the the amount of memory reserved is usually a multiple of the memory alignment.

How is memory allocated Java?

The Java Virtual Machine divides the memory into Stack and Heap Memory. For Java Virtual Machine, executing an application in its maximum potential can happen from stack and heap memory. Every time a new variable or object is declared, the memory allocates memory dedicated to such operations.

What does 4-byte aligned mean?

For instance, in a 32-bit architecture, the data may be aligned if the data is stored in four consecutive bytes and the first byte lies on a 4-byte boundary. Data alignment is the aligning of elements according to their natural alignment.

What is align in memory?

What is alignment? Alignment refers to the arrangement of data in memory, and specifically deals with the issue of accessing data as proper units of information from main memory. First we must conceptualize main memory as a contiguous block of consecutive memory locations. Each location contains a fixed number of bits.


1 Answers

No it is not possible. Keep in mind that objects on the heap in Java can move around during garbage collection. You have some options:

  1. Stop accessing Java objects directly from JNI. Copy what you care about into a JNI-provided buffer that the native code has already aligned.
  2. Use ByteBuffer.allocateDirect(). Then find a region of your buffer that is correctly aligned. One way to do that is to allocate the buffer at startup and repeatedly attempt the alignment sensitive operation at different offsets until it works. This is a hack!
like image 175
Spike Gronim Avatar answered Oct 03 '22 23:10

Spike Gronim