Wednesday 18 December 2019

Custom ConcurrentHashMap Implementation in java

package kp;

import java.util.HashMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;

public class MyConcurrentHashMap<K, V> extends HashMap<K, V> {

private static final long serialVersionUID = 1L;

private ReentrantReadWriteLock[] lock = new ReentrantReadWriteLock[16];

public MyConcurrentHashMap() {
super();

for (int i = 0; i < 16; i++) {
lock[i] = new ReentrantReadWriteLock();
}

}

@Override
public V get(Object key) {

ReentrantReadWriteLock lock = getLock(key);
WriteLock wl = lock.writeLock();

if (lock.isWriteLocked()) {
try {
wl.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

lock.readLock().lock();
V value = super.get(key);
lock.readLock().unlock();
return value;
}

@Override
public V put(K key, V value) {

ReentrantReadWriteLock lock = getLock(key);
while (lock.getReadLockCount() > 0) {
try {
lock.readLock().wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
lock.writeLock().lock();
V val = super.put(key, value);
lock.writeLock().unlock();
return val;
}

private ReentrantReadWriteLock getLock(Object key) {
int hash = hashCode(key);
return lock[hash / 100];
}

private int hashCode(Object key) {

return (key == null ? 0 : key.hashCode() % 1600);
}

}

------------------------------------------------------------------------------------------------------------------

package kp;

public class MyConcurrentHashMapTestDrive {

public static void main(String[] args) {

MyConcurrentHashMap<Integer, String> myConcurrentHashMap = new MyConcurrentHashMap<Integer, String>();
WriteMap w1 = new WriteMap(myConcurrentHashMap);
WriteMap w2 = new WriteMap(myConcurrentHashMap);
ReadMap r1 = new ReadMap(myConcurrentHashMap);
w1.setName("First Thread");
w2.setName("Second Thread");
w1.start();
w2.start();
r1.start();

}

}

class WriteMap extends Thread {
MyConcurrentHashMap<Integer, String> cMap;
public WriteMap(MyConcurrentHashMap<Integer, String> cMap){
this.cMap = cMap;
}
public void run(){
int i=1;
while(true){
cMap.put(i, this.currentThread().getName());
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

class ReadMap extends Thread {
MyConcurrentHashMap<Integer, String> cMap;
public ReadMap(MyConcurrentHashMap<Integer, String> cMap){
this.cMap = cMap;
}
public void run(){
int i=1;
while(true){
System.out.println(cMap.get(i));
}
}
}





No comments:

Post a Comment