0

I am writing file and closing stream after writing. In finally I am deleting file. But I am still able to find file after program execution is complete. Its Multi threaded environment.

So is it possible to check it is being used by which function or which thread?

Updated with code :

 File p_file = new File("C:\\", "GUID");
 p_file.createNewFile();

 FileOutputStream fos = null;
try {
  fos = new FileOutputStream(p_file);
  fos.write("This is test msg.".getBytes());
} finally {
  try {
         fos.close();
      } catch (IOException e) {
                e.printStackTrace();
      }
      if(p_file.exists())
   System.out.println(p_file.delete());
}
}

Thanks

rot
  • 129
  • 11

2 Answers2

1

In a Linux/Unix environment lsof is your friend. For Windows Process Explorer can help you finding the process that holds a handle to the file.

Anders R. Bystrup
  • 15,729
  • 10
  • 59
  • 55
  • In windows it is easy to check which process use file using utility: http://en.wikipedia.org/wiki/Unlocker – Taky Oct 09 '12 at 10:44
0

If I understand it right this peace of code is executed concurrently by many threads. In this case many threads may create, open, delete the same file concurrently, i.e. one thread is currently writing to the file and a second thread tries to remove the file. Then it may happen, that the operation to remove the file fails.

To prevent concurrent access to the same file, you can synchronize your code (see synchronize keyword) or you can generate a separate unique filename, e.g. see answers to this question.

Community
  • 1
  • 1
mmehl
  • 234
  • 1
  • 6