javaandroidmultithreadingexecutorservice

How to promise completion of multiple threads?


I'm kinda new to the MultiThreading concept in java.
This question's title may have a similarity to previous questions on this topic but still, despite looking in the answers, I have yet succeeded accomplishing the following:

say on MainActivity I have a nested for loop. and in the inner loop I am running a method from another class that takes an interface as a callback, something like this:

MainActivity.java

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_display_prices, container, false);

    return v;

    for (i = 0; i < 10; i++) {

        for (i = 0; i < 4; i++){
              CategoryItemsDataSource.getCategoryItemsData(url, new CategoryItemsDataSource.OnCategoryItemsDataArrived() {
                        @Override
                        public void onCategoryItemsDataArrived(List<ProductItem> data, Exception e) {
                             getActivity.runOnUiThread(new Runnable() {

                                   //display retrieved data on UIThread...
                             });

                        }
              });
        }
    }

}

CategoryItemDataSource.java

 public class CategoryItemsDataSource {

public interface OnCategoryItemsDataArrived {
    void onCategoryItemsDataArrived(List<ProductItem> data, Exception e);
}

public static void getCategoryItemsData(final String[] url, final OnCategoryItemsDataArrived listener){

    ExecutorService service = Executors.newSingleThreadExecutor();
    service.execute(new Runnable() {
        @Override
        public void run() {
            try {
                List<ProductItem> data = new ArrayList<>();
                //retreiving data from web and appending to List<> Data....
                }
                listener.onCategoryItemsDataArrived(data, null);
            } catch (Exception e) {
                e.printStackTrace();
                listener.onCategoryItemsDataArrived(null, e);
            }
        }
    });
    service.shutdown();
}

I don't know how to access the ExecutorService instance from the CategoryItemDataSource class [I.E if I need to at all], in the MainActivity. hence, how am I suppose to ensure/promise completion of all the several threads generated in the inner loop?


Solution

  • create a counter variable; in the loop, increment the counter each time a new task is submitted to the executor. In the onCategoryItemsDataArrived method, decrement that counter; when it become zero, all tasks are finished. Provide atomic access to the counter: use AtomicInteger, or synchronized statement.