1

I have a static utility class, FileUtils which has the following method:

public static Object readDataFromInternalStorage(String fileName) 
{...}

public static synchronized void 
          writeDataToInternalStorage(Serializable theData, String fileName) 
{...}

I am encountering the odd java.io.EOFException in my read method when trying to read from internal storage. This is a multi-threaded app where multiple threads can access this code at the same time (though this is not a common case). After thinking about this for a bit, my suspicion is that while reading the file, another thread comes along and writes to the file before the read is finished, thereby mangling the read. Is my assumption correct?

Assuming it is, what is the best way to fix this? Is the answer simply to add 'synchonized' to my read method, which if I read this post correctly locks on the entire class?

Community
  • 1
  • 1
Chris Knight
  • 24,333
  • 24
  • 88
  • 134

3 Answers3

2

Your assumption is probably correct; a concurrent write while you are reading can cause all sorts of problems.

One option is to synchronize the read but, as you say, that will allow only one reader or writer at a time. Another option is to use a ReentrantReadWriteLock to control both reading and writing. This is harder to use but is much more flexible, allowing for multiple, simultaneous readers and exclusive writers.

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
  • thanks very much. Its pretty unsual that my code would have two threads read or write at the same time so I think I'll stick with the easier solution of synchronizing the read, but thanks for the ReentrantReadWriteLock. Looks very interesting, will keep in mind for the future – Chris Knight Jan 30 '12 at 22:03
1

Assuming that you close the file handles before the end of the respective methods, adding synchronized to your read method should make sure that only one thread at a time is reading or writing. Of course, you should also make sure that no other methods in your application are reading or writing to the same file.

The Nail
  • 8,355
  • 2
  • 35
  • 48
1

Cant say for sure but it is definitely possible that you are seeing corruption in the read based on a concurrent write to the same file. In general, you do need to synchronize such access to a single file by multiple threads. And yes, synchronizing the read method would do that for you. There are other potential solutions but until you find a need to go down a more complex path, this may be your best bet.

philwb
  • 3,805
  • 19
  • 20