All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.tectonica.collections.ConcurrentMultimap Maven / Gradle / Ivy

Go to download

Set of Java utility classes, all completely independent, to provide lightweight solutions for common situations

There is a newer version: 0.6.1
Show newest version
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();
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy