Return unmodifiable view of packs
[xudocci.git] / src / main / java / net / pterodactylus / xdcc / data / Bot.java
index 211dde7..c9e2a9b 100644 (file)
@@ -20,6 +20,7 @@ package net.pterodactylus.xdcc.data;
 import static com.google.common.base.Preconditions.checkNotNull;
 
 import java.util.Collection;
+import java.util.Collections;
 import java.util.Iterator;
 import java.util.Map;
 
@@ -39,6 +40,7 @@ public class Bot implements Iterable<Pack> {
 
        /** The packs this bot carries. */
        private final Map<String, Pack> packs = Maps.newHashMap();
+       private final Map<String, Pack> packsByName = Maps.newHashMap();
 
        /** The current name of the bot. */
        private String name;
@@ -81,7 +83,9 @@ public class Bot implements Iterable<Pack> {
         * @return The packs this bot carries
         */
        public Collection<Pack> packs() {
-               return packs.values();
+               synchronized (packs) {
+                       return Collections.unmodifiableCollection(packs.values());
+               }
        }
 
        //
@@ -111,7 +115,14 @@ public class Bot implements Iterable<Pack> {
         *              The pack to add
         */
        public void addPack(Pack pack) {
-               packs.put(pack.id(), pack);
+               synchronized (this) {
+                       if (packsByName.containsKey(pack.name())) {
+                               Pack oldPack = packsByName.remove(pack.name());
+                               packs.remove(oldPack.id());
+                       }
+                       packs.put(pack.id(), pack);
+                       packsByName.put(pack.name(), pack);
+               }
        }
 
        //
@@ -120,7 +131,7 @@ public class Bot implements Iterable<Pack> {
 
        @Override
        public Iterator<Pack> iterator() {
-               return packs.values().iterator();
+               return packs().iterator();
        }
 
        //