androidandroid-asynctaskasynctaskloader

What happens when you modify class attributes in AsyncTaskLoader


When you try to modify/read a class attribute from the loadInBackground() method. What happens? Does android make a deep copy before passing in the variable?

Do modifications inside loadInBackground() actually change the class attribute values on the exterior context?

public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Void>
{
    public List<String> some_array  = new ArrayList();
    public String       some_string = "Hello world";

    ...

    @Override
    public Loader<Void> onCreateLoader(int id, Bundle args)
    {
        return new AsyncTaskLoader<Void>(MainActivity.this)
        {
            @Override
            protected void onStartLoading()
            {
                forceLoad();
            }

            @Override
            public Void loadInBackground()
            {
                some_array.add("some element");

                some_string = "good bye";
            }
        };
    }

    @Override
    public void onLoadFinished(Loader<Void> loader, Void data)
    {
        // what are the values of some_array and some_string now?
    }

    @Override
    public void onLoaderReset(Loader<Void> loader)
    {

    }
}

Solution

  • Okay so I manually tested it and found that in Java, arrays are passed as pointers to the background thread.

    Therefore, modifications in the background thread do alter the class variables, but this should be avoided as it is asynchronous and can quickly become unpredictable and chaotic.

    My current approach is to store the changes in a temporary, overwritable array and then merge them back in the onLoadFinished method, when we are all back in the same thread.