|
| |
The ReadWriteLock interface defines the
following methods:
| Method |
Description |
Lock readLock()
|
Returns the lock used for reading. |
Lock writeLock()
|
Returns the lock used for writing. |
Java provides an implementation of ReadWriteLock,
java.util.concurrent.locks.ReentrantReadWriteLock,
whose API javadocs you can find here.
Here's an example of how you might use this feature:
package threads;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* A Dictionary class that uses a ReentrantReadWriteLock to provide
* convenient and controlled reader and writer synchronized access.
*
* (Follows the example in the ReentrantReadWriteLock class javadocs.)
*
*/
public class ReadWriteDictionary
{
public Data get(String key)
{
readLock.lock();
try
{
return theMap.get(key);
}
finally
{
readLock.unlock();
}
}
public String[] allKeys()
{
readLock.lock();
try
{
return (String[]) theMap.keySet().toArray();
}
finally
{
readLock.unlock();
}
}
public Data put(String key, Data value)
{
writeLock.lock();
try
{
return theMap.put(key, value);
}
finally
{
writeLock.unlock();
}
}
public void clear()
{
writeLock.lock();
try
{
theMap.clear();
}
finally
{
writeLock.unlock();
}
}
////// Private data /////
private final Map<String, Data> theMap = new TreeMap<String, Data>();
private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
private final Lock readLock = rwl.readLock();
private final Lock writeLock = rwl.writeLock();
}
|
package threads;
/**
* Dummy Data class for ReadWriteDictionary.
*/
public class Data
{
/**
* Creates a new instance of Data
*/
public Data()
{
}
// ...
}
|
Note how the methods that read data from the dictionary are protected
by the read lock, while methods that implement changes to the dictionary are
protected by the write lock. The ReentrantReadWriteLock
class provides the necessary coordination.
|