tee*_*joe 3 android locking cross-process
我正在编写一个供多个APP使用的库项目.由于某种原因,我必须为不同的APP做一个函数互斥,所以我需要一个跨进程锁.但据我所知,在android中,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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1317 次 |
| 最近记录: |