无法使用File delete()方法删除git repo中的.pack文件

对于我写的这个方法,我正在使用jgit库克隆一个git repo,然后用这些文件做一些事情,最后我想删除repo。 我遇到的问题是当我在.pack文件(位于.git \ objects \ pack)上调用delete()方法时,它无法删除。 但是可以删除所有其他文件。 为什么会这样?

您可以看到,基于JGit的Java应用程序在默认情况下会出现ddd崩溃的趋势。
例如,请参阅Gitblit的此配置文件 :

# When true, JGit will use mmap() rather than malloc()+read() to load data from # pack files. The use of mmap can be problematic on some JVMs as the garbage # collector must deduce that a memory mapped segment is no longer in use before # a call to munmap() can be made by the JVM native code. # # In server applications (such as Gitblit) that need to access many pack files, # setting this to true risks artificially running out of virtual address space, # as the garbage collector cannot reclaim unused mapped spaces fast enough. # # Default on JGit is false. Although potentially slower, it yields much more # predictable behavior. # Documentation courtesy of the Gerrit project. # # SINCE 1.0.0 # RESTART REQUIRED git.packedGitMmap = false 

这与您找到的JGit线程一致:

我遇到了另一个无法在Windows中删除克隆存储库的实例。
这个似乎与使用“ PackedGitMMAP ”有关。
这是尝试使用虚拟内存映射的已知问题吗?

是。
问题是JVM在Java GC垃圾收集映射之前不会释放内存映射。
这可能在将来的任何时候发生,如果没有足够的内存压力迫使GC真正寻找垃圾和回收,可能永远不会发生。
这就是我们默认禁用该function的原因,我们无法预测JVM何时最终会释放该文件。

在此测试用例中,如果我“ setPackedGitMMAP=false ”,则成功删除存储库。

是。 这就是默认情况。

刚刚发现了一个干净的方法:用你的repo做一些事情后,用这种方式关闭你的git对象:

 Git git; ... git.getRepository().close(); //then delete files