Search code examples
androidsemaphoreandroid-syncadapter

Semaphore to coordinate two sync adapters results in an InterruptedException


I have two sync adapters, and I would like each one to wait until the other finishes before it starts execution. I used the following technique with a semaphore:

public class SyncerOne extends AbstractThreadedSyncAdapter {
    protected static Semaphore semaphore = new Semaphore(1);
...
    @Override
    public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult)
    {
            semaphore.acquire();
            doMyStuff();
            semaphore.release();
    }

    public static Semaphore getSemaphore() {
        return semaphore;
    }


public class SyncerTwo extends AbstractThreadedSyncAdapter {
...
    @Override
    public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult)
    {
            Semaphore semaphore = SyncerOne.getSemaphore();
            semaphore.acquire();
            doMyStuff();
            semaphore.release();
    }

It all works well when no one needs to wait, but once one of the sync adapters needs to wait in acquire(), an InterruptedException is raised:

10-29 19:08:38.777: W/System.err(419): java.lang.InterruptedException
10-29 19:08:38.787: W/System.err(419):  at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireSharedInterruptibly(AbstractQueuedSynchronizer.java:1280)

Any ideas why?


Solution

  • Try using Semaphore.acquireUninterruptibly() rather than Semaphore.acquire().

    http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Semaphore.html#acquireUninterruptibly()