Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

background service call inside for loop in java?

I hope I can explain the problem in proper way :) I have an array of object (handleData).I get them from DB. I want to send them to server by calling service for each one individually. I put the service in a for loop to send all handleData (refer to code) .

Calling service is done a background . the response of each may not come as they sent orderly. and I have to do some update for each handleData I send.

problem : when the response comes I am not sure that if the regarded action (update of record) is done to the exact handleData that I want/sent properly.

private void sendDataOfTemplates() {
    ArrayList<FormHandleData> formHandleDatas = FormHandleData.getDatasFromDB(getContext(), 12, EnumDataStatusOfServer.NoSTATUS.getIntValue(),-1);// true means >> to send / -1 means no limit
    try {
        if (formHandleDatas != null && formHandleDatas.size() != 0) {
            for (int i = 0; i < formHandleDatas.size(); i++) {
                final FormHandleData handleData = formHandleDatas.get(i);
                if (handleData.status_in_server == EnumDataStatusOfServer.OPEN.getIntValue())
                    if (handleData.status_in_app == EnumDataStatusInApp.SAVED.getIntValue() || handleData.status_in_app == EnumDataStatusInApp.EDITED.getIntValue()) {
                        ServiceHelper.getInstance().sendDataOfTemplates(new ServiceHelper.ResponseListener() {
                            @Override
                            public void onResponse(String response) {
                                try {

                                    SimpleResponse simple_response = new Gson().fromJson(response, SimpleResponse.class);
                                    if (simple_response.isSuccessful()) {
                                       handleData.status_in_app = EnumDataStatusInApp.SENT.getIntValue();
                                        FormHandleData.UpdateDataTemplatesInDB(handleData, getContext(),false);
                                    } else {
                                    }
                                } catch (Exception e) {
                                }
                            }

                            @Override
                            public void onErrorResponse(VolleyError error) {
                            }
                        }, handleData);
                    }
            }
        }
    } catch (Exception e) {
    }

}
like image 669
iDeveloper Avatar asked Apr 22 '26 23:04

iDeveloper


1 Answers

problem : when the response comes I am not sure that if the regarded action (update of record) is done to the exact handleData that I want/sent properly.

If I understand correctly, you are asking if the surrounding local variable handleData which is being accessed by your anonymous ServiceHelper.ResponseListener subclass will always be the same object instance even though in the next for cycle the value of that variable will be different. The answer is yes. So you don't need to worry.

If you want to know more about how anonymous classes can capture variables from a surrounding scope, please read this part of the Oracle's Java tutorial, which says:

  • An anonymous class has access to the members of its enclosing class.
  • An anonymous class cannot access local variables in its enclosing scope that are not declared as final or effectively final.

So the fact that the surrounding variable can be accessed means it is (effectively) final from the perspective of the anonymous class, i.e. it does not change.

Here is a little demonstration using multiple threads:

package de.scrum_master.app;

public class WhoDoesWhat {
  private String name;
  private final String action;

  public WhoDoesWhat(String name, String action) {
    this.name = name;
    this.action = action;
  }

  public String getName() {
    return name;
  }

  @Override
  public String toString() {
    return name + " -> " + action;
  }
}
package de.scrum_master.app;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class Application {
  private static final Random RANDOM = new Random();

  public static void main(String[] args) {
    List<WhoDoesWhat> peopleDoingSomething = new ArrayList<>();
    peopleDoingSomething.add(new WhoDoesWhat("Galileo", "discover moons of Jupiter"));
    peopleDoingSomething.add(new WhoDoesWhat("Johannes", "determine the laws of planetary motion"));
    peopleDoingSomething.add(new WhoDoesWhat("Albert", "explain the precession of Mercury"));
    peopleDoingSomething.add(new WhoDoesWhat("Edwin", "notice something odd about recession speeds of galaxies"));

    for (WhoDoesWhat personDoingSomething : peopleDoingSomething) {
      new Thread(() -> {
        System.out.println("START " + personDoingSomething);
        try {
          int waitCycles = 1 + RANDOM.nextInt(10);
          for (int cycle = 0; cycle < waitCycles; cycle++) {
            System.out.println("  " + personDoingSomething.getName() + " is still being busy");
            Thread.sleep(250);
          }
        } catch (InterruptedException e) {
        }
        System.out.println("STOP " + personDoingSomething);
      }).start();
    }
  }
}

The console log could look like this:

START Johannes -> determine the laws of planetary motion
START Albert -> explain the precession of Mercury
START Galileo -> discover moons of Jupiter
START Edwin -> notice something odd about recession speeds of galaxies
  Albert is still being busy
  Johannes is still being busy
  Edwin is still being busy
  Galileo is still being busy
  Galileo is still being busy
  Edwin is still being busy
  Johannes is still being busy
  Albert is still being busy
  Edwin is still being busy
  Galileo is still being busy
  Albert is still being busy
STOP Johannes -> determine the laws of planetary motion
  Edwin is still being busy
  Galileo is still being busy
  Albert is still being busy
  Galileo is still being busy
STOP Edwin -> notice something odd about recession speeds of galaxies
STOP Albert -> explain the precession of Mercury
  Galileo is still being busy
  Galileo is still being busy
  Galileo is still being busy
STOP Galileo -> discover moons of Jupiter
like image 68
kriegaex Avatar answered Apr 26 '26 20:04

kriegaex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!