Honestly I would just abandon using ByteBuffer entirely. Internally the JVM us using Unsafe anyway and you're just asking for trouble because honestly a lot of the code here is just flat out horrible.
I posted a lot of my writeup to the mechanical sympathy group.
There is explicit GC invocation, duplicate code blocks, and in one place a errant Thread.sleep( 100 ) with no explanation why the hell you're sleeping for 100ms.
This documents the page cache alignment issue:
and here's the bug in the JVM regarding the incorrect 'reserved memory' bug.
My plan is to use Unsafe for everything. including allocateMemory and freeMemory to release it. I'm going to bypass the entire JVM here as all the code is ugly, bug ridden, and has far too many locks.
For example, I was unaware of the synchronized methods in Cleaner! Ouch. Can you create a gists of this ? Perhaps some of us should write up a criticism of direct memory handling in the JVM and post it to the OpenJDK list along with examples of what is broken.
Unsafe makes this stuff much "easier" and at least the gotchas there can be fixed.
I had been using Netty ChannelBuffers within my code for things like sorting data and I realized that I have different requirements and it would be best for me to implement my own buffer system.
One issue is that I only need about 3-4 methods. The other is that I need a 64bit pointer so I can work with memory > 2GB. That and the performance benchmarks showing that Netty was slower with the Unsafe implementation was enough to push me in this direction.
I implemented a version of an UnsafeByteSlab (ByteSlab is the name of the interface I'm using here) which is oddly enough 5% slower than DirectByteBuffers. One issue was cache alignment, which I fixed, the other issue was that I'm doing too much range assertion and I can back off a bit...
I'll post the source here when I'm done.. you can see it now if you want but it's still in development. I imagine you can just take of my code and put it into Netty directly.
you should also implement a Netty setting for the equivalent of "MAX_DIRECT_MEMORY" so that you can give Netty a HARD limit on memory so that bug doesn't actually cause the OOM killer to kick in.
Kevin