Java FileLock tryLock(File file)

Here you can find the source of tryLock(File file)

Description

try Lock

License

Apache License

Declaration

public static FileLock tryLock(File file) 

Method Source Code


//package com.java2s;
/*/*from ww  w  .  j a v a2s .c  o m*/
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License 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.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import java.io.RandomAccessFile;
import java.lang.management.ManagementFactory;

import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;

public class Main {
    public static FileLock tryLock(File file) {
        FileLock toReturn = null;

        try {
            RandomAccessFile raf = new RandomAccessFile(file, "rw");

            try {
                FileChannel channel = raf.getChannel();
                toReturn = channel.tryLock();
                raf.writeBytes("lock file for: " + ManagementFactory.getRuntimeMXBean().getName());
            } finally {
                if (toReturn == null)
                    raf.close();
            }
        } catch (OverlappingFileLockException e) {
            toReturn = null;
        } catch (FileNotFoundException e) {
            toReturn = null;
        } catch (IOException e) {
            toReturn = null;
        }

        return toReturn;
    }
}

Related

  1. pauseForLock(File f, int frequency, int totalTime)
  2. releaseQuietly(FileLock lock)
  3. releaseQuietly(final FileLock lock)
  4. releaseSilent(FileLock fileLock)
  5. setNonBlockingFD(Channel c, boolean blocking)
  6. trylock(File file, boolean shared)
  7. tryLock(File location)
  8. unblockSocket(SelectableChannel... channels)
  9. unlock(File file)