2 * Copyright (c) 2017 Pantheon Technologies, s.r.o. 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.yang.data.codec.gson;
10 import static com.google.common.base.Verify.verifyNotNull;
11 import static java.util.Objects.requireNonNull;
13 import com.google.common.annotations.Beta;
14 import com.google.common.base.Stopwatch;
15 import com.google.common.cache.CacheBuilder;
16 import com.google.common.cache.CacheLoader;
17 import com.google.common.cache.LoadingCache;
18 import java.util.Optional;
19 import java.util.function.BiFunction;
20 import org.eclipse.jdt.annotation.NonNull;
21 import org.opendaylight.yangtools.yang.data.util.codec.LazyCodecCache;
22 import org.opendaylight.yangtools.yang.data.util.codec.NoopCodecCache;
23 import org.opendaylight.yangtools.yang.data.util.codec.PrecomputedCodecCache;
24 import org.opendaylight.yangtools.yang.data.util.codec.SharedCodecCache;
25 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
26 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
27 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
28 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
33 * API entry point for acquiring {@link JSONCodecFactory} instances.
35 * @author Robert Varga
38 public enum JSONCodecFactorySupplier {
40 * Source of {@link JSONCodecFactory} instances compliant with RFC7951.
42 // FIXME: YANGTOOLS-766: use a different codec
43 RFC7951(JSONStringInstanceIdentifierCodec::new),
45 * Source of {@link JSONCodecFactory} instances compliant with RFC7951.
47 DRAFT_LHOTKA_NETMOD_YANG_JSON_02(JSONStringInstanceIdentifierCodec::new);
49 private static final Logger LOG = LoggerFactory.getLogger(JSONCodecFactorySupplier.class);
51 private static final class EagerCacheLoader extends CacheLoader<SchemaContext, JSONCodecFactory> {
52 private final BiFunction<SchemaContext, JSONCodecFactory, JSONStringInstanceIdentifierCodec>
55 EagerCacheLoader(final BiFunction<SchemaContext, JSONCodecFactory, JSONStringInstanceIdentifierCodec>
57 this.iidCodecSupplier = requireNonNull(iidCodecSupplier);
61 public JSONCodecFactory load(final SchemaContext key) {
62 final Stopwatch sw = Stopwatch.createStarted();
63 final LazyCodecCache<JSONCodec<?>> lazyCache = new LazyCodecCache<>();
64 final JSONCodecFactory lazy = new JSONCodecFactory(key, lazyCache, iidCodecSupplier);
65 final int visitedLeaves = requestCodecsForChildren(lazy, key);
68 final PrecomputedCodecCache<JSONCodec<?>> cache = lazyCache.toPrecomputed();
69 LOG.debug("{} leaf nodes resulted in {} simple and {} complex codecs in {}", visitedLeaves,
70 cache.simpleSize(), cache.complexSize(), sw);
71 return new JSONCodecFactory(key, cache, iidCodecSupplier);
74 private static int requestCodecsForChildren(final JSONCodecFactory lazy, final DataNodeContainer parent) {
76 for (DataSchemaNode child : parent.getChildNodes()) {
77 if (child instanceof TypedDataSchemaNode) {
78 lazy.codecFor((TypedDataSchemaNode) child);
80 } else if (child instanceof DataNodeContainer) {
81 ret += requestCodecsForChildren(lazy, (DataNodeContainer) child);
89 private final BiFunction<SchemaContext, JSONCodecFactory, JSONStringInstanceIdentifierCodec> iidCodecSupplier;
91 // Weak keys to retire the entry when SchemaContext goes away
92 private final LoadingCache<SchemaContext, JSONCodecFactory> precomputed;
94 // Weak keys to retire the entry when SchemaContext goes away and to force identity-based lookup
95 private final LoadingCache<SchemaContext, JSONCodecFactory> shared;
97 JSONCodecFactorySupplier(
98 final BiFunction<SchemaContext, JSONCodecFactory, JSONStringInstanceIdentifierCodec> iidCodecSupplier) {
99 this.iidCodecSupplier = requireNonNull(iidCodecSupplier);
100 precomputed = CacheBuilder.newBuilder().weakKeys().build(new EagerCacheLoader(iidCodecSupplier));
101 shared = CacheBuilder.newBuilder().weakKeys().build(new CacheLoader<SchemaContext, JSONCodecFactory>() {
103 public JSONCodecFactory load(final SchemaContext key) {
104 return new JSONCodecFactory(key, new SharedCodecCache<>(), iidCodecSupplier);
110 * Get a thread-safe, eagerly-caching {@link JSONCodecFactory} for a SchemaContext. This method can, and will,
111 * return the same instance as long as the associated SchemaContext is present. Returned object can be safely
112 * used by multiple threads concurrently. If the SchemaContext instance does not have a cached instance
113 * of {@link JSONCodecFactory}, it will be completely precomputed before this method will return.
116 * Choosing this implementation is appropriate when the memory overhead of keeping a full codec tree is not as
117 * great a concern as predictable performance. When compared to the implementation returned by
118 * {@link #getShared(SchemaContext)}, this implementation is expected to offer higher performance and have lower
119 * peak memory footprint when most of the SchemaContext is actually in use.
122 * For call sites which do not want to pay the CPU cost of pre-computing this implementation, but still would like
123 * to use it if is available (by being populated by some other caller), you can use
124 * {@link #getPrecomputedIfAvailable(SchemaContext)}.
126 * @param context SchemaContext instance
127 * @return A sharable {@link JSONCodecFactory}
128 * @throws NullPointerException if context is null
130 public @NonNull JSONCodecFactory getPrecomputed(final @NonNull SchemaContext context) {
131 return verifyNotNull(precomputed.getUnchecked(context));
135 * Get a thread-safe, eagerly-caching {@link JSONCodecFactory} for a SchemaContext, if it is available. This
136 * method is a non-blocking equivalent of {@link #getPrecomputed(SchemaContext)} for use in code paths where
137 * the potential of having to pre-compute the implementation is not acceptable. One such scenario is when the
138 * code base wants to opportunistically take advantage of pre-computed version, but is okay with a fallback to
139 * a different implementation.
141 * @param context SchemaContext instance
142 * @return A sharable {@link JSONCodecFactory}, or absent if such an implementation is not available.
143 * @throws NullPointerException if context is null
145 public @NonNull Optional<JSONCodecFactory> getPrecomputedIfAvailable(final @NonNull SchemaContext context) {
146 return Optional.ofNullable(precomputed.getIfPresent(context));
150 * Get a thread-safe, lazily-caching {@link JSONCodecFactory} for a SchemaContext. This method can, and will,
151 * return the same instance as long as the associated SchemaContext is present or the factory is not invalidated
152 * by memory pressure. Returned object can be safely used by multiple threads concurrently.
155 * Choosing this implementation is a safe default, as it will not incur prohibitive blocking, nor will it tie up
156 * memory in face of pressure.
158 * @param context SchemaContext instance
159 * @return A sharable {@link JSONCodecFactory}
160 * @throws NullPointerException if context is null
162 public @NonNull JSONCodecFactory getShared(final @NonNull SchemaContext context) {
163 return verifyNotNull(shared.getUnchecked(context));
167 * Create a new thread-unsafe, lazily-caching {@link JSONCodecFactory} for a SchemaContext. This method will
168 * return distinct objects every time it is invoked. Returned object may not be used from multiple threads
172 * This implementation is appropriate for one-off serialization from a single thread. It will aggressively cache
173 * codecs for reuse and will tie them up in memory until the factory is freed.
175 * @param context SchemaContext instance
176 * @return A non-sharable {@link JSONCodecFactory}
177 * @throws NullPointerException if context is null
179 public @NonNull JSONCodecFactory createLazy(final @NonNull SchemaContext context) {
180 return new JSONCodecFactory(context, new LazyCodecCache<>(), iidCodecSupplier);
184 * Create a simplistic, thread-safe {@link JSONCodecFactory} for a {@link SchemaContext}. This method will return
185 * distinct objects every time it is invoked. Returned object may be use from multiple threads concurrently.
188 * This implementation exists mostly for completeness only, as it does not perform any caching at all and each codec
189 * is computed every time it is requested. This may be useful in extremely constrained environments, where memory
190 * footprint is more critical than performance.
192 * @param context SchemaContext instance
193 * @return A non-sharable {@link JSONCodecFactory}
194 * @throws NullPointerException if context is null.
196 public @NonNull JSONCodecFactory createSimple(final @NonNull SchemaContext context) {
197 return new JSONCodecFactory(context, NoopCodecCache.getInstance(), iidCodecSupplier);