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.util.codec;
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;
20 * A thread-safe lazily-populated codec cache. Instances are cached in an internal weak/soft cache.
22 * @author Robert Varga
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();
33 public T lookupComplex(final TypedSchemaNode schema) {
34 return complexCodecs.getIfPresent(schema);
38 public T lookupSimple(final TypeDefinition<?> type) {
39 return simpleCodecs.getIfPresent(type);
43 public T getComplex(final TypedSchemaNode schema, final T codec) {
45 return complexCodecs.get(schema, () -> codec);
46 } catch (ExecutionException e) {
47 throw Throwables.propagate(e.getCause());
52 public T getSimple(final TypeDefinition<?> type, final T codec) {
54 return simpleCodecs.get(type, () -> codec);
55 } catch (ExecutionException e) {
56 throw Throwables.propagate(e.getCause());