Akshay
Akshay

Reputation: 903

Android: wait for several Async Tasks to complete

I have to make several calls to save data into my database. I have to wait for all the calls to finish and then move further. I am using CountDownLatch and ExecutorService to achieve this. Following is my code:

    private void saveData(double latitude, double longitude) {
    try {
        performParallelTask(getListOfLatLngPair(latitude, longitude));
        preformPostTask();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

public void performParallelTask(List<LatLngPair> latLngPairList) throws InterruptedException {
    CountDownLatch doneLatch = new CountDownLatch(latLngPairList.size());
    ExecutorService executorService = Executors.newFixedThreadPool(latLngPairList.size());
    for (int i = 0; i < latLngPairList.size(); i++) {
        executorService.execute(new StopLatchedThread(doneLatch, latLngPairList.get(i)));
    }
    doneLatch.await();
}

public class StopLatchedThread implements Runnable {
    private final CountDownLatch stopLatch;
    private final LatLngPair latLngpair;

    public StopLatchedThread(CountDownLatch stopLatch, Fence latLngpair
                            ) {
        this.stopLatch = stopLatch;
        this.latLngpair = latLngpair;
    }

    public void run() {
        try {
            addLatLngPair();
        } finally {
            stopLatch.countDown();
        }
    }

    private void addLatLngPair() {
        Log.i(LOG_AREA, "add fence method");
        Engine.AddLatLngPair(latLngPair, new Engine
            .LatLngPairOperationListener() {
            @Override
            public void Succeed() {
                // do noting
            }

            @Override
            public void Failed(int reason) {
                Log.i(LOG_AREA, "Failed to add pair"
            }
        });
    }
}

private void preformPostTask() {
    Intent intent = new Intent(PairListActivity.this, PairListMapActivity.class);
    atartActivity(intent);
}

When I try to execute code, It starts Activity before threads finish their execution. May I know what is wrong in my code.

Upvotes: 1

Views: 797

Answers (1)

Yuriy
Yuriy

Reputation: 837

I strongly believe that Engine.AddLatLngPair is a asynchronous call therefore you have to call stopLatch.countDown(); in _Succeed()_ and _Failed(int reason)_ methods

By the way - you don't threads and executor service over there, you can just use

public void performParallelTask(List<LatLngPair> latLngPairList) throws InterruptedException {
CountDownLatch doneLatch = new CountDownLatch(latLngPairList.size());
for (int i = 0; i < latLngPairList.size(); i++) {
    addLatLngPair(doneLatch, latLngPairList.get(i));
}
doneLatch.await();

}

Upvotes: 1

Related Questions