Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we need a java lock for just reading?

Tags:

locking

java-5

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?

like image 449
Victor Avatar asked Mar 13 '26 16:03

Victor


1 Answers

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).

like image 129
SLaks Avatar answered Mar 16 '26 16:03

SLaks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!