-
Notifications
You must be signed in to change notification settings - Fork 104
Expand file tree
/
Copy pathInMemoryStorage.java
More file actions
54 lines (47 loc) · 1.37 KB
/
InMemoryStorage.java
File metadata and controls
54 lines (47 loc) · 1.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package com.lld.inmemorycache.service.impl;
import com.lld.inmemorycache.service.Storage;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;
public class InMemoryStorage implements Storage {
private ConcurrentHashMap<String, String> storage;
private static ReentrantLock lock;
public InMemoryStorage() {
storage = new ConcurrentHashMap<>();
// fairness: first come, first served.
lock = new ReentrantLock(true);
}
@Override
public boolean put(String key, String value) {
lock.lock();
try {
// access _storage. do not allow an exception here.
storage.put(key, value);
} catch (Exception ex) {
return false;
} finally {
lock.unlock();
}
return true;
}
@Override
public String get(String key) {
return storage.get(key);
}
@Override
public boolean remove(String key) {
lock.lock();
try {
// access _storage. do not allow an exception here.
storage.remove(key);
} catch (Exception ex) {
return false;
} finally {
lock.unlock();
}
return true;
}
@Override
public int size() {
return storage.size();
}
}