Home > database >  is there any way to stop part of process without disturbing whole process?
is there any way to stop part of process without disturbing whole process?

Time:06-15

I have a for loop which iterates on customer ids and I have process function which process those customer in the same for loop.

Scenario:-

while executing for loop, if the repetitive customer is found then we should check if the old process of customer is finished or not. if finished then we must wait.

here I don't want to halt my whole for loop execution as other customers having different ids can be processed.

so is there any way using that I can stop only part of process that is waiting for particular customer while executing others using same for loop.

example

for(customer:customers)
{
 if(customer.isRepeated())
 {
  if(customer.inProcess())
   {
    wait();
   }
 }
 process(customer);

}

CodePudding user response:

You could use a Deque.

Deque<Customer> toProcess;
//inialize and populate the queue
while( toProcess.size() > 0){
    //take the front
    Customer c = toProcess.remove();
    if( c.inProcess() ){
        //put it back at the tail.
        toProcess.offer(c);
        continue;
    }
    //operate on it.
}

CodePudding user response:

For the problem you've described, the multithreaded approach in the other answer is probably ideal. But if you want to keep it single-threaded and defer processing for customers that aren't ready yet while processing customers that are ready, then this might work.

Here, we create another list of waitingCustomers, which is a list of the customers that we would have called .wait() on. Instead of doing that, when we reach a customer who needs to wait, we put it in the waitingCustomers list. And then we repeat the entire block of code until the waitingCustomers list is empty.

List<Customer> waitingCustomers = customers;
do {
    List<Customer> toProcess = waitingCustomers;
    waitingCustomers = new ArrayList<>();

    for(customer : toProcess) {
        if(customer.isRepeated() && customer.inProcess()) {
            waitingCustomers.add(customer);
        } else {
            process(customer);
        }
    }
} while (waitingCustomers.size() > 0)

CodePudding user response:

You can use kind of Asynchronous programming for this:

new Thread(new Runnable() {
    public void run() {
        //Do whatever
    }
}).start();
  • Related