Hi all,
I'm using the ReentrantReadWriteLock to synchronize my caching. I also read the API of the ReentrantReadWriteLock. So I run the following example code :
and expect the outputs shoud always look like:
t4 get the read lock
t4 get the read lock
t4 release read lock
t4 release read lock
t1 get the write lock
t1 get the read lock
t1 release read lock
t1 release write lock
or
t1 get the write lock
t1 get the read lock
t1 release read lock
t1 release write lock
t4 get the read lock
t4 get the read lock
t4 release read lock
t4 release read lock
However, i was surprised by some of the outputs:
case1 :
t1 get the write lock
t1 get the read lock
t1 release read lock
t4 get the read lock
t4 get the read lock
t4 release read lock
t4 release read lock
t1 release write lock
case2 :
t4 get the read lock
t4 get the read lock
t4 release read lock
t1 get the write lock
t1 get the read lock
t1 release read lock
t1 release write lock
t4 release read lock
From my unstanding about the the ReentrantReadWriteLock: multiple threads can own a read lock simultaneously as long as the write lock isn't owned by any
thread. Only one thread can own a write lock at any given time, and no thread can own a write lock while any thread owns a read lock.
Why the thread is not synchorzed?
The reason I tried to run t1 & t4 is because some of the methods will use the same scenario. Firstly I will cach every contractor information into a Class call ContractorItem, and then save it in the HashMap<Long, ContractorItem>.
In my updateRecord method:
Assuming there are two threads, thread A is is trying to update record 1, and thread B is trying to read the infromation of record 1. According to my above code (the output result of t1 & t4), the thread B may read the information of record 1 after the thread A pass the getContractor method but not release the write lock. It may return the wrong result because the record 1 has been updated yet.
My question is : how can I avoid this situation? am I used the ReentrantReadWriteLock correctly?
Last but not least, this is not important, but i just want to know:
I tried to run the Thread t2, and it will cause dead lock. Why?
Thank you in advance.