My main question is "Do I really need recheck the value in the following code"?
The following code describes how to implement a cache by using ReadWriteLock.
public class ReadWriteLockCache {
private Map<String, Object> cache = new HashMap<String, Object>();
private ReadWriteLock rwl = new ReentrantReadWriteLock();
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public Object getData(String key) {
rwl.readLock().lock();
Object value = null;
try {
value = cache.get(key);
if (value == null) {
rwl.readLock().unlock(); //line1
rwl.writeLock().lock(); //line2
try {
if (value == null) //line3
{
value = "aaaa"; // may get data from db
//line5 put the data into cache.
cache.put(key, value);
}
} finally {
rwl.writeLock().unlock();
}
rwl.readLock().lock();
}
} finally {
rwl.readLock().unlock();
}
return value;
}
}
Whether Should I still need to recheck the value at the 'line3' ?
As I know, the value object is must be null when excuted to line3,
because it's a local variable (when it's null)and it's cann't be A state variable of our main obj:ReadWriteLockCache.
What we should really do is recall the get method ,and check the key's value is whether putted by some other thread or not.
The code should like this:
value = cache.get(key);
if (value == null) //line3
{
value = "aaaa";
cache.put(key, value);
}
Anyone can help?Am I right? I'm confused.