File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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
Author

RandomAccessFile.length() is NOT thread safe

Christian Kindler
Greenhorn

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
    
    2

Thanks Christian for information


Fernando Franzini - Java Blog
 
GeeCON Prague 2014
 
subject: RandomAccessFile.length() is NOT thread safe