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 org.opendaylight.yangtools.yang.model.api.SchemaNode;
16 import org.opendaylight.yangtools.yang.model.api.TypeAware;
17 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
20 * A thread-safe lazily-populated codec cache. Instances are cached in an internal weak/soft cache.
22 * @author Robert Varga
25 public final class SharedCodecCache<T> extends CodecCache<T> {
26 // Weak keys to force identity lookup
27 // Soft values to keep unreferenced codecs around for a bit, but eventually we want them to go away
28 private final Cache<TypeDefinition<?>, T> simpleCodecs = CacheBuilder.newBuilder().weakKeys().softValues().build();
29 private final Cache<SchemaNode, T> complexCodecs = CacheBuilder.newBuilder().weakKeys().softValues().build();
32 public <S extends SchemaNode & TypeAware> T lookupComplex(final S schema) {
33 return complexCodecs.getIfPresent(schema);
37 T lookupSimple(final TypeDefinition<?> type) {
38 return simpleCodecs.getIfPresent(type);
42 <S extends SchemaNode & TypeAware> T getComplex(final S schema, final T codec) {
44 return complexCodecs.get(schema, () -> codec);
45 } catch (ExecutionException e) {
46 final Throwable cause = e.getCause();
47 Throwables.throwIfUnchecked(cause);
48 throw new IllegalStateException(e);
53 T getSimple(final TypeDefinition<?> type, final T codec) {
55 return simpleCodecs.get(type, () -> codec);
56 } catch (ExecutionException e) {
57 final Throwable cause = e.getCause();
58 Throwables.throwIfUnchecked(cause);
59 throw new IllegalStateException(e);