com.tectonica.collections.ConcurrentMultimap Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of tectonica-commons Show documentation
Show all versions of tectonica-commons Show documentation
Set of Java utility classes, all completely independent, to provide lightweight solutions for common situations
package com.tectonica.collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
public class ConcurrentMultimap
{
private ConcurrentHashMap> map = new ConcurrentHashMap<>();
public int put(K key, V value)
{
return put(key, value, true);
}
public int put(K key, V value, boolean autoCreateKey)
{
Set valuesSet;
if (autoCreateKey)
{
HashSet emptySet = new HashSet();
valuesSet = map.putIfAbsent(key, emptySet);
if (valuesSet == null)
valuesSet = emptySet;
}
else
{
valuesSet = map.get(key);
if (valuesSet == null)
return 0;
}
synchronized (valuesSet)
{
valuesSet.add(value);
}
return valuesSet.size();
}
public Set get(K key)
{
Set valuesSet = map.get(key);
if (valuesSet == null)
return null;
synchronized (valuesSet)
{
return new HashSet(valuesSet);
}
}
public int remove(K key, V value)
{
Set valuesSet = map.get(key);
if (valuesSet == null)
return 0;
synchronized (valuesSet)
{
valuesSet.remove(value);
if (valuesSet.isEmpty())
map.remove(key);
return valuesSet.size();
}
}
public void removeFromAll(V value)
{
for (K key : map.keySet())
remove(key, value);
}
public void clear()
{
map.clear();
}
}