1 package cz.cuni.amis.utils.maps;
2
3 import java.util.Collections;
4 import java.util.HashMap;
5 import java.util.Map;
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 public abstract class LazyMapMap<PRIMARY_KEY, SECONDARY_KEY, ITEM> extends HashMap<PRIMARY_KEY, Map<SECONDARY_KEY, ITEM>> {
21
22 public LazyMapMap() {
23 }
24
25
26
27
28
29
30 protected abstract ITEM create(SECONDARY_KEY key);
31
32
33
34
35
36
37 @Override
38 public Map<SECONDARY_KEY, ITEM> get(Object primaryKey) {
39 Map<SECONDARY_KEY, ITEM> map = super.get(primaryKey);
40 if (map != null) return map;
41 map = Collections.synchronizedMap(new LazyMap<SECONDARY_KEY, ITEM>(){
42 @Override
43 protected ITEM create(SECONDARY_KEY key) {
44 return LazyMapMap.this.create(key);
45 }
46 });
47 super.put((PRIMARY_KEY)primaryKey, map);
48 return map;
49 }
50
51
52
53
54
55
56
57 public ITEM get(PRIMARY_KEY primaryKey, SECONDARY_KEY secondaryKey) {
58 return get(primaryKey).get(secondaryKey);
59 }
60
61
62
63
64
65
66
67 public void put(PRIMARY_KEY primaryKey, SECONDARY_KEY secondaryKey, ITEM item) {
68 get(primaryKey).put(secondaryKey, item);
69 }
70
71
72
73
74
75
76 @Override
77 public Map<SECONDARY_KEY, ITEM> remove(Object primaryKey) {
78 Map<SECONDARY_KEY, ITEM> map = super.remove(primaryKey);
79 if (map != null) return map;
80 return Collections.synchronizedMap(new LazyMap<SECONDARY_KEY, ITEM>(){
81 @Override
82 protected ITEM create(SECONDARY_KEY key) {
83 return LazyMapMap.this.create(key);
84 }
85 });
86 }
87
88
89
90
91
92
93
94 public ITEM remove(PRIMARY_KEY primaryKey, SECONDARY_KEY secondaryKey) {
95 return get(primaryKey).remove(secondaryKey);
96 }
97
98 }