Refactor TypedSchemaNode
[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.TypedDataSchemaNode;
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<TypedDataSchemaNode, T> complexCodecs = CacheBuilder.newBuilder().weakKeys().softValues()
31         .build();
32
33     @Override
34     public T lookupComplex(final TypedDataSchemaNode schema) {
35         return complexCodecs.getIfPresent(schema);
36     }
37
38     @Override
39     T lookupSimple(final TypeDefinition<?> type) {
40         return simpleCodecs.getIfPresent(type);
41     }
42
43     @Override
44     T getComplex(final TypedDataSchemaNode schema, final T codec) {
45         try {
46             return complexCodecs.get(schema, () -> codec);
47         } catch (ExecutionException e) {
48             final Throwable cause = e.getCause();
49             Throwables.throwIfUnchecked(cause);
50             throw new RuntimeException(e);
51         }
52     }
53
54     @Override
55     T getSimple(final TypeDefinition<?> type, final T codec) {
56         try {
57             return simpleCodecs.get(type, () -> codec);
58         } catch (ExecutionException e) {
59             final Throwable cause = e.getCause();
60             Throwables.throwIfUnchecked(cause);
61             throw new RuntimeException(e);
62         }
63     }
64 }