I\'m writing GC friendly code to read and return to the user a series of byte[]
messages. Internally I reuse the same ByteBuffer which means I\'ll repeatedly re
I would define an intermediate object which you can invalidate. So your function would return an Iterator
, and ByteArray
is something like this:
class ByteArray {
private byte[] data;
ByteArray(byte[] d) { data = d; }
byte[] getData() {
if (data == null) throw new BadUseOfIteratorException();
return data;
}
void invalidate() { data = null; }
}
Then your iterator can invalidate the previously returned ByteArray
so that any future access (via getData
, or any other accessor you provide) will fail. Then at least if someone does something like Lists.newArrayList(myIterator)
, they will at least get an error (when the first invalid ByteArray
is accessed) instead of silently returning the wrong data.
Of course, this won't catch all possible bad uses, but probably the common ones. If you're happy with never returning the raw byte[]
and providing accessors like byte get(int idx)
instead, then it should catch all cases.
You will have to allocate a new ByteArray
for each iterator return, but hopefully that's a lot less expensive than copying your byte[]
for each iterator return.