BUG-7983: extract codec caching from JSONCodecFactory
[yangtools.git] / yang / yang-data-util / src / main / java / org / opendaylight / yangtools / yang / data / util / codec / SharedCodecCache.java
1 /*
2  * Copyright (c) 2017 Pantheon Technologies, s.r.o. 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.yang.data.util.codec;
9
10 import com.google.common.annotations.Beta;
11 import com.google.common.base.Throwables;
12 import com.google.common.cache.Cache;
13 import com.google.common.cache.CacheBuilder;
14 import java.util.concurrent.ExecutionException;
15 import javax.annotation.concurrent.ThreadSafe;
16 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
17 import org.opendaylight.yangtools.yang.model.api.TypedSchemaNode;
18
19 /**
20  * A thread-safe lazily-populated codec cache. Instances are cached in an internal weak/soft cache.
21  *
22  * @author Robert Varga
23  */
24 @Beta
25 @ThreadSafe
26 public final class SharedCodecCache<T> extends CodecCache<T> {
27     // Weak keys to force identity lookup
28     // Soft values to keep unreferenced codecs around for a bit, but eventually we want them to go away
29     private final Cache<TypeDefinition<?>, T> simpleCodecs = CacheBuilder.newBuilder().weakKeys().softValues().build();
30     private final Cache<TypedSchemaNode, T> complexCodecs = CacheBuilder.newBuilder().weakKeys().softValues().build();
31
32     @Override
33     public T lookupComplex(final TypedSchemaNode schema) {
34         return complexCodecs.getIfPresent(schema);
35     }
36
37     @Override
38     public T lookupSimple(final TypeDefinition<?> type) {
39         return simpleCodecs.getIfPresent(type);
40     }
41
42     @Override
43     public T getComplex(final TypedSchemaNode schema, final T codec) {
44         try {
45             return complexCodecs.get(schema, () -> codec);
46         } catch (ExecutionException e) {
47             throw Throwables.propagate(e.getCause());
48         }
49     }
50
51     @Override
52     public T getSimple(final TypeDefinition<?> type, final T codec) {
53         try {
54             return simpleCodecs.get(type, () -> codec);
55         } catch (ExecutionException e) {
56             throw Throwables.propagate(e.getCause());
57         }
58     }
59 }