Java FileLock pauseForLock(File f, int frequency, int totalTime)

Here you can find the source of pauseForLock(File f, int frequency, int totalTime)

Description

Waits for a file lock for a given time, with a given frequency.

License

Open Source License

Parameter

Parameter Description
f a parameter
time a parameter
totalTime a parameter

Declaration

public static void pauseForLock(File f, int frequency, int totalTime) throws Exception 

Method Source Code

//package com.java2s;
/*//from  w w  w  . j  a v a  2 s . com
 * Copyright (c) 2012 Diamond Light Source Ltd.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 */

import java.io.File;

import java.io.FileOutputStream;

import java.nio.channels.FileLock;

public class Main {
    /**
     * Waits for a file lock for a given time, with a given frequency.
     * Does nothing if cannot lock after totalTime - to avoid deadlocks
     * @param f
     * @param time
     * @param totalTime
     */
    public static void pauseForLock(File f, int frequency, int totalTime) throws Exception {

        // If file locked, wait for up to 2s
        int waited = 0;
        final FileOutputStream out = new FileOutputStream(f);
        try {
            FileLock lock = out.getChannel().tryLock();
            try {
                while (lock == null) {
                    Thread.sleep(frequency);
                    waited += frequency;
                    if (waited >= totalTime)
                        break;
                }
            } finally {
                if (lock != null)
                    lock.release();
            }
        } finally {
            out.close();
        }
    }
}

Related

  1. lock(File file)
  2. lockFile(File file)
  3. lockFile(File file, RandomAccessFile raf)
  4. lockFileExists(File file)
  5. openTcpSocket(boolean blocking)
  6. releaseQuietly(FileLock lock)
  7. releaseQuietly(final FileLock lock)
  8. releaseSilent(FileLock fileLock)
  9. setNonBlockingFD(Channel c, boolean blocking)