Extract memory-based identity database into its own class.
[Sone.git] / src / main / java / net / pterodactylus / sone / database / memory / MemoryIdentityDatabase.java
1 package net.pterodactylus.sone.database.memory;
2
3 import static com.google.common.base.Optional.fromNullable;
4 import static com.google.common.collect.Maps.newHashMap;
5
6 import java.util.Map;
7 import java.util.concurrent.locks.ReadWriteLock;
8
9 import net.pterodactylus.sone.database.IdentityDatabase;
10 import net.pterodactylus.sone.freenet.wot.Identity;
11
12 import com.google.common.base.Optional;
13
14 /**
15  * {@link IdentityDatabase} implementation that keeps all {@link Identity}s in
16  * memory.
17  *
18  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
19  */
20 public class MemoryIdentityDatabase implements IdentityDatabase {
21
22         private final ReadWriteLock lock;
23         private final Map<String, Identity> identities = newHashMap();
24
25         public MemoryIdentityDatabase(ReadWriteLock readWriteLock) {
26                 this.lock = readWriteLock;
27         }
28
29         @Override
30         public Optional<Identity> getIdentity(String identityId) {
31                 lock.readLock().lock();
32                 try {
33                         return fromNullable(identities.get(identityId));
34                 } finally {
35                         lock.readLock().unlock();
36                 }
37         }
38
39         @Override
40         public void storeIdentity(Identity identitiy) {
41                 lock.writeLock().lock();
42                 try {
43                         identities.put(identitiy.getId(), identitiy);
44                 } finally {
45                         lock.writeLock().unlock();
46                 }
47         }
48
49 }