3

我正在编写一个供多个应用程序使用的库项目。而且由于某种原因,我必须为不同的APP做一个功能互斥,所以我需要一个跨进程锁。但据我所知,在android APP中只能写入内部存储中自己的文件目录,而外部存储是不可靠的,因为有些设备没有。所以文件锁似乎对我不适用,那么有没有其他方法可以实现跨进程锁呢?

谢谢~

4

1 回答 1

5

如果您不想(或不能)使用flock 或fcntl,也许您可​​以使用LocalServerSocket 来实现自旋锁。例如:

public class SocketLock {
    public SocketLock(String name) {
        mName = name;
    }

    public final synchronized void tryLock() throws IOException {
        if (mServer == null) {
            mServer = new LocalServerSocket(mName);
        } else {
            throw new IllegalStateException("tryLock but has locked");
        }
    }

    public final synchronized boolean timedLock(int ms) {
        long expiredTime = System.currentTimeMillis() + ms;

        while (true) {
            if (System.currentTimeMillis() > expiredTime) {
                return false;
            }
            try {
                try {
                    tryLock();
                    return true;
                } catch (IOException e) {
                    // ignore the exception
                }
                Thread.sleep(10, 0);
            } catch (InterruptedException e) {
                continue;
            }
        }
    }

    public final synchronized void lock() {
        while (true) {
            try {
                try {
                    tryLock();
                    return;
                } catch (IOException e) {
                    // ignore the exception
                }
                Thread.sleep(10, 0);
            } catch (InterruptedException e) {
                continue;
            }
        }
    }

    public final synchronized void release() {
        if (mServer != null) {
            try {
                mServer.close();
            } catch (IOException e) {
                // ignore the exception
            }
        }
    }

    private final String mName;

    private LocalServerSocket mServer;
}
于 2015-03-31T05:49:57.967 回答