Java Multithreading – How to Avoid Nested Threads?

javamultithreading

I often have a situation where I first need to do something in the UI thread (Android in this case), then to some networkstuff in an extra thread, switch back to the UI thread and udate the layout, etc.

This looks most of the time like this:

MainActivity.getActivity().runOnUiThread(new Runnable(){
    @Override
    public void run{
        //Some code here
        new Thread(new Runnable(){
            @Override
            public void run(){
                //Even more code
                MainActivity.runOnUiThread(...);
            }
        }).start();
    }
});

I think this is not optimal in two ways:

  1. It is nested code and not easy enough to read. Yes, it could be simplified through Lambdas, but it would still have many nested parts.

  2. The UI code is all run on one thread, the one provided by the system. For the networking thread, for each part a new thread is started. That's bad for performance.

How can I improve this?

Best Answer

On android you can use AsyncTask (the equivalent of SwingWorker).

It has 3 methods you can override,

  • doInBackground for the work you want to do in the background thread,
  • onPostExecute called on the UI thread with the return value of doInBackground after it returns, and
  • onProgressUpdate also called on the UI thread in responce to calls to publishProgress.
Related Topic