views:

276

answers:

3

Is there a way to pin a byte array in java, so it never gets moved/compacted?

I am working on an application which is intended to have zero GCs during runtime, and I want to use primitive byte arrays that are pinned to a memory mapped area. Is there any way to do this or hack my way to it?

+5  A: 

Truly zero garbage collections? Really?

If so, I would suggest one of two options:

  1. Use a real-time JVM. There are options for managing nearly everything that separates general applications from soft to hard real-time systems.
  2. Think very seriously about just allocating far more memory than you'll need during a particular run. This isn't a sophisticated solution but if you have the memory available, try allocating 10 times more than you expect to need in your core footprint. It might just work and, you'll have to admit, RAM is cheaper than software engineering labor.

EDIT much later:

It just occurred to me that you should consider allocating your byte array statically. I.e., something like this:

/** Byte arrays that you absolutely have to keep. */
public class KeepForever {
    /** Note that I make no claims about thread safety in this simple example. */
    public static byte [] keepMe = new byte[100];
};

// Much later in example code ....

/** This should always succeed.  No worries about garbage collection. */
public void setMe(int index, byte newByte) {
    // Admittedly, this defeats several principles of OOD but it makes 
    // the point about the syntax.
    KeepForever.keepMe[index] = newByte;
}
Bob Cross
Truly zero garbage collections. My application allocates everything when it starts and never does any further allocations. But, I dont think not doing any allocation guarantees that the JVM won't run a GC and compact my heap, which is my concern.I dont want to use a real-time JVM, because I want high throughout and low latency, as opposed to a consistent medium latency and average throughput.
Pre-allocating the array will not stop it being moved during garbage collection (assuming something else triggers the GC.)
finnw
A: 

Although it's not related to direct memory mapping, an object that's still referenceable will not be GC'd. Anything where the reference stays live should be fine.

Steve B.
But with a generational-GC it will be moved in the memory.
Mnementh
+1  A: 

You can use a ByteBuffer/allocateDirect() This creates a byte buffer which is in the "c" space and doesn't use heap so it won't get moved and can be use efficiently with JNI calls.

Peter Lawrey
byte buffers have poorer performance than byte arrays, so I am trying to avoid using them.
Really? And I thought the whole point of ByteBuffer was to improve performance (for certain operations at least) ;) Either you need this functionality or you don't.
Peter Lawrey