'What is wrong with code - Trying to batch agent with similar account ID?

I am trying to batch Sales Invoice per customer . My agents are Invoice. I am looping through each of the account and checking how many invoices are there for each customer. Based on that changing the batch size. the batch Size calculated seems correct but the batching is not happening and batchSize is printed as 1 for each account.

LinkedHashMap<Integer, List<MyAgent>> productsWaiting = new 
LinkedHashMap<Integer, List<MyAgent>>();

for (int i = 0; i < wait.size(); i ++){

MyAgent myAgent = wait.get(i);
int id = myAgent.actNo;
if (!productsWaiting.containsKey(id)) productsWaiting.put(id, new ArrayList<MyAgent>());
productsWaiting.get(id).add(myAgent);

 }

for (int key : productsWaiting.keySet())
{
int id= key;
 batchsize= productsWaiting.get(id).size();
 batch1.set_batchSize(batchsize);

 traceln("iD: " + id  + "   batchsize    "  +  batchsize);

    for (MyAgent p:productsWaiting.get(id)) {
      
        //System.out.println(x);
        //traceln("actNo" +p.actNo  );
        batch1.set_batchSize(batchsize);
        wait.free(p);
        batch1.set_batchSize(batchsize);
                      
        traceln(batch1.batchSize);
        
        //System.out.println("Released  " +"Batch Size  " + x + "account ID-" + id);
 
    }
    
} 

   

Unable to change the batch size for each of account based on the invoices it contains.

Some logs are here

iD: 165691   batchsize    1
iD: 120895   batchsize    1
iD: 85295   batchsize    1
iD: 5080702   batchsize    2
iD: 121437   batchsize    1
iD: 174098   batchsize    1 

On the entry of the batch block I checked the batach Size ..

165691

batch Size    1

120895

batch Size    1

85295

batch Size    1

5080702

batch Size    1

5080702

batch Size    1

121437

batch Size    1

174098

batch Size    1

Every entry of agent has batch size of 1.. Could you pls point out the mistake in the code.



Solution 1:[1]

The batching itself happens in a separate event and not inside the loop. Because you're calling the function set_batchSize(int batchSize) from the inside of a loop, your Batch block will only take the last value defined by this function as the batch size. That's why the batch size of every agent is 1.

The same also goes for the function wait.free(Agent agent). This event will also take place only after you've finished calling the function to calculate the batch size.

So basically, instead of using a loop, you should only calculate the batch size for the next agent in the queue. Then you need to "wait" until the batching of this agent has taken place before you can calculate the batch size for the next agent.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nadia Galaske