Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Activity lag when using ExecutorService

Tags:

java

android

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.

like image 847
Anton Kazakov Avatar asked Dec 04 '25 09:12

Anton Kazakov


1 Answers

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.

like image 145
George Mulligan Avatar answered Dec 06 '25 23:12

George Mulligan



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!