Java File.delete() hangs or taking too long

Solution for Java File.delete() hangs or taking too long
is Given Below:

I’m simply deleting a file based on a filter

public void delete(String folder, String filter){
   File f = new File(path);
   String[] files = f.list();
   for (string s : files){
      if (s.indexOf(filter) >= 0){
          new File(folder + s).delete(); 

This usually goes well in a few microseconds.

On occasion though, I have users report this section hangs. If the app becomes unresponsive for too long, I kill it and grab the stacktrace, and this is where the thread is at:


This also happens when writing to a file sometimes. I’m wondering if it can the file being locked by the JVM. Any way of checking for this?

Something in the OS probably has the file open. Anyone has seen the issue in Windows when a file is open in their IDE or something and they are trying to delete a directory.

Java NIO has some features which may help, FileChannel, FileLock. It’s not great.

For example, you could kill it for running long, then check to see if you can get an exclusive lock

File file = new File(fileName);
FileChannel channel = new RandomAccessFile(file, "rw").getChannel();

FileLock lock = channel.lock();
if(lock.isValid() && !lock.isShared()){
  // lock is exclusive, you should be able to delete if you have permissions
} else {
  // cannot get lock