This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
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


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
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
 
It is sorta covered in the JavaRanch Style Guide.
 
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