4d429f1aaa11c899f6759cea472d48dabde75171
[yangtools.git] / common / util / src / main / java / org / opendaylight / yangtools / util / ReadOnlyTrieMap.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 java.util.Map;
11
12 import org.slf4j.Logger;
13 import org.slf4j.LoggerFactory;
14
15 import com.google.common.base.Preconditions;
16 import com.google.common.collect.ForwardingMap;
17 import com.romix.scala.collection.concurrent.TrieMap;
18
19 /**
20  * A read-only facade in front of a TrieMap. This is what we give out from
21  * MapAdaptor.optimize(). The idea is that we want our read-only users to
22  * share a single snapshot. That snapshot is instantiated lazily either on
23  * first access. Since we never leak the TrieMap and track its size as it
24  * changes, we can cache it for future reference.
25  */
26 final class ReadOnlyTrieMap<K, V> extends ForwardingMap<K, V> {
27     private static final Logger LOG = LoggerFactory.getLogger(ReadOnlyTrieMap.class);
28     private final TrieMap<K, V> readWrite;
29     private final int size;
30     private volatile TrieMap<K, V> readOnly;
31
32     ReadOnlyTrieMap(final TrieMap<K, V> map, final int size) {
33         super();
34         this.readWrite = Preconditions.checkNotNull(map);
35         this.size = size;
36     }
37
38     Map<K, V> toReadWrite() {
39         final Map<K, V> ret = new ReadWriteTrieMap<>(readWrite.snapshot(), size);
40         LOG.trace("Converted read-only TrieMap {} to read-write {}", this, ret);
41         return ret;
42     }
43
44     @Override
45     protected Map<K, V> delegate() {
46         TrieMap<K, V> ret = readOnly;
47         if (ret == null) {
48             synchronized (this) {
49                 ret = readOnly;
50                 if (ret == null) {
51                     ret = readWrite.readOnlySnapshot();
52                     readOnly = ret;
53                 }
54             }
55         }
56
57         return ret;
58     }
59
60     @Override
61     public int size() {
62         return size;
63     }
64 }