mercredi 29 juillet 2015

How to Generalizing batch call on list in java

I have following repeated code.

  1. Give a list, other api parameters and max item supported in list.
  2. Divide list in sub partions.
  3. For each partition call api with given parameters.

So I have following repeated code for each api:

final List < List < GivenType >> partions = Lists.partition(givenListObject, batchSize);
final Iterator < List < GivenType >> iter = partions.iterator();
while (iter.hasNext()) {
    final APIResponse response = this.performSingleBatch(iter.next(), .....argument which need to be passed, argument count can differs from api to api);

    // Some custom processing with response object

    if (iter.hasNext()) {

        Thread.sleep(sleepTime);

    }
}

I was thinking to use callable. to reduce this repeated code. So I will have a function: performBatchRequest(callable,requestType,requestList,batchSize,timeToSleep)

So my code will look like: {Not 100% java syntax}

public void batchProcess(callable,GivenType,givenListObject,batchSize,sleepTime)
    final List < List < GivenType >> partions = Lists.partition(givenListObject, batchSize);
    final Iterator < List < GivenType >> iter = partions.iterator();
    while (iter.hasNext()) {
        callable.call();
        if (iter.hasNext()) {
            Thread.sleep(sleepTime);
        }
    }

A consumer can use it by:
batchProcess((list)-> {
 // there logic
}, GivenType,givenListObject,batchSize,sleepTime )

I have following question:

  1. Is it worth to avoid this code repetition ?
  2. Do you see problem with purposed solution?
  3. Any suggestion to improve purposed solution?

Aucun commentaire:

Enregistrer un commentaire