2 * Copyright (c) 2017 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.yang.data.codec.gson;
10 import com.google.common.base.Throwables;
11 import com.google.common.cache.Cache;
12 import com.google.common.cache.CacheBuilder;
13 import com.google.common.cache.CacheLoader;
14 import com.google.common.cache.LoadingCache;
15 import java.util.concurrent.ExecutionException;
16 import javax.annotation.concurrent.ThreadSafe;
17 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
18 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
19 import org.opendaylight.yangtools.yang.model.api.TypedSchemaNode;
22 * A thread-safe lazily-populated codec factory. Instances are cached in an internal weak/soft cache.
24 * @author Robert Varga
27 final class SharedJSONCodecFactory extends JSONCodecFactory {
28 // Weak keys to retire the entry when SchemaContext goes away and to force identity-based lookup
29 private static final LoadingCache<SchemaContext, SharedJSONCodecFactory> CACHE = CacheBuilder.newBuilder()
30 .weakKeys().build(new CacheLoader<SchemaContext, SharedJSONCodecFactory>() {
32 public SharedJSONCodecFactory load(final SchemaContext key) {
33 return new SharedJSONCodecFactory(key);
37 // Weak keys to force identity lookup
38 // Soft values to keep unreferenced codecs around for a bit, but eventually we want them to go away
39 private final Cache<TypeDefinition<?>, JSONCodec<?>> simpleCodecs = CacheBuilder.newBuilder().weakKeys()
40 .softValues().build();
41 private final Cache<TypedSchemaNode, JSONCodec<?>> complexCodecs = CacheBuilder.newBuilder().weakKeys().softValues()
44 SharedJSONCodecFactory(final SchemaContext context) {
48 static SharedJSONCodecFactory getIfPresent(final SchemaContext context) {
49 return CACHE.getIfPresent(context);
52 static SharedJSONCodecFactory get(final SchemaContext context) {
53 return CACHE.getUnchecked(context);
57 JSONCodec<?> lookupComplex(final TypedSchemaNode schema) {
58 return complexCodecs.getIfPresent(schema);
62 JSONCodec<?> lookupSimple(final TypeDefinition<?> type) {
63 return simpleCodecs.getIfPresent(type);
67 JSONCodec<?> getComplex(final TypedSchemaNode schema, final JSONCodec<?> codec) {
69 return complexCodecs.get(schema, () -> codec);
70 } catch (ExecutionException e) {
71 throw Throwables.propagate(e.getCause());
76 JSONCodec<?> getSimple(final TypeDefinition<?> type, final JSONCodec<?> codec) {
78 return simpleCodecs.get(type, () -> codec);
79 } catch (ExecutionException e) {
80 throw Throwables.propagate(e.getCause());