0

I want to fetch some data from service by callable and future. This is one of my code:

@Override
public void getCIFilesType(Consumer<String> consumer) {
    try {
        consumer.accept(serviceExecutor.submit(() ->
                service.getCi(EsupFactory.getConfigString(SETTING_ROOT_CI) + "GetCI",
                        translator.makeCiJsonObject("PCiName", "CI_FilesType")).execute())
                .get().body().string());
    } catch (ExecutionException | InterruptedException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

I have 10 method like this that execute like above.I used Executor service to run callable :

ExecutorService serviceExecutor = Executors.newSingleThreadExecutor();

I'm my activity I have a menu and then click on one item in the menu a fragment is a transaction in activity. All of the thread tasks immediately started in onViewCreated in fragment:

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    presenter.getCis();
}

But when I clicked on the menu item UI is frizzed till all task down then transaction is down. This is not the first time that I have this problem. Every time I use callable and executor service I do not know why UI is frizzed!!!!

This is profiler :

enter image description here

Someone has some guidance for me!!? Please do not tell me to use asyncTask :-)

What is a read line?? In ui thread I just do transaction not execute long running task!!!

Community
  • 1
  • 1
Cyrus the Great
  • 5,145
  • 5
  • 68
  • 149

1 Answers1

1

It happens because you're calling get() on the future returned by execute() method. According, to the docs,

If you would like to immediately block waiting for a task, you can use constructions of the form result = exec.submit(aCallable).get();

So, even though you use a background thread, by calling get you block your main thread until the background thread finishes your task.

To avoid UI junks you should've used callbacks.

Stanislav Shamilov
  • 1,746
  • 11
  • 20
  • What does mean `used callbacks`? I used `Consumer` as a callback!! I did not understand what is your point of `used callbacks` ?@StanislavShamilov – Cyrus the Great Feb 19 '19 at 11:52
  • Yes, you used it as a callback, but the problem is that you're calling get method. As I mentioned before, it's a blocking method, so calling thread(in this case, it's a Android Main Thread), will be blocked until a background thread finishes it's task. So call of the Consumer's accept method will be delayed until this get method is executed. – Stanislav Shamilov Feb 19 '19 at 12:10
  • I think, this SO post can help you: https://stackoverflow.com/questions/826212/java-executors-how-to-be-notified-without-blocking-when-a-task-completes. Or you can try using some frameworks to deal with concurrency, for example, RxJava – Stanislav Shamilov Feb 19 '19 at 12:11