Question: I'm wondering how I'd code up a `ByteBuffer` recycling class that can get me a `ByteBuffer` which is at least as big as the specified length, and which can lock up `ByteBuffer` objects in use to prevent their use while they are being used by my code. This would prevent re-construction of `DirectByteBuffers` and such over and over, instead using existing ones. Is there an existing Java library which can do this very effectively? I know Javolution can work with object recycling, but does that extend to the `ByteBuffer` class in this context with the requirements set out?

Answer: 
It would be more to the point to be more conservative in your usage patterns in the first place. For example there is lots of code out there that shows allocation of a new ByteBuffer on every OP\_READ. This is insane. You only need two ByteBuffers at most per connection, one for input and one for output, and depending on what you're doing you can get away with exactly one. In extremely simple cases like an echo server you can get away with one BB for the entire application.

I would look into that rather than paper over the cracks with yet another layer of software.
This is just advice, not an answer. If you do implement some caching for DirectByteBuffer, then be sure to read about the GC implications, because the memory consumed by DirectByteBuffer is not tracked by the garbage collector.

Some references:

[A thread - featuring Stack Overflow's tackline](http://www.velocityreviews.com/forums/t147788-nio-outofmemoryexception.html)

[A blog post on the same subject](http://www.jroller.com/gkorland/entry/java_s_memory_isn_t)

[And the followup](http://www.jroller.com/gkorland/entry/java_s_memory_managment_is)