This week's book giveaway is in the OCAJP forum.
We're giving away four copies of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) and have Khalid A Mughal & Rolf W Rasmussen on-line!
See this thread for details.
Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

RandomAccessFile.length() is NOT thread safe

 
Christian Kindler
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 489
2
Java Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Christian for information
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic