Java file locking on a network

前端 未结 4 1429
执念已碎
执念已碎 2021-01-17 12:01

This is perhaps similar to previous posts, but I want to be specific about the use of locking on a network, rather than locally. I want to write a file to a shared location,

4条回答
  •  甜味超标
    2021-01-17 12:43

    You can have a empty file which is lying on the server you want to write to.

    When you want to write to the server you can catch the token. Only when you have the token you should write to any file which is lying on the server.

    When you are ready with you file operations or an exception was thrown you have to release the token.

    The helper class can look like

    private FileLock lock;
    
    private File tokenFile;
    
    public SLTokenLock(String serverDirectory) {
        String tokenFilePath = serverDirectory + File.separator + TOKEN_FILE;
        tokenFile = new File(tokenFilePath);
    }
    
    public void catchCommitToken() throws TokenException {
        RandomAccessFile raf;
        try {
            raf = new RandomAccessFile(tokenFile, "rw"); //$NON-NLS-1$
            FileChannel channel = raf.getChannel();
            lock = channel.tryLock();
    
            if (lock == null) {
                throw new TokenException(CANT_CATCH_TOKEN);
            }
        } catch (Exception e) {
            throw new TokenException(CANT_CATCH_TOKEN, e);
        }
    }
    
    public void releaseCommitToken() throws TokenException {
        try {
            if (lock != null && lock.isValid()) {
                lock.release();
            }
        } catch (Exception e) {
            throw new TokenException(CANT_RELEASE_TOKEN, e);
        }
    }
    

    Your operations then should look like

    try {
            token.catchCommitToken();
    
            // WRITE or READ to files inside the directory
        } finally {
            token.releaseCommitToken();
        }
    

提交回复
热议问题