Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Atomic operations with ReentrantReadWriteLock

 
Alexandr Murga
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ReentrantReadWriteLock API says that �in many cases any number of threads can concurrently read the data�, but what about atomic operations?

If many threads at the same time what to perform some sequence of operations like:
- change the position of filePointer
- read bytes

Is it possible to happen that threads A and B both have readLock on the same File and:
1)Thread A change file pointer position
2)Thread B change file pointer position
3)Thread A reads wrong data
4)Thread B reads wrong data

May be ReadWriteLock is designed only to concurrently read data in one operation like retrieving a key from HashMap and for sequence of operations described above we just need to use ReentrantLock.
 
Henry Wong
author
Marshal
Pie
Posts: 22113
88
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The purpose of the reader writer lock (specifically the reader lock) is to allow threads that don't change the state of something, and hence, can work in parallel, to be allowed to work in parallel.

As you have already figured out, just because you are not writing to the disk doesn't mean that you are not changing the state -- of the file object. The file pointer can change. And since reading or wrting from a file, or actually, any stream, changes the state, you can't use the reader writer lock to obtain extra parallelism.

Henry
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic