katit
katit

Reputation: 17915

Syncronizing tasks in Android

In my application I have multiple places where AsyncTask can be invoked to connect to web, download stuff, etc. It can be from Activity or from background service.

There is various issues because I'm reading and writing to SQLite database and when multiple tasks overlap on a similar operation (let's say GetMail runs on background and user started it manually).

I want to syncronize types of this tasks and wrote code like this. I'm not sure how to test it, it seems to be running OK but I wanted to get your opinion if it's valid..

public enum AsyncTasks
{
    GetMail,
    PostMail,
}
public class MyApplication extends Application
{
    private final ArrayList<AsyncTasks> mLockedAsyncTasks = new ArrayList<AsyncTasks>();


    public boolean lockAsyncTask(AsyncTasks task)
    {
        synchronized (mLockedAsyncTasks)
        {
            if (!mLockedAsyncTasks.contains(task)) 
            {
                mLockedAsyncTasks.add(task);
                return true;
            }

            return false;            
        }        
    }

    public void unlockAsyncTask(AsyncTasks task)
    {
        synchronized (mLockedAsyncTasks)
        {
            if (mLockedAsyncTasks.contains(task))
            {
                mLockedAsyncTasks.remove(task);
            }
        }
    }
}

Idea here is that I'm calling lockAsyncTask and if success - I proceed with HTTP stuff, otherwise skip since it's running already.

Upvotes: 0

Views: 134

Answers (1)

twaddington
twaddington

Reputation: 11645

It might be easier to just use an operation queue backed by a single worker thread. That way all tasks will be run in the order they are received. You can easily accomplish this by using the Executors factory methods. Here's a simple example:

private static final ExecutorService mThreadPool =
        Executors.newSingleThreadExecutor();

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mThreadPool.execute(new Runnable() {
        public void run() {
            // Do some work here...
        }
    });

    mThreadPool.execute(new Runnable() {
        public void run() {
            // Do some additional work here after
            // the first Runnable has finished...
        }
    });
}

Upvotes: 1

Related Questions