Introduce MapAdaptor.initialSnapshot()
[yangtools.git] / common / util / src / main / java / org / opendaylight / yangtools / util / MapAdaptor.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.yangtools.util;
9
10 import com.google.common.base.Preconditions;
11 import com.google.common.collect.ImmutableMap;
12 import com.google.common.collect.Maps;
13 import com.romix.scala.collection.concurrent.TrieMap;
14 import java.util.Collections;
15 import java.util.HashMap;
16 import java.util.Map;
17 import java.util.Map.Entry;
18 import org.slf4j.Logger;
19 import org.slf4j.LoggerFactory;
20
21 /**
22  * A simple layer on top of maps, which performs snapshot mediation and optimization of
23  * what the underlying implementation is.
24  */
25 public final class MapAdaptor {
26     public static final int DEFAULT_COPY_MAX_ITEMS = 100;
27     public static final String COPY_MAX_ITEMS_MAX_PROP = "org.opendaylight.yangtools.util.mapadaptor.maxcopy";
28
29     public static final int DEFAULT_PERSIST_MIN_ITEMS = 50;
30     public static final String PERSIST_MIN_ITEMS_PROP = "org.opendaylight.yangtools.util.mapadaptor.minpersist";
31
32     private static final Logger LOG = LoggerFactory.getLogger(MapAdaptor.class);
33     private static final MapAdaptor DEFAULT_INSTANCE;
34
35     private final boolean useSingleton;
36     private final int persistMinItems;
37     private final int copyMaxItems;
38
39     static {
40         DEFAULT_INSTANCE = new MapAdaptor(true,
41                 getProperty(COPY_MAX_ITEMS_MAX_PROP, DEFAULT_COPY_MAX_ITEMS),
42                 getProperty(PERSIST_MIN_ITEMS_PROP, DEFAULT_PERSIST_MIN_ITEMS));
43         LOG.debug("Configured HashMap/TrieMap cutoff at {}/{} entries",
44                 DEFAULT_INSTANCE.persistMinItems, DEFAULT_INSTANCE.copyMaxItems);
45     }
46
47     private static final int getProperty(final String name, final int defaultValue) {
48         try {
49             final String p = System.getProperty(name);
50             if (p != null) {
51                 try {
52                     int pi = Integer.valueOf(p);
53                     if (pi <= 0) {
54                         LOG.warn("Ignoring illegal value of {}: has to be a positive number", name);
55                     } else {
56                         return pi;
57                     }
58                 } catch (NumberFormatException e) {
59                     LOG.warn("Ignoring non-numerical value of {}", name, e);
60                 }
61             }
62         } catch (Exception e) {
63             LOG.debug("Failed to get {}", name, e);
64         }
65         return defaultValue;
66     }
67
68     private MapAdaptor(final boolean useSingleton, final int copyMaxItems, final int persistMinItems) {
69         this.useSingleton = useSingleton;
70         this.copyMaxItems = copyMaxItems;
71         this.persistMinItems = persistMinItems;
72     }
73
74     /**
75      * Return the default-configured instance.
76      *
77      * @return the singleton global instance
78      */
79     public static MapAdaptor getDefaultInstance() {
80         return DEFAULT_INSTANCE;
81     }
82
83     public static MapAdaptor getInstance(final boolean useSingleton, final int copyMaxItems, final int persistMinItems) {
84         Preconditions.checkArgument(copyMaxItems >= 0, "copyMaxItems has to be a non-negative integer");
85         Preconditions.checkArgument(persistMinItems >= 0, "persistMinItems has to be a positive integer");
86         Preconditions.checkArgument(persistMinItems <= copyMaxItems, "persistMinItems must be less than or equal to copyMaxItems");
87         return new MapAdaptor(useSingleton, copyMaxItems, persistMinItems);
88     }
89
90     /**
91      * Creates an initial snapshot. The backing map is selected according to
92      * the expected size.
93      *
94      * @param expectedSize Expected map size
95      * @return An empty mutable map.
96      */
97     public <K, V> Map<K, V> initialSnapshot(final int expectedSize) {
98         Preconditions.checkArgument(expectedSize >= 0);
99         if (expectedSize > persistMinItems) {
100             return new ReadWriteTrieMap<>();
101         }
102
103         return Maps.newHashMapWithExpectedSize(expectedSize);
104     }
105
106     /**
107      * Input is treated is supposed to be left unmodified, result must be mutable.
108      *
109      * @param input
110      * @return
111      */
112     public <K, V> Map<K, V> takeSnapshot(final Map<K, V> input) {
113         if (input instanceof ReadOnlyTrieMap) {
114             return ((ReadOnlyTrieMap<K, V>)input).toReadWrite();
115         }
116
117         LOG.trace("Converting input {} to a HashMap", input);
118
119         // FIXME: be a bit smart about allocation based on observed size
120
121         final Map<K, V> ret = new HashMap<>(input);
122         LOG.trace("Read-write HashMap is {}", ret);
123         return ret;
124     }
125
126     /**
127      * Input will be thrown away, result will be retained for read-only access or
128      * {@link #takeSnapshot(Map)} purposes.
129      *
130      * @param input
131      * @return
132      */
133     public <K, V> Map<K, V> optimize(final Map<K, V> input) {
134         if (input instanceof ReadOnlyTrieMap) {
135             LOG.warn("Optimizing read-only map {}", input);
136         }
137
138         final int size = input.size();
139
140         /*
141          * No-brainer :)
142          */
143         if (size == 0) {
144             LOG.trace("Reducing input {} to an empty map", input);
145             return ImmutableMap.of();
146         }
147
148         /*
149          * We retain the persistent map as long as it holds at least
150          * persistMinItems
151          */
152         if (input instanceof ReadWriteTrieMap && size >= persistMinItems) {
153             return ((ReadWriteTrieMap<K, V>)input).toReadOnly();
154         }
155
156         /*
157          * If the user opted to use singleton maps, use them. Except for the case
158          * when persistMinItems dictates we should not move off of the persistent
159          * map.
160          */
161         if (useSingleton && size == 1) {
162             final Entry<K, V> e = input.entrySet().iterator().next();
163             final Map<K, V> ret = Collections.singletonMap(e.getKey(), e.getValue());
164             LOG.trace("Reducing input {} to singleton map {}", input, ret);
165             return ret;
166         }
167
168         if (size <= copyMaxItems) {
169             /*
170              * Favor access speed: use a HashMap and copy it on modification.
171              */
172             if (input instanceof HashMap) {
173                 return input;
174             }
175
176             LOG.trace("Copying input {} to a HashMap ({} entries)", input, size);
177             final Map<K, V> ret = new HashMap<>(input);
178             LOG.trace("Read-only HashMap is {}", ret);
179             return ret;
180         }
181
182         /*
183          * Favor isolation speed: use a TrieMap and perform snapshots
184          *
185          * This one is a bit tricky, as the TrieMap is concurrent and does not
186          * keep an uptodate size. Updating it requires a full walk -- which is
187          * O(N) and we want to avoid that. So we wrap it in an interceptor,
188          * which will maintain the size for us.
189          */
190         LOG.trace("Copying input {} to a TrieMap ({} entries)", input, size);
191         final TrieMap<K, V> map = new TrieMap<>();
192         map.putAll(input);
193         final Map<K, V> ret = new ReadOnlyTrieMap<>(map, size);
194         LOG.trace("Read-only TrieMap is {}", ret);
195         return ret;
196     }
197 }