JAVA File Lock

package fileLock;

import java.io.File;
import java.io.RandomAccessFile;
import java.util.Collection;
import java.util.Iterator;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

/**
 * @ClassName: FileLock
 * @Description: TODO
 * @author Zhou Shengshuai
 * @date 2014年9月22日 下午2:03:04
 * 
 */
public class FileLock {
	private ExecutorService threadPool = null;
	private Collection<File> files = null;

	public void initial() {
		threadPool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

		files = FileUtils.listFiles(new File("lock"), new String[] { "lck", "LCK" }, false);
	}

	public void execute() {
		Iterator<File> iterator = files.iterator();
		while (iterator.hasNext()) {
			File file = iterator.next();

			ThreadTask threadTask = new ThreadTask(file);
			threadPool.submit(threadTask);
		}
	}

	public void destroy() {
		threadPool.shutdown();

		while (!threadPool.isTerminated())
			;
	}

	public static void main(String[] args) {
		FileLock fileLock = new FileLock();

		fileLock.initial();
		fileLock.execute();
		fileLock.destroy();
	}
}

class ThreadTask implements Callable<File> {
	private File file = null;

	public ThreadTask(File file) {
		this.file = file;
	}

	@Override
	public File call() throws Exception {
		if (file == null || !file.isFile()) {
			throw new Exception("File is null or non-file");
		}

		RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rws");
		java.nio.channels.FileLock fileLock = null;

		while (true) {
			fileLock = randomAccessFile.getChannel().tryLock();

			if (fileLock != null) {
				break;
			}
		}

		randomAccessFile.writeBytes("123\n");

		if (fileLock != null) {
			fileLock.release();
		}

		IOUtils.closeQuietly(randomAccessFile);

		return file;
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值