BUG-7464: Switch to use forked TrieMap
[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 com.google.common.base.Preconditions;
11 import com.google.common.collect.ForwardingMap;
12 import java.util.Map;
13 import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
14 import org.opendaylight.yangtools.triemap.ImmutableTrieMap;
15 import org.opendaylight.yangtools.triemap.MutableTrieMap;
16 import org.slf4j.Logger;
17 import org.slf4j.LoggerFactory;
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     @SuppressWarnings("rawtypes")
28     private static final AtomicReferenceFieldUpdater<ReadOnlyTrieMap, ImmutableTrieMap> UPDATER =
29             AtomicReferenceFieldUpdater.newUpdater(ReadOnlyTrieMap.class, ImmutableTrieMap.class, "readOnly");
30     private static final Logger LOG = LoggerFactory.getLogger(ReadOnlyTrieMap.class);
31     private final MutableTrieMap<K, V> readWrite;
32     private final int size;
33     private volatile ImmutableTrieMap<K, V> readOnly;
34
35     ReadOnlyTrieMap(final MutableTrieMap<K, V> map, final int size) {
36         super();
37         this.readWrite = Preconditions.checkNotNull(map);
38         this.size = size;
39     }
40
41     Map<K, V> toReadWrite() {
42         final Map<K, V> ret = new ReadWriteTrieMap<>(readWrite.mutableSnapshot(), size);
43         LOG.trace("Converted read-only TrieMap {} to read-write {}", this, ret);
44         return ret;
45     }
46
47     @Override
48     protected Map<K, V> delegate() {
49         ImmutableTrieMap<K, V> ret = readOnly;
50         if (ret == null) {
51             ret = readWrite.immutableSnapshot();
52             if (!UPDATER.compareAndSet(this, null, ret)) {
53                 ret = readOnly;
54             }
55         }
56         return ret;
57     }
58
59     @Override
60     public int size() {
61         return size;
62     }
63 }