Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
580 views
in Technique[技术] by (71.8m points)

locking - How to implement cross process lock in android?

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~

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...