Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
267 views
in Technique[技术] by (71.8m points)

java - ReentrantReadWriteLock: what's the difference between ReadLock and WriteLock?

What I know is:

  • ReadLock and WriteLock affect each other somehow
  • WriteLock is just like synchronized
  • ReadLock seems cannot work alone
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.
  • Once the lock is granted no other thread will be allowed to write (i.e. take a write lock) until the lock is released.

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.
  • Once the lock is granted, no other thread will be allowed to read or write (i.e. take a read or write lock) until the lock is released.

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, take a write lock. This way 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...