Created
May 3, 2020 04:36
-
-
Save vissapra/e8085da8fa49c56198e2d1a7b5a71faf to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.HashMap; | |
import java.util.concurrent.locks.Lock; | |
import java.util.concurrent.locks.ReadWriteLock; | |
import java.util.concurrent.locks.ReentrantReadWriteLock; | |
public class ConcurrentMap<K,V> extends HashMap<K,V> { | |
private final Lock readLock; | |
private final Lock writeLock; | |
public ConcurrentMap() { | |
ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); | |
readLock = readWriteLock.readLock(); | |
writeLock = readWriteLock.writeLock(); | |
} | |
public V get(Object key) { | |
try { | |
readLock.lock(); | |
return super.get(key); | |
} finally { | |
readLock.unlock(); | |
} | |
} | |
public V put(K key, V value) { | |
try { | |
writeLock.lock(); | |
return super.put(key, value); | |
}finally { | |
writeLock.unlock(); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.HashMap; | |
import java.util.Map; | |
import java.util.concurrent.locks.Lock; | |
import java.util.concurrent.locks.ReadWriteLock; | |
import java.util.concurrent.locks.ReentrantReadWriteLock; | |
public class SingletonThreadsafeMap { | |
private Map<String, String> map = new HashMap<String, String>(); | |
private ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); | |
private static TestMap INSTANCE = new TestMap(); | |
private Lock readLock = readWriteLock.readLock();; | |
private Lock writeLock = readWriteLock.writeLock(); | |
public static TestMap getInstance() { | |
return INSTANCE; | |
} | |
public String get(String key) { | |
try { | |
readLock.lock(); | |
return map.get(key); | |
} finally { | |
readLock.unlock(); | |
} | |
} | |
public String put(String key, String value) { | |
try { | |
writeLock.lock(); | |
return map.put(key, value); | |
}finally { | |
writeLock.unlock(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment