File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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 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:
Fernando Franzini
Ranch Hand

Joined: Jan 09, 2009
Posts: 489

Thanks Christian for information

Fernando Franzini - Java Blog
I agree. Here's the link:
subject: RandomAccessFile.length() is NOT thread safe
jQuery in Action, 3rd edition