Hi, I've written a program that spawns several threads. Each thread handles its own set of files. Here is what each thread does: 1. Create result.out.tmp 2. Renames result.out.tmp to result.out 3. Repeasts #1 (loop indevinitely) Here is the code snippet:
I'm running this in FreeBSD. How come most of the times, renameTo() works (returns true), and sometime it fails (returns false). If ever it returns false, is there a way to find out what is tha cause? I'm pretty sure it's not security error, because I have enclosed the code in try-catch, and no security exception was thrown. Besides, only one thread accesses the file. Thanks.
Well, it could fail if a file by that name already exists. Your description makes it sound as if all the threads are using these fixed filenames; are they all working in the same directory? Are they occasionally working in the same directory?
I really hate certain File methods like renameTo(), delete(), mkdir(), and setReadOnly(), because returning "false" is a poor way to fail, providing no useful information why it failed. Plus many programmers forget to check the return value, not even realizing it failed. (And thank you, David, for remembering to check.) Aside from Ernest's advice (which covers what may be the most likely case), another possible source of your problem is that you may not have closed the stream / channel / RandomAccessFile which created result.out.tmp before trying to move() it. In many cases this may seem unnecessary, if the stream was referenced only by a local variable somewhere - when the method ends, the variable goes out of scope, the object becomes eligible for GC, and the stream will eventually be closed, without you ever explicitly closing it. The problem is if you try to do something else with the file that was created, before the stream has been closed. The operating system may not allow you to delete or rename a file while it's still held open by an unclosed FileOutputStream. And you can't control how quickly GC will occur, so you can get unpredictable behavior, depending on when GC takes effect. So to be safe - make sure that whenever you're done writing to a file, close() the associated filestream, immediately. And use a finally block to unsure this happens even if an exception occurred during the writing. Hope that helps...