Nekr Blog

try {
        File file = new File("filename");
        FileChannel channel = new RandomAccessFile(file, "rw").getChannel();

        FileLock lock = channel.lock();
        try {
            lock = channel.tryLock();
        } catch (OverlappingFileLockException e) {
            // File is already locked in this thread or virtual machine
        }

        lock.release();
        channel.close();
}catch(Exception e){
}