FileChannel& RandomAccessFile似乎不工作 [英] FileChannel & RandomAccessFile don't seem to work

查看:312
本文介绍了FileChannel& RandomAccessFile似乎不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简单来说:一个使用sqlitejdbc作为后端的swing应用程序。目前,启动使用同一个数据库文件的多个实例是没有问题的。应该有的。
文件被锁定(不能删除它,而应用程序正在运行),所以检查应该是微不足道的。结果不是。

 文件f =新建文件(/ path / to / file / db.sqlite); 
FileChannel channel = new RandomAccessFile(f,rw)。getChannel();
System.out.println(channel.isOpen());
System.out.println(channel.tryLock());

结果

  true 
sun.nio.ch.FileLockImpl [0:9223372036854775807独占有效]



无论应用程序是否正在运行。我错过了点吗?
TIA

解决方案

FileLocks是JVM专有的,而不是单独的线程。因此,如果您在Swing应用程序的同一进程中运行该代码,则会获得锁定,因为它由JVM共享。



如果您的Swing应用程序未运行,则没有其他进程正在争夺锁定,因此您将获得该应用程序。


To put it simple: a swing app that uses sqlitejdbc as backend. Currently, there's no problem launching multiple instances that work with the same database file. And there should be. The file is locked (can't delete it while the app is running) so the check should be trivial. Turns out not.

    File f = new File("/path/to/file/db.sqlite");
    FileChannel channel = new RandomAccessFile(f, "rw").getChannel();
    System.out.println(channel.isOpen());
    System.out.println(channel.tryLock());

results in

    true
    sun.nio.ch.FileLockImpl[0:9223372036854775807 exclusive valid]

No matter whether the app is running or not. Am I missing the point? TIA.

解决方案

FileLocks are exclusive to the JVM, not an individual thread. So if you ran that code inside the same process as your Swing app, you would get the lock because it is shared by the JVM.

If your Swing app is not running, no other process is contending for the lock so you will obtain it there is well.

这篇关于FileChannel& RandomAccessFile似乎不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆