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