我正在为多个应用程序编写一个库项目。由于某种原因,我必须为不同的app做一个函数互斥,所以我需要一个跨进程锁。但据我所知,在安卓应用程序只能写自己的文件的目录在内部存储,外部存储是不可靠的,因为有些设备没有一个。所以文件锁似乎不适用于我,所以有没有其他方法来实现跨进程锁?
谢谢~
如果你不想(或者你不能)使用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;
}