FileHandle: don't unnecessarily init a RandomAccessFile on close#307
FileHandle: don't unnecessarily init a RandomAccessFile on close#307
Conversation
If we close a handle on a file that does not exist, we do not need to initialize the RandomAccessFile, just to close it again. This fixes the problem of empty files appearing when closing a FileHandle to a file that does not exist.
There was a problem hiding this comment.
Unfortunately, this simple fix can result in a race condition if close() is called near-simultaneously with another thread that causes the RandomAccessFile to be initialized.
Suppose Thread1 calls fileHandle.writeShort(555); and Thread2 then calls fileHandle.close() while Thread1's operation is in the middle of the new RandomAccessFile call. The raf reference has not yet been assigned, so Thread2's close operation will do nothing.
Maybe this doesn't matter, because RandomAccessFile is not thread-safe anyway. So fileHandle really should not be shared between Thread1 and Thread2.
If we do care for some reason, the only easy fix I can see is to add a new method like getRAF() which is synchronized, and returns raf. This would minimize the chances of (but not fully prevent!) close() doing nothing while another thread is in the midst of the initRAF() operation.
What do you think?
|
I don't think a single handle should be shared between threads at all, as this can very easily result in data corruption unless the threads are coordinating their access somehow. |
1f4575a to
fdfc4ef
Compare
|
@gab1one Let's just make the |
This change does two things: * It synchronizes close(), so that the RAF cannot be in the process of initializing while the close() operation is happening. * It guards all operations against an already-closed state, such that an IOException will be thrown if the handle has already been closed.
fdfc4ef to
5f4b56a
Compare
If we close a handle on a file that does not exist, we do not need to
initialize the RandomAccessFile, just to close it again. This fixes the problem of
empty files appearing when closing a FileHandle to a file that does not exist.