郭同jet 郭同jet - 4 months ago 11
Java Question

ReentrantReadWriteLock,what's the difference between ReadLock and WriteLock

What I know is , writelock is just like synchronized .

Readlock and writelock affect each other somehow .

ReadLock seems cann't work alone.

Answer
readLock.lock();

This means that if any other thread is writing (i.e. holds a write lock) then stop here until no other thread is writing.

writeLock.lock();

This means that if any other thread is reading or writing, stop here and wait until no other thread is reading or writing.

Combining these you can arrange for only one thread at a time to have write access but as many readers as you like can read at the same time except when a thread is writing.

Put another way. Every time you want to read from the structure, take a read lock. Every time you want to write you take a write lock. Whenever a write happens no-one is reading (you can imagine you have exclusive access), but there can be many readers reading at the same time so long as no-one is writing.

Comments