Java Reference
In-Depth Information
Using the implementations of the CompletionPolicy interface isn't your only option to determine
how large a chunk is. You can also implement it yourself. Before you look at an implementation, let's go
over the interface.
The CompletionPolicy interface requires four methods: two versions of isComplete , start , and
update . If you look at this through the lifecycle of the class, first the start method is called first. This
method initializes the policy so that it knows the chunk is starting. It's important to note that an
implementation of the CompletionPolicy interface is intended to be stateful and should be able to
determine if a chunk has been completed by its own internal state. The start method resets this internal
state to whatever is required by the implementation at the beginning of the chunk. Using
SimpleCompletionPolicy as an example, the start method resets an internal counter to 0 at the
beginning of a chunk. The update method is called once for each item that has been processed to update
the internal state. Going back to the SimpleCompletionPolicy example, update increments the internal
counter by one after each item. Finally, there are two isComplete methods. The first isComplete method
signature accepts a RepeatContext as its parameter. This implementation is intended to use its internal
state to determine if the chunk has completed. The second signature takes the RepeatContext and also
the RepeatStatus as parameters. This implementation is expected to determine based on the status
whether a chunk has completed. Listing 4-36 shows an example of a CompletionPolicy implementation
that considers a chunk complete once a random number of items fewer than 20 have been processed;
Listing 4-37 showing the configuration.
Listing 4-36. Random Chunk Size CompletionPolicy Implementation
package com.apress.springbatch.chapter4;
import java.util.Random;
import org.springframework.batch.repeat.CompletionPolicy;
import org.springframework.batch.repeat.RepeatContext;
import org.springframework.batch.repeat.RepeatStatus;
public class RandomChunkSizePolicy implements CompletionPolicy {
private int chunkSize;
private int totalProcessed;
public boolean isComplete(RepeatContext context) {
return totalProcessed >= chunkSize;
}
public boolean isComplete(RepeatContext context, RepeatStatus status) {
if (RepeatStatus.FINISHED == status) {
return true;
} else {
return isComplete(context);
}
}
public RepeatContext start(RepeatContext context) {
Random random = new Random();
chunkSize = random.nextInt(20);
 
Search WWH ::




Custom Search