用于协调两个同步适配器的信号量会导致InterruptedException

时间:2014-10-29 17:21:44

标签: android semaphore android-syncadapter

我有两个同步适配器,我希望每个同步适配器在开始执行之前等到另一个完成。我使用以下技术和信号量:

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();
    }

当没有人需要等待时一切正常,但是一旦其中一个同步适配器需要在acquire()中等待,就会引发InterruptedException:

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)

任何想法为什么?

1 个答案:

答案 0 :(得分:1)

尝试使用Semaphore.acquireUninterruptibly()而不是Semaphore.acquire()。

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