How to implement cross process lock in android?

后端 未结 1 1161
[愿得一人]
[愿得一人] 2020-12-18 13:25

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

相关标签:
1条回答
  • 2020-12-18 14:25

    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;
    }
    
    0 讨论(0)
提交回复
热议问题