3

I have a Spring Batch project with a simple custom reader and writer. When i run the code i end up with an endeless loop printing the first item "item 1". What am i doing wrong?

Here is my code:

Reader.java

public class Reader implements ItemReader<SimpleItem> {


public SimpleItem read() throws Exception, UnexpectedInputException, ParseException {
    if (getIterator().hasNext()) {
        return getIterator().next();
    }
    return null;
}

public Iterator<SimpleItem> getIterator() {
    List<SimpleItem> list = new ArrayList();
    list.add(new SimpleItem("item 1"));
    list.add(new SimpleItem("item 2"));
    return list.iterator();
}

}

Writer.java

public class Writer implements ItemWriter<SimpleItem> {
@Override
public void write(List<? extends SimpleItem> list) throws Exception {
    for(SimpleItem item : list) {
        System.out.println(item.getName()); // this prints item 1 endelessly
    }
}
}

1 Answer 1

2

Every call to ItemReader#read begins with a call to Reader#getIterator which means you get a new list with every time you call to read. You really only want to create the list once.

We already have a List based ItemReader implementation. You can take a look at the code for it on Github here: https://github.com/spring-projects/spring-batch/blob/master/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/ListItemReader.java

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.