1 package cz.cuni.amis.utils.maps;
2
3 import java.util.HashMap;
4 import java.util.Map;
5 import java.util.concurrent.locks.Lock;
6 import java.util.concurrent.locks.ReadWriteLock;
7 import java.util.concurrent.locks.ReentrantReadWriteLock;
8
9
10
11
12
13
14
15
16
17
18 public class SyncHashMap<K, V> {
19
20 private Map<K, V> map = new HashMap<K, V>();
21
22 private ReadWriteLock rwLock = new ReentrantReadWriteLock(false);
23
24 private Lock readLock = rwLock.readLock();
25
26 private Lock writeLock = rwLock.writeLock();
27
28 public V put(K key, V value) {
29 writeLock.lock();
30 try {
31 return map.put(key, value);
32 } finally {
33 writeLock.unlock();
34 }
35 }
36
37 public V remove(K key) {
38 writeLock.lock();
39 try {
40 return map.remove(key);
41 } finally {
42 writeLock.unlock();
43 }
44 }
45
46 public V get(Object key) {
47 readLock.lock();
48 try {
49 return map.get(key);
50 } finally {
51 readLock.unlock();
52 }
53 }
54
55 public int size() {
56 return map.size();
57 }
58
59
60
61
62
63 public Map<K, V> getMap() {
64 return map;
65 }
66
67
68
69
70
71 public Lock getReadLock() {
72 return readLock;
73 }
74
75
76
77
78
79 public Lock getWriteLock() {
80 return writeLock;
81 }
82
83 }