Concurrent Hash Table Assignment
Contents
Motivation
For this exercise you will create a thread safe data structure. You have previously created a non-thread safe Map. Now, with the help of multiple ReentrantReadWriteLocks you will create a thread safe Map that both deals with contention and allows simultaneous gets.
class: | ConcurrentBucketHashMap.java | |
methods: | constructor getIndex getBucket getLock getEntry get put compute |
|
package: | kmer.lab.concurrentbuckethashmap | |
source folder: | student/src/main/java |
Code To Implement
ConcurrentHashTable
constructor
method: public ConcurrentBucketHashMap(int bucketCount)
(sequential implementation only)
bucketCount can be treated as a hint of how many entries the Map can expect to receive.
private support methods
Tip:Use HashUtils.toIndex(key,N) |
getBucket(key)
method: private List<Entry<K, V>> getBucket(Object key)
(sequential implementation only)
getLock(key)
method: private ReadWriteLock getLock(Object key)
(sequential implementation only)
getEntry(bucket, key)
method: private static <K, V> Optional<Entry<K, V>> getEntry(List<Entry<K, V>> bucket, Object key)
(sequential implementation only)
Refer to Optional<T> Class documentation.
public methods
Be sure to make each of these methods thread safe by acquiring the appropriate (read or write) lock for the appropriate bucket.
Which method, lock() or tryLock(), is the appropriate one to use for creating a thread safe data structure such as this?
Whenever you acquire a lock, but sure to leverage try finally and unlock() the lock within the finally block.
method: public V get(Object key)
(thread-safe required)
method: public V put(K key, V value)
(thread-safe required)
method: public V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction)
(thread-safe required)
advice
Warning: Do NOT call get() from compute(). It will result in a nonintuitive error. getEntry(bucket, key) gives you everything you need. |
Warning: Do NOT call put() from compute() either. Just do the work within the compute method. |
Tip: Be sure to make your ConcurrentBucketHashMap thread-safe. If any code is going to access shared mutable data, it needs to do so in a thread-safe manner. |