Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
   * Copyright 2015-2015 Amazon Technologies, Inc.
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at:
  * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
  * OR CONDITIONS OF ANY KIND, either express or implied. See the
  * License for the specific language governing permissions and
  * limitations under the License.
 import java.util.Map;
An internal utility used to provide both inter and intra JVM file locking. This works well as long as this class is loaded with the same class loader in a JVM. Otherwise, intra-JVM file locking is not guaranteed.

Per javadoc of java.nio.channels.FileLock, "File locks are held on behalf of the entire Java virtual machine. They are not suitable for controlling access to a file by multiple threads within the same virtual machine."

Hence the need for this utility class.

 public enum FileLocks {
     // External file lock doesn't seem to work correctly on Windows, 
     // so disabling for now (Ref: TT0047889941)
     private static final boolean EXTERNAL_LOCK = false;
     private static final Log log = LogFactory.getLog(FileLocks.class);
     private static final Map<FileRandomAccessFilelockedFiles = new TreeMap<FileRandomAccessFile>();

Acquires an exclusive lock on the specified file, creating the file as necessary. Caller of this method is responsible to call the unlock( method to prevent release leakage.

true if the locking is successful; false otherwise.
Throws: if we failed to lock the file
     public static boolean lock(File file) {
         synchronized() {
             if (.containsKey(file))
                 return false;   // already locked
         FileLock lock = null;
         RandomAccessFile raf = null;
         try {
             // Note if the file does not already exist then an attempt will be
             // made to create it because of the use of "rw".
             raf = new RandomAccessFile(file"rw");
             FileChannel channel = raf.getChannel();
             if ()
                 lock = channel.lock();
         } catch (Exception e) {
             throw new FileLockException(e);
         final boolean locked;
         synchronized() {
             RandomAccessFile prev = .put(fileraf);
             if (prev == null) {
                 locked = true;
             } else {
                 // race condition: some other thread got locked it before this
                 locked = false;
                 .put(fileprev);    // put it back
         if (locked) {
             if (.isDebugEnabled())
                 .debug("Locked file " + file + " with " + lock);
         } else {
         return locked;

Returns true if the specified file is currently locked; false otherwise.
    public static boolean isFileLocked(File file) {
        synchronized() {
            return .containsKey(file);

Unlocks a file previously locked via lock(

true if the unlock is successful; false otherwise. Successful unlock means we have found and attempted to close the locking file channel, but ignoring the fact that the close operation may have actually failed.
    public static boolean unlock(File file) {
        synchronized() {
            final RandomAccessFile raf = .get(file);
            if (raf == null)
                return false;
            else {
                // Must close out the channel before removing it from the map;
                // or else risk giving a false negative (of no lock but in fact
                // the file is still locked by the file system.)
        if (.isDebugEnabled())
            .debug("Unlocked file " + file);
        return true;
New to GrepCode? Check out our FAQ X