Introduce NodeIdentifier.create() 73/26473/2
authorRobert Varga <rovarga@cisco.com>
Thu, 3 Sep 2015 16:21:55 +0000 (18:21 +0200)
committerRobert Varga <rovarga@cisco.com>
Thu, 3 Sep 2015 17:40:18 +0000 (19:40 +0200)
The number of possible NodeIdentifier objects for a particular
SchemaContext is bound by the number of leaves it contains. This means
we can reuse the same objects for the same input QName.

Change-Id: I700f0c45a5e93dd5a3a7e1270cf9ad5a99d363a4
Signed-off-by: Robert Varga <rovarga@cisco.com>
yang/yang-data-api/src/main/java/org/opendaylight/yangtools/yang/data/api/YangInstanceIdentifier.java

index 039187cc889edea6460f5dd5be2002feaffdd425..81f474db58c1b0ded8d3383b1cc34effbf50c6d9 100644 (file)
@@ -10,6 +10,9 @@ package org.opendaylight.yangtools.yang.data.api;
 import com.google.common.annotations.Beta;
 import com.google.common.base.Optional;
 import com.google.common.base.Preconditions;
+import com.google.common.cache.CacheBuilder;
+import com.google.common.cache.CacheLoader;
+import com.google.common.cache.LoadingCache;
 import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.ImmutableSet;
 import com.google.common.collect.Iterables;
@@ -459,10 +462,28 @@ public abstract class YangInstanceIdentifier implements Path<YangInstanceIdentif
      */
     public static final class NodeIdentifier extends AbstractPathArgument {
         private static final long serialVersionUID = -2255888212390871347L;
+        private static final LoadingCache<QName, NodeIdentifier> CACHE = CacheBuilder.newBuilder().weakValues()
+                .build(new CacheLoader<QName, NodeIdentifier>() {
+                    @Override
+                    public NodeIdentifier load(final QName key) {
+                        return new NodeIdentifier(key);
+                    }
+                });
 
         public NodeIdentifier(final QName node) {
             super(node);
         }
+
+        /**
+         * Return a NodeIdentifier for a particular QName. Unlike the constructor, this factory method uses a global
+         * instance cache, resulting in object reuse for equal inputs.
+         *
+         * @param node Node's QName
+         * @return A {@link NodeIdentifier}
+         */
+        public static NodeIdentifier create(final QName node) {
+            return CACHE.getUnchecked(node);
+        }
     }
 
     /**