I have implemented an Iterator for my Pojo class.
The purpose here is to lazily decode multiple Pojos encoded in a buffer (bytes array).
To improve performance, it needs to be thread-safe to be correctly used from multiple Thread (parallel Stream).
The buffer is formed as follows :
- The first 4 bytes represent an int indicating how many bytes the next element uses in the buffer :
n. - The following
nbytes are encoded representation of a singlePojo. - 4 other bytes for the length of the next element.
- And so on ...
I think it is achieved with this code :
public class StringDecodeIterator implements Iterator<Pojo> {
private final int size;
private final PojoDecoder decoder;
private final byte[] buffer;
private int offset = 0;
private int count = 0;
private StringDecodeIterator(int size, PojoDecoder decoder, byte[] buffer) {
this.size = size;
this.decoder = decoder;
this.buffer = buffer;
}
@Override
public synchronized boolean hasNext() {
return this.count < this.size;
}
@Override
public Pojo next() {
return this.decoder.decode(offset(), this.buffer);
}
private synchronized int offset() {
if (!(this.count < this.size)) {
throw new NoSuchElementException("No more element");
}
this.count++;
int o = this.offset;
this.offset += Utils.getInt(o) + 4;
return o;
}
}
Here are some explanations/details :
sizeis the number of element to decode : It is a known value; we know how manyPojos are encoded.PojoDecoder decoderis an object that can decodePojos from a buffer at a given position.interface PojoDecoder { Pojo decode(int offset, byte[] buffer); }Utils#getInt(int);just converts 4 bytes to an int from the given position.PojoDecoder#decode(int, byte[])does not need to be in the thread-safety scope. Same instance can be used from multiple threads, as it does not hold any internal state.