0

I am working with a init() that need to be synchronise. But I have to run some set of instructions in init() which has to execute on main thread. So I created a runnable to add this instruction. And those instructions has some async calls.

So I am exploring efficient ways to block the init() untill all the instructions completes successfully.

Static void init() {
 new Handler(context.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
        // doing some async calls
        }
  }
}
Sandy K
  • 65
  • 1
  • 1
  • 8

1 Answers1

0

You need to synchronize the init() method and then use CompletionService to wait for Future to complete. Like so:

public synchronized void init() throws InterruptedException {
        Executor executor = Executors.newFixedThreadPool(4);
        CompletionService<String> completionService = new ExecutorCompletionService<String>(executor);

        // 4 tasks
        for (int i = 0; i < 4; i++) {
            completionService.submit(new Callable<String>() {
                public String call() {
                    return "i am an async task finished";
                }
            });
        }

        int received = 0;
        boolean errors = false;

        while (received < 4 && !errors) {
            Future<String> resultFuture = completionService.take(); // blocks if none available
            try {
                String result = resultFuture.get();
                System.out.println(result);
                received++;
            } catch (Exception e) {
                errors = true;
                /// some acceptable error handling;
            }
        }
    }

I have taken the code from this thread and adopted it for your needs. Don't forget to handle InterruptedException properly like described here.