Search code examples
lockingjava-5

Why do we need a java lock for just reading?


W.r.t ReadWriteLock, why would i need a lock while i am just trying to read something? Locking in my knowledge is to be used only if i am mutating a variable, not reading it to avoid concurrent threads trying to mutate the variable. So why we need a Lock for just reading?


Solution

  • The point of a ReaderWriterLock is to make sure that no other thread mutates something while you read it.

    The read portion of the lock is not exclusive (there can be multiple concurrent readers), except with regard to the write portion (readers will wait for the writer and vice-versa).