[英]How to implement cross process lock in android?
I'm writing a library project for multiple APPs to use. 我正在编写一个供多个APP使用的库项目。 And for some reason, I must make a function mutual exclusion for different APPs, so I need a cross-process lock.
由于某种原因,我必须为不同的APP做一个函数互斥,所以我需要一个跨进程锁。 But as far as I know, in android APPs can only write to it's own file's directory in internal storage, and external storage is unreliable because some device don't have one.
但据我所知,在android中,APP只能在内部存储中写入自己文件的目录,外部存储不可靠,因为某些设备没有。 So file lock seems not applicable for me, so is there any other way to implement cross-process lock?
所以文件锁似乎不适合我,所以有没有其他方法来实现跨进程锁?
thanks~ 谢谢〜
If you do not want to (or you can not) use flock or fcntl, maybe you can use LocalServerSocket to implement a spinlock. 如果你不想(或你不能)使用flock或fcntl,也许你可以使用LocalServerSocket来实现一个自旋锁。 For example:
例如:
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.