2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.yangtools.util;
10 import static java.util.Objects.requireNonNull;
12 import com.google.common.collect.ForwardingMap;
14 import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
15 import org.opendaylight.yangtools.triemap.ImmutableTrieMap;
16 import org.opendaylight.yangtools.triemap.MutableTrieMap;
17 import org.slf4j.Logger;
18 import org.slf4j.LoggerFactory;
21 * A read-only facade in front of a TrieMap. This is what we give out from
22 * MapAdaptor.optimize(). The idea is that we want our read-only users to
23 * share a single snapshot. That snapshot is instantiated lazily either on
24 * first access. Since we never leak the TrieMap and track its size as it
25 * changes, we can cache it for future reference.
27 final class ReadOnlyTrieMap<K, V> extends ForwardingMap<K, V> {
28 @SuppressWarnings("rawtypes")
29 private static final AtomicReferenceFieldUpdater<ReadOnlyTrieMap, ImmutableTrieMap> UPDATER =
30 AtomicReferenceFieldUpdater.newUpdater(ReadOnlyTrieMap.class, ImmutableTrieMap.class, "readOnly");
31 private static final Logger LOG = LoggerFactory.getLogger(ReadOnlyTrieMap.class);
32 private final MutableTrieMap<K, V> readWrite;
33 private final int size;
34 private volatile ImmutableTrieMap<K, V> readOnly;
36 ReadOnlyTrieMap(final MutableTrieMap<K, V> map, final int size) {
37 this.readWrite = requireNonNull(map);
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);
48 protected Map<K, V> delegate() {
49 ImmutableTrieMap<K, V> ret = readOnly;
51 ret = readWrite.immutableSnapshot();
52 if (!UPDATER.compareAndSet(this, null, ret)) {