【问题标题】:ObjectInputStream throws ioexception inside the filelock lock sectionObjectInputStream 在文件锁锁定部分内抛出 ioexception
【发布时间】:2018-12-09 19:56:19
【问题描述】:

我有一个函数,它必须将键值对放入存储在文件中的映射中。如果文件不存在,我必须创建它。当我使用 Filelock lock() 处理文件时,我尝试锁定文件。但是当我尝试写入它时(在锁定部分的内部),我得到 IO 异常: 抑制:java.io.IOException:该进程无法访问该文件,因为另一个进程已锁定文件的一部分 我可能不会正确使用 lock() 。这是我的功能:

        private void createDataSet(String key, String data) throws IOException, ClassNotFoundException{

                final   String path = (fileName);
    //            1. Check if file exists
    //            2. If file exists, write/override key/value.
                Path nPath = Paths.get(path);
                HashMap<String, List<String>> map = new HashMap<String, List<String>>();
    //            createFile is atomic, no need to check if exists.
                    try(FileChannel fileChannel = FileChannel.open(nPath,StandardOpenOption.WRITE,StandardOpenOption.APPEND
                            , StandardOpenOption.CREATE);
                        FileOutputStream fos= new FileOutputStream(path, false);
                        ObjectOutputStream oos= new ObjectOutputStream(fos);

                        ){
                        FileLock lock = fileChannel.lock();
                        if(fileChannel.size()==4){
                            map.put(key, values);
                            oos.writeObject(map);
                        }else{
                            ObjectInputStream objectIn = new ObjectInputStream(Channels.newInputStream(fileChannel));
                            Object obj = objectIn.readObject();
                            map = (HashMap<String, List<String>>) obj;
                            map.put(key, values);
// In this row exception being throwed:
                            oos.writeObject(map); 
                        }
                        oos.close();
                        fos.close();
                        lock.release();
                    }
                    return;

【问题讨论】:

  • 很高兴听到有关创建文件/使用锁定打开现有文件的任何其他解决方案,以使写入操作线程安全。
  • 抛出什么IOException?

标签: java multithreading nio filechannel filelock


【解决方案1】:

您打开文件两次 - 一次通过FileChannel,另一次通过FileOutputStream。然后通过FileChannel 锁定文件,但尝试通过FileOutputStream 写入文件。这就是为什么流被通道锁阻塞的原因。

FileChannel 有自己的读/写方法。使用频道或流,但不能同时使用。

[编辑]文件锁定是为了防止另一个进程写入它,所以除非你知道有其他进程可能会尝试写入你的文件,否则通常不需要在写入之前显式锁定文件它。

【讨论】:

  • 感谢您的回复,会尽快更新!关于锁:我使用它,因为文件可能被其他线程(同一程序的)打开。如果我理解正确,这是比在文件路径上同步更好的解决方案。
猜你喜欢
  • 1970-01-01
  • 2011-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-29
  • 2015-07-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多