Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Can File.exists and File.delete have a race condition?

 
Satya Maheshwari
Ranch Hand
Posts: 368
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

Can File.exists and File.delete have a race condition?

Let's say thread-1 deletes a file and thread-2 checks for the existence of the same file. Now do I need to ensure that this does not happen simultaneously or does Java/OS take care of this by itself.

Regards
 
meghala devi
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Sathya

Can synchronizing the block of code help?

This ensures that only one thread accesses the file at a time
 
Rob Spoor
Sheriff
Pie
Posts: 20511
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It depends on the file system, but assume there is no synchronization. If one thread or process* deleted the file mere nanoseconds after File.exists() has returned true the file no longer exists even though your program thinks it does. This isn't something you can do much about I fear.


* After all, the file can also be deleted from Explorer, or another program.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic