Just an update: I tried using ChunkListener and I was able to achieve a sorted result.
The writer stores the items in a list; calls from SkipListener or from the normal flow will not actually write anything to the file. It only does during afterChunk() where it sorts the items (by line number or by some field in that item) and writes the items through a delegate writer (i.e., flat file writer). Actual writing will be deferred in this setup.
This writer is registered as a listener. The only issue I currently see is that skips during write may no longer happen and exceptions during the actual write may just be logged. Is this workaround good?
Code:
public class SortingItemWriter<K, T> implements ItemWriter<T>, ChunkListener {
private ItemWriter<T> delegate;
private List<T> list;
private final Comparator<T> comparator;
//Initialization part omitted
@Override
public void write(List<? extends T> items) throws Exception {
list.addAll(items);
}
@Override
public void beforeChunk() {
// Nothing
}
@Override
public void afterChunk() {
Collections.sort(list, comparator);
try {
delegate.write(list);
} catch (Exception e) {
logger.error("Exception occured while writing sorted items using actual writer. Items not written: " + list, e);
} finally {
list = new ArrayList<T>();
}
}
}