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.TypedDataSchemaNode;
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<TypedDataSchemaNode, T> complexCodecs = CacheBuilder.newBuilder().weakKeys().softValues()
34 public T lookupComplex(final TypedDataSchemaNode schema) {
35 return complexCodecs.getIfPresent(schema);
39 T lookupSimple(final TypeDefinition<?> type) {
40 return simpleCodecs.getIfPresent(type);
44 T getComplex(final TypedDataSchemaNode schema, final T codec) {
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);
55 T getSimple(final TypeDefinition<?> type, final T codec) {
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);