Created
August 11, 2013 03:12
-
-
Save theotherian/6203215 to your computer and use it in GitHub Desktop.
Bits.class is scary
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Using ByteBuffer instances to allocate memory can be dodgy |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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