Here you can find the source of lock(File file)
public static FileOutputStream lock(File file)
//package com.java2s; /**/* w ww.ja v a 2 s.c o m*/ * Copyright (C) 2008 http://code.google.com/p/maven-license-plugin/ * * 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 * * 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.*; import java.nio.channels.FileLock; import java.util.HashMap; import java.util.Map; public class Main { private static final Map<File, FileLock> locks = new HashMap<File, FileLock>(); public static FileOutputStream lock(File file) { try { FileOutputStream out = new FileOutputStream(file); FileLock lock = out.getChannel().tryLock(); if (lock == null) { throw new IllegalStateException("Cannot acquire a lock on file " + file + ". Please verify that this file is not used by another process."); } locks.put(file, lock); return out; } catch (IOException e) { throw new IllegalStateException("An I/O error occured when trying to get a lock on file " + file + ". Please verify that this file is not used by another process. Cause: " + e.getMessage(), e); } } }