Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I subclass ByteBuffer?

So the Java NIO architects didn't make a ByteBuffer interface, but rather a ByteBuffer class, which isn't a final class, but it has no package-public constructors, and therefore it can't be subclassed outside of its package. Phooey. :P

I have a program that uses memory-mapped file byte buffers (obtained via FileChannel.map()) in a bunch of places, and I'm trying to track down a nasty bug where the file in question is left open because there is at least one ByteBuffer that isn't released to garbage collection.

I would like to create an InstrumentedByteBuffer class that looks like a byte buffer, but decorates a regular ByteBuffer (or its subclasses e.g. MappedByteBuffer) and keeps track of its existence (including new buffers created by duplicate() and slice()) -- that way I can keep my code intact that uses the ByteBuffer, I just have to decorate the original byte buffer.

Is there any way to do this (via reflection or proxies or whatever) to get around the private constructors? I don't need to ship this into a final product, I just need to use it temporarily to solve this bug.

like image 846
Jason S Avatar asked Oct 10 '11 17:10

Jason S


2 Answers

I'm trying to track down a nasty bug where the file in question is left open because there is at least one ByteBuffer that isn't released to garbage collection

That doesn't make sense. An uncollected ByteBuffer won't stop a file being closed. You're barking up the wrong tree here. However there is a well-known problem with MappedByteBuffer whereby it is never garbage-collected, keeping the file effectively open. It's really a design problem: it has been known about for years but there is no real solution. The moral is don't use large numbers of MappedByteBuffers.

like image 57
user207421 Avatar answered Oct 29 '22 04:10

user207421


JMockit provides a convenient way of creating a mocked class. It may be of help in this case.

Mock the methods you are interested in, and let them do your bookkeeping and then call the original class' method.

like image 32
KarlP Avatar answered Oct 29 '22 05:10

KarlP