问题
I'm writing a library project for multiple APPs to use. And for some reason, I must make a function mutual exclusion for different APPs, so I need a cross-process lock. 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. So file lock seems not applicable for me, so is there any other way to implement cross-process lock?
thanks~
回答1:
If you do not want to (or you can not) use flock or fcntl, maybe you can use LocalServerSocket to implement a spinlock. 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;
}
来源:https://stackoverflow.com/questions/23893431/how-to-implement-cross-process-lock-in-android