1 package net.pterodactylus.sone.database.memory;
3 import java.util.Collection;
4 import java.util.concurrent.locks.ReadWriteLock;
5 import java.util.concurrent.locks.ReentrantReadWriteLock;
7 import com.google.common.collect.HashMultimap;
8 import com.google.common.collect.Multimap;
11 * In-memory implementation of friend-related functionality.
13 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
15 class MemoryFriendDatabase {
17 private final ReadWriteLock lock = new ReentrantReadWriteLock();
18 private final ConfigurationLoader configurationLoader;
19 private final Multimap<String, String> soneFriends = HashMultimap.create();
21 MemoryFriendDatabase(ConfigurationLoader configurationLoader) {
22 this.configurationLoader = configurationLoader;
25 Collection<String> getFriends(String localSoneId) {
26 loadFriends(localSoneId);
27 lock.readLock().lock();
29 return soneFriends.get(localSoneId);
31 lock.readLock().unlock();
35 boolean isFriend(String localSoneId, String friendSoneId) {
36 loadFriends(localSoneId);
37 lock.readLock().lock();
39 return soneFriends.containsEntry(localSoneId, friendSoneId);
41 lock.readLock().unlock();
45 void addFriend(String localSoneId, String friendSoneId) {
46 loadFriends(localSoneId);
47 lock.writeLock().lock();
49 if (soneFriends.put(localSoneId, friendSoneId)) {
50 configurationLoader.saveFriends(localSoneId, soneFriends.get(localSoneId));
53 lock.writeLock().unlock();
57 void removeFriend(String localSoneId, String friendSoneId) {
58 loadFriends(localSoneId);
59 lock.writeLock().lock();
61 if (soneFriends.remove(localSoneId, friendSoneId)) {
62 configurationLoader.saveFriends(localSoneId, soneFriends.get(localSoneId));
65 lock.writeLock().unlock();
69 private void loadFriends(String localSoneId) {
70 lock.writeLock().lock();
72 if (soneFriends.containsKey(localSoneId)) {
75 soneFriends.putAll(localSoneId, configurationLoader.loadFriends(localSoneId));
77 lock.writeLock().unlock();