View Javadoc

1   package cz.cuni.amis.utils.maps;
2   
3   import java.util.Collections;
4   import java.util.HashMap;
5   import java.util.Map;
6   import java.util.WeakHashMap;
7   
8   /**
9    * Two-level hashMap where the first-level keys are weakly referenced!
10   * This means that if the key is not strongly referenced elsewhere, the maps can be garbage collected.
11   * @author srlok
12   *
13   * @param <PRIMARY_KEY>
14   * @param <SECONDARY_KEY>
15   * @param <ITEM>
16   */
17  public class WeakHashMapMap<PRIMARY_KEY,SECONDARY_KEY,ITEM>
18  	extends WeakHashMap<PRIMARY_KEY, Map<SECONDARY_KEY, ITEM>> {
19  	
20  	@SuppressWarnings("unchecked")
21  	@Override
22  	public Map<SECONDARY_KEY,ITEM> get(Object primaryKey)
23  	{
24  		Map<SECONDARY_KEY,ITEM> result = super.get( primaryKey );
25  		if (result != null) return result;
26  		result = Collections.synchronizedMap( new HashMap<SECONDARY_KEY,ITEM>() );
27  		super.put( (PRIMARY_KEY)primaryKey, result);
28  		return result;
29  	}
30  	
31  	/**
32  	 * Returns the requested item under primary and secondary key.
33  	 * @param primaryKey weakly-referenced
34  	 * @param secondaryKey
35  	 * @return if no such item exists returns  NULL
36  	 */
37  	public ITEM get(PRIMARY_KEY primaryKey, SECONDARY_KEY secondaryKey)
38  	{
39  		return get(primaryKey).get(secondaryKey);
40  	}
41  	
42  	/**
43  	 * Inserts item under primary and secondary_key.
44  	 * @param primaryKey weakly-referenced
45  	 * @param secondaryKey
46  	 * @param item
47  	 * @return inserted item
48  	 */
49  	public ITEM put(PRIMARY_KEY primaryKey, SECONDARY_KEY secondaryKey, ITEM item)
50  	{
51  		return get(primaryKey).put(secondaryKey, item);
52  	}
53  	
54  	/**
55  	 * removes the item under primary and secondary key.
56  	 * @param primaryKey
57  	 * @param secondaryKey
58  	 * @return removed item
59  	 */
60  	public ITEM remove(PRIMARY_KEY primaryKey, SECONDARY_KEY secondaryKey)
61  	{
62  		return get(primaryKey).remove( secondaryKey);
63  	}
64  	
65  	/**
66  	 * removes all items under primaryKey
67  	 * @param primaryKey
68  	 * @return map of all removed items
69  	 */
70  	@Override
71  	public Map<SECONDARY_KEY,ITEM> remove(Object primaryKey)
72  	{
73  		Map<SECONDARY_KEY,ITEM> result = super.remove(primaryKey);
74  		if (result != null) { return result ; }
75  		result = Collections.synchronizedMap( new HashMap<SECONDARY_KEY,ITEM>() );
76  		return result;
77  	}
78  	
79  	
80  }