Skip to content

Instantly share code, notes, and snippets.

@theotherian
Created August 11, 2013 03:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theotherian/6203215 to your computer and use it in GitHub Desktop.
Save theotherian/6203215 to your computer and use it in GitHub Desktop.
Bits.class is scary
Using ByteBuffer instances to allocate memory can be dodgy
static void reserveMemory(long size, int cap) {
// theotherian: yep, we are indeed synchronizing on a class
synchronized (Bits.class) {
if (!memoryLimitSet && VM.isBooted()) {
maxMemory = VM.maxDirectMemory();
memoryLimitSet = true;
}
// -XX:MaxDirectMemorySize limits the total capacity rather than the
// actual memory usage, which will differ when buffers are page
// aligned.
if (cap <= maxMemory - totalCapacity) {
reservedMemory += size;
totalCapacity += cap;
count++;
return;
}
}
// theotherian: may as well run the garbage collector while we're at it
System.gc();
try {
Thread.sleep(100);
} catch (InterruptedException x) {
// Restore interrupt status
Thread.currentThread().interrupt();
}
// theotherian: better synchronize again too
synchronized (Bits.class) {
if (totalCapacity + cap > maxMemory)
throw new OutOfMemoryError("Direct buffer memory");
reservedMemory += size;
totalCapacity += cap;
count++;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment