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;
13 import java.lang.invoke.MethodHandles;
14 import java.lang.invoke.VarHandle;
15 import org.slf4j.Logger;
16 import org.slf4j.LoggerFactory;
17 import tech.pantheon.triemap.ImmutableTrieMap;
18 import tech.pantheon.triemap.MutableTrieMap;
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 private static final Logger LOG = LoggerFactory.getLogger(ReadOnlyTrieMap.class);
29 private static final VarHandle READ_ONLY;
33 READ_ONLY = MethodHandles.lookup().findVarHandle(ReadOnlyTrieMap.class, "readOnly", ImmutableTrieMap.class);
34 } catch (NoSuchFieldException | IllegalAccessException e) {
35 throw new ExceptionInInitializerError(e);
39 private final MutableTrieMap<K, V> readWrite;
40 private final int size;
42 // Used via the varhandle
43 @SuppressWarnings("unused")
44 private volatile ImmutableTrieMap<K, V> readOnly;
46 ReadOnlyTrieMap(final MutableTrieMap<K, V> map, final int size) {
47 this.readWrite = requireNonNull(map);
51 ReadWriteTrieMap<K, V> toReadWrite() {
52 final ReadWriteTrieMap<K, V> ret = new ReadWriteTrieMap<>(readWrite.mutableSnapshot(), size);
53 LOG.trace("Converted read-only TrieMap {} to read-write {}", this, ret);
58 protected ImmutableTrieMap<K, V> delegate() {
59 final ImmutableTrieMap<K, V> ret = (ImmutableTrieMap<K, V>) READ_ONLY.getAcquire(this);
60 return ret != null ? ret : loadReadOnly();
68 @SuppressWarnings("unchecked")
69 private ImmutableTrieMap<K, V> loadReadOnly() {
70 final ImmutableTrieMap<K, V> ret = readWrite.immutableSnapshot();
71 final Object witness = READ_ONLY.compareAndExchangeRelease(this, null, ret);
72 return witness == null ? ret : (ImmutableTrieMap<K, V>) witness;