Anton Kazakov
Anton Kazakov

Reputation: 2774

Activity lag when using ExecutorService

I am using multiple threads and ExecutorService to check when all of them finished.The problem is when I call method which init Executor service and execute threads (I call it in onCreate()) I have lag when activity starting. Here is my code:

public void test(){
    ExecutorService executor = Executors.newCachedThreadPool();
    executor.execute(new SomeTask());
    executor.execute(new SomeTask());
    executor.execute(new SomeTask());
    executor.shutdown();

    try{
        boolean finshed = executor.awaitTermination(1, TimeUnit.MINUTES);
    }
    catch (InterruptedException e){e.printStackTrace();}
    if (executor.isTerminated()){
        Toast.makeText(AddVehicleActivity.this,"DONE",Toast.LENGTH_LONG).show();
    }

}


 private class SomeTask implements Runnable
{
        @Override
        public void run(){
            final Request request = new Request.Builder()
                    .addHeader("Authorization",SharedPreferencesHelper.getToken())
                    .url("http://sapron.uveee.ru/api/vehicles/marks/get")
                    .build();
        try{
            Response response = client.newCall(request).execute();
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }else{
                Gson gson = new GsonBuilder().create();
                MarkResponse resp = gson.fromJson(response.body().charStream(), MarkResponse.class);

                for (int i = 0;i<resp.getData().size();i++){
                    Log.i("SHOWVEH", "onResponse: " + resp.getData().get(i).getImg());
                }
            }
            }catch (IOException e){
            e.printStackTrace();}

    }

}

Please help. Thanks.

Upvotes: 3

Views: 314

Answers (1)

George Mulligan
George Mulligan

Reputation: 11923

It will be better to use AsyncTask for this so you do not block the UI thread while waiting for all tasks to complete. Since it already has a callback method that executes on the UI thread it simplifies things a bit. Make sure you use the AsyncTask.executeOnExecutor() method so the tasks are executed in parallel.

After each task completes you can increment an int variable in onPostExecute(). Once the variable equals how many tasks you need to complete you will know all tasks are completed and you can update the UI in the activity accordingly.

Upvotes: 1

Related Questions