1

我想保护我的代码同时在一个目录中做同样的事情,为此我需要一种跨进程互斥锁。由于有问题的目录最终可能会在网络上共享,我想打开一个文件作为这种锁进行写入。

public static void main(String[] args) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    try {
        FileOutputStream fos = new FileOutputStream("lockfile", false);
        try {
            System.out.println("Lock obtained. Enter to exit");
            br.readLine();
            System.out.println("Done");
        }
        finally {
            fos.close();
        }
    } catch (FileNotFoundException ex) {
        System.out.println("No luck - file locked.");
    }
}

运行java -jar dist\LockFileTest.jar两次成功!– 我看到两个控制台提示输入。

我也试过new RandomAccessFile("lockfile", "rw")了,效果一样。

背景:windows xp,32bit,jre1.5。

我的错误在哪里?这怎么可能?

4

2 回答 2

2

你试过文件锁吗?

RandomAccessFile randomAccessFile = new RandomAccessFile("lockfile", "rw");
FileChannel channel = randomAccessFile.getChannel();
FileLock lock = channel.lock();

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
    OutputStream fos = Channels.newOutputStream(channel);
    try {
        System.out.println("Lock obtained. Enter to exit");
        br.readLine();
        System.out.println("Done");
    } finally {
        fos.close();
    }
} catch (FileNotFoundException ex) {
}
于 2013-10-25T13:22:44.047 回答
1

以这种方式使用 FileOutputStream 和/或 RandomAccessFile 不会让您锁定文件..

相反,您应该使用 RandomAccessFile 并获取 FileChannel 然后对文件发出锁定..

以下是您修改的示例:

public static void main(String[] args)throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        try {
            RandomAccessFile raf = new RandomAccessFile(new File("d:/lockfile"), "rw");

            System.out.println("Requesting File Lock");
            FileChannel fileChannel = raf.getChannel();
            fileChannel.lock();
            try {
                System.out.println("Lock obtained. Enter to exit");
                br.readLine();
                System.out.println("Done");
            } finally {
                fileChannel.close();
            }
        } catch (FileNotFoundException ex) {
            System.out.println("No luck - file locked.");
        }
    }
于 2013-10-25T13:37:58.823 回答