wood burning stoves 2.0*
The moose likes Developer Certification (SCJD/OCMJD) and the fly likes RandomAccessFile.length() is NOT thread safe Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Developer Certification (SCJD/OCMJD)
Bookmark "RandomAccessFile.length() is NOT thread safe" Watch "RandomAccessFile.length() is NOT thread safe" New topic

RandomAccessFile.length() is NOT thread safe

Christian Kindler

Joined: Apr 16, 2009
Posts: 18
If you allow multiple threads to access our data class simultaneously (for read operations, using ReadWriteLock), there is one important thing to know: RandomAccessFile.length() is NOT thread safe. So if you use RandomAccessFile.length() (e.g. to make sure not to read beyond EOF), use it within a synchronized block with the RandomAccessFile object as mutex (like you would do with calls to seek/read methods).

I made some tests with multiple threads and had java.io.EOFExceptions thrown from RandomAccessFile's read methods and it took me a while to find out that unsynchronized calls to RandomAccessFile.length() was the reason.

See also: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4823133
Fernando Franzini
Ranch Hand

Joined: Jan 09, 2009
Posts: 486

Thanks Christian for information

Fernando Franzini - Java Blog
I agree. Here's the link: http://aspose.com/file-tools
subject: RandomAccessFile.length() is NOT thread safe
Similar Threads
parse()-Method of NumberFormat-Object throws Exception
RandomAccessFile.length() is not thread save!
SCJP Brainteaser (9)
Autoboxing, compound assignment operator or
Java 5 final is final no more