Nathan Osman
Nathan Osman

Reputation: 73235

Is it safe to use these variables within the doInBackground() method of an AsyncTask?

I have a method that looks something like this:

public void doSomething(final int num1, final int num2, final String str) {
    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {
            reallyComplexStatisticFunction(num1 + num2, str);
        }
    }.execute();
}

(I've greatly simplified the example.)

Is is wise to directly use the parameters supplied to doSomething() within the AsyncTask's doInBackground() method? Or will this cause thread-related issues?

Also, would it make any difference if the third parameter was a Context instance instead of a String?

Upvotes: 2

Views: 203

Answers (2)

frozenkoi
frozenkoi

Reputation: 3248

There are some guarantees that AsyncTask make, which you can see in it's documentation, but these are mostly regarding access to AsyncTask's fields.

In your example you're using primitives and String. Neither can really be modified so you're safe on that end.

However, if you're using an object that can be modified from another thread then you can't really be sure that it won't be modified between the moment you call execute() and when you actually use the object, that it won't be changed right as you read it inside doInBackground(), or worse that it will be modified as you try to modify it inside doInBackground() and possibly end in a corrupted state. For those cases you'll need to use synchronization to make sure that only one thread can read or modify such object at a time.

If you need to keep the object's value/state as it was when you called execute() by the time you use it in doInBackground() you might want to clone it and use this clone as a snapshot.

Upvotes: 2

Costi Ciudatu
Costi Ciudatu

Reputation: 38225

It is safe, as long as you are only passing primitives and/or references to immutable objects. Otherwise, you need to make sure that no other thread will be modifying the state of those objects (or synchronize the access to it).

As Strings are immutable in Java, your example looks fine.

Upvotes: 0

Related Questions