This week's book giveaway is in the OCAJP 8 forum.
We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori 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 OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 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

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: 488

Thanks Christian for information

Fernando Franzini - Java Blog
I agree. Here's the link:
subject: RandomAccessFile.length() is NOT thread safe
It's not a secret anymore!