Add null check to AsyncItemWriter

The AsyncItemWriter is used in conjunction with the AsyncItemProcessor
to unwrap the Futures that are returned by that processor.
Traditionally when an ItemProcessor returns null, it's considered having
been filtered out and should not be passed to the ItemWriter.  In this
case, the AsyncItemWriter was not checking for nulls so they were being
passed to the delegate ItemWriter.  Most of the OOTB ItemWriters do not
perform a null check prior to doing the write so they were throwing NPEs
when using this paradigm.
This commit is contained in:
Michael Minella
2014-09-11 11:50:07 -05:00
parent 4f32f623f0
commit 2fec70d25e
2 changed files with 137 additions and 7 deletions

View File

@@ -15,18 +15,18 @@
*/
package org.springframework.batch.integration.async;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;
import org.springframework.batch.item.ItemWriter;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;
public class AsyncItemWriter<T> implements ItemWriter<Future<T>>, InitializingBean {
private ItemWriter<T> delegate;
public void afterPropertiesSet() throws Exception {
Assert.notNull(delegate, "A delegate ItemWriter must be provided.");
}
@@ -38,12 +38,23 @@ public class AsyncItemWriter<T> implements ItemWriter<Future<T>>, InitializingBe
this.delegate = delegate;
}
/**
* In the processing of the {@link java.util.concurrent.Future}s passed, nulls are <em>not</em> passed to the
* delegate since they are considered filtered out by the {@link org.springframework.batch.integration.async.AsyncItemProcessor}'s
* delegated {@link org.springframework.batch.item.ItemProcessor}.
*
* @param items {@link java.util.concurrent.Future}s to be upwrapped and passed to the delegate
* @throws Exception
*/
public void write(List<? extends Future<T>> items) throws Exception {
List<T> list = new ArrayList<T>();
for (Future<T> future : items) {
list.add(future.get());
T item = future.get();
if(item != null) {
list.add(future.get());
}
}
delegate.write(list);
}
}