1/**
2 * Copyright (C) 2008 Google Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.google.inject.internal;
18
19import com.google.common.cache.CacheBuilder;
20import com.google.common.cache.CacheLoader;
21import com.google.common.cache.LoadingCache;
22
23/**
24 * Lazily creates (and caches) values for keys. If creating the value fails (with errors), an
25 * exception is thrown on retrieval.
26 *
27 * @author jessewilson@google.com (Jesse Wilson)
28 */
29public abstract class FailableCache<K, V> {
30
31  private final LoadingCache<K, Object> delegate = CacheBuilder.newBuilder().build(
32      new CacheLoader<K, Object>() {
33        public Object load(K key) {
34          Errors errors = new Errors();
35          V result = null;
36          try {
37            result = FailableCache.this.create(key, errors);
38          } catch (ErrorsException e) {
39            errors.merge(e.getErrors());
40          }
41          return errors.hasErrors() ? errors : result;
42        }
43      });
44
45  protected abstract V create(K key, Errors errors) throws ErrorsException;
46
47  public V get(K key, Errors errors) throws ErrorsException {
48    Object resultOrError = delegate.getUnchecked(key);
49    if (resultOrError instanceof Errors) {
50      errors.merge((Errors) resultOrError);
51      throw errors.toException();
52    } else {
53      @SuppressWarnings("unchecked") // create returned a non-error result, so this is safe
54      V result = (V) resultOrError;
55      return result;
56    }
57  }
58
59  boolean remove(K key) {
60    return delegate.asMap().remove(key) != null;
61  }
62}
63