Java Code Examples for com.google.common.cache.LoadingCache#get()

The following examples show how to use com.google.common.cache.LoadingCache#get() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GuavaCacheLoaderUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenCacheLoader_whenRefreshingItem_shouldCallAgain() throws ExecutionException {

    final LoadingCache<String, String> loadingCache = CacheBuilder.newBuilder()
        .build(new CacheLoader<String, String>() {
            @Override
            public String load(final String s) throws Exception {
                return slowMethod(s);
            }
        });

    String value = loadingCache.get("key");
    loadingCache.refresh("key");

    assertThat(callCount).isEqualTo(2);
    assertThat(value).isEqualTo("key");
}
 
Example 2
Source File: GuavaCacheLoaderUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenCacheLoader_whenGettingItemTwice_shouldOnlyCallOnce() throws ExecutionException {

    final LoadingCache<String, String> loadingCache = CacheBuilder.newBuilder()
        .build(new CacheLoader<String, String>() {
            @Override
            public String load(final String s) throws Exception {
                return slowMethod(s);
            }
        });

    String value = loadingCache.get("key");
    value = loadingCache.get("key");

    assertThat(callCount).isEqualTo(1);
    assertThat(value).isEqualTo("key");
}
 
Example 3
Source File: ReplaceMapper.java    From copybara with Apache License 2.0 6 votes vote down vote up
@Override
public String apply(String s) {
  LoadingCache<Replace, Replacer> cache = REPLACE_CACHE.get();
  String replacement = s;
  try {
    for (Replace replace : replaces) {
      Replacer replacer = cache.get(replace);
      replacement = replacer.replace(replacement);
      if (all) {
        continue;
      }
      if (replacement.equals(s)) {
        continue;
      }
      return replacement;
    }
  } catch (ExecutionException e) {
    throw new RuntimeException("Shouldn't happen", e);
  }
  return replacement;
}
 
Example 4
Source File: CacheUtil.java    From jpmml-evaluator with GNU Affero General Public License v3.0 6 votes vote down vote up
static
public <K extends PMMLObject, V> V getValue(K key, LoadingCache<K, V> cache){

	try {
		return cache.get(key);
	} catch(ExecutionException | UncheckedExecutionException e){
		Throwable cause = e.getCause();

		if(cause instanceof PMMLException){
			throw (PMMLException)cause;
		}

		throw new InvalidElementException(key)
			.initCause(cause);
	}
}
 
Example 5
Source File: Utils.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
public static DateTimeZone getDataTimeZone(String collection)  {
  String timezone = TimeSpec.DEFAULT_TIMEZONE;
  try {
    DatasetConfigDTO datasetConfig;
    LoadingCache<String, DatasetConfigDTO> datasetConfigCache = CACHE_REGISTRY.getDatasetConfigCache();
    if (datasetConfigCache != null && datasetConfigCache.get(collection) != null) {
      datasetConfig = CACHE_REGISTRY.getDatasetConfigCache().get(collection);
    } else {
      datasetConfig = DAORegistry.getInstance().getDatasetConfigDAO().findByDataset(collection);
    }
    if (datasetConfig != null) {
      timezone = datasetConfig.getTimezone();
    }
  } catch (ExecutionException e) {
    LOG.error("Exception while getting dataset config for {}", collection);
  }
  return DateTimeZone.forID(timezone);
}
 
Example 6
Source File: WaveletInfo.java    From swellrt with Apache License 2.0 5 votes vote down vote up
/**
 * Initializes front-end information from the wave store, if necessary.
 * @returns true iff the wave is new = if it doesn't have any wavelet
 */
public boolean initialiseWave(WaveId waveId) throws WaveServerException {
  
  boolean isNew = false; 
  
  if(LOG.isFineLoggable()) {
    LOG.fine("frontend initialiseWave(" + waveId +")");
  }

  try {
    
    LoadingCache<WaveletId, PerWavelet> wavelets = perWavelet.getIfPresent(waveId);
    
    if (wavelets == null) {
      wavelets = perWavelet.get(waveId);
      for (WaveletId waveletId : waveletProvider.getWaveletIds(waveId)) {
        ReadableWaveletData wavelet =
            waveletProvider.getSnapshot(WaveletName.of(waveId, waveletId)).snapshot;
        // Wavelets is a computing map, so get() initializes the entry.
        PerWavelet waveletInfo = wavelets.get(waveletId);
        synchronized (waveletInfo) {
          waveletInfo.currentVersion = wavelet.getHashedVersion();
          LOG.info("frontend wavelet " + waveletId + " @" + wavelet.getHashedVersion().getVersion());
          if(LOG.isFineLoggable()) {
            LOG.fine("frontend wavelet " + waveletId + " @" + wavelet.getHashedVersion().getVersion());
          }
          waveletInfo.explicitParticipants.addAll(wavelet.getParticipants());
        }
      }
    } 
    
    if (wavelets.size() == 0)
      isNew = true;
    
  } catch (ExecutionException ex) {
    throw new RuntimeException(ex);
  }
  
  return isNew;
}
 
Example 7
Source File: SimpleHoconConfigTest.java    From kite with Apache License 2.0 5 votes vote down vote up
@Test
public void testCacheBuilder() throws ExecutionException {
  LoadingCache<String, Matcher> cache = CacheBuilder.newBuilder()
      .maximumSize(10)
      .build(
          new CacheLoader<String, Matcher>() {
            public Matcher load(String key) {
              return Pattern.compile(key).matcher("");
            }
          });
  
  Matcher m = cache.get(".*");
  Matcher m2 = cache.get(".*");
}
 
Example 8
Source File: WaveletInfo.java    From incubator-retired-wave with Apache License 2.0 5 votes vote down vote up
/**
 * Initializes front-end information from the wave store, if necessary.
 */
public void initialiseWave(WaveId waveId) throws WaveServerException {
  if(LOG.isFineLoggable()) {
    LOG.fine("frontend initialiseWave(" + waveId +")");
  }

  try {
    if (perWavelet.getIfPresent(waveId) == null) {
      LoadingCache<WaveletId, PerWavelet> wavelets = perWavelet.get(waveId);
      for (WaveletId waveletId : waveletProvider.getWaveletIds(waveId)) {
        ReadableWaveletData wavelet =
            waveletProvider.getSnapshot(WaveletName.of(waveId, waveletId)).snapshot;
        // Wavelets is a computing map, so get() initializes the entry.
        PerWavelet waveletInfo = wavelets.get(waveletId);
        synchronized (waveletInfo) {
          waveletInfo.currentVersion = wavelet.getHashedVersion();
          if(LOG.isFineLoggable()) {
            LOG.fine("frontend wavelet " + waveletId + " @" + wavelet.getHashedVersion().getVersion());
          }
          waveletInfo.explicitParticipants.addAll(wavelet.getParticipants());
        }
      }
    }
  } catch (ExecutionException ex) {
    throw new RuntimeException(ex);
  }
}
 
Example 9
Source File: CacheMetricsCollectorTest.java    From client_java with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void loadingCacheExposesMetricsForLoadsAndExceptions() throws Exception {
    CacheLoader<String, String> loader = mock(CacheLoader.class);
    when(loader.load(anyString()))
            .thenReturn("First User")
            .thenThrow(new RuntimeException("Seconds time fails"))
            .thenReturn("Third User");

    LoadingCache<String, String> cache = CacheBuilder.newBuilder().recordStats().build(loader);
    CollectorRegistry registry = new CollectorRegistry();
    CacheMetricsCollector collector = new CacheMetricsCollector().register(registry);
    collector.addCache("loadingusers", cache);

    cache.get("user1");
    cache.get("user1");
    try{
        cache.get("user2");
    } catch (Exception e) {
        // ignoring.
    }
    cache.get("user3");

    assertMetric(registry, "guava_cache_hit_total", "loadingusers", 1.0);
    assertMetric(registry, "guava_cache_miss_total", "loadingusers", 3.0);

    assertMetric(registry, "guava_cache_load_failure_total", "loadingusers", 1.0);
    assertMetric(registry, "guava_cache_loads_total", "loadingusers", 3.0);

    assertMetric(registry, "guava_cache_load_duration_seconds_count", "loadingusers", 3.0);
    assertMetricGreatThan(registry, "guava_cache_load_duration_seconds_sum", "loadingusers", 0.0);
}
 
Example 10
Source File: PhoenixStatsCacheLoaderTest.java    From phoenix with Apache License 2.0 5 votes vote down vote up
GuidePostsInfo getStats(LoadingCache<GuidePostsKey, GuidePostsInfo> cache, GuidePostsKey guidePostsKey) {
    GuidePostsInfo guidePostsInfo;
    try {
        guidePostsInfo = cache.get(guidePostsKey);
    } catch (ExecutionException e) {
        assertFalse(true);
        return GuidePostsInfo.NO_GUIDEPOST;
    }

    return guidePostsInfo;
}
 
Example 11
Source File: PinotMetadata.java    From presto with Apache License 2.0 5 votes vote down vote up
private static <K, V> V getFromCache(LoadingCache<K, V> cache, K key)
{
    V value = cache.getIfPresent(key);
    if (value != null) {
        return value;
    }
    try {
        return cache.get(key);
    }
    catch (ExecutionException e) {
        throw new PinotException(PinotErrorCode.PINOT_UNCLASSIFIED_ERROR, Optional.empty(), "Cannot fetch from cache " + key, e.getCause());
    }
}
 
Example 12
Source File: BlobStoreExpiryTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private Set<Service> getServices(Credentials creds) throws Exception {
    BlobStoreContext tmpContext = BlobStoreContextFactoryImpl.INSTANCE.newBlobStoreContext(location);
    try {
        tmpContext.getBlobStore().list();
        LoadingCache<Credentials, Access> authCache = getAuthCache(tmpContext);
        Access tmpAccess = authCache.get(creds);
        return ImmutableSet.copyOf(tmpAccess);
    } finally {
        tmpContext.close();
    }

}
 
Example 13
Source File: GuavaTest.java    From onetwo with Apache License 2.0 5 votes vote down vote up
@Test
public void testCache() throws ExecutionException{
	LoadingCache<Long, UserEntity> userCaches = CacheBuilder.newBuilder().expireAfterWrite(2, TimeUnit.SECONDS).maximumSize(400).build(new CacheLoader<Long, UserEntity>(){

		@Override
		public UserEntity load(Long key) throws Exception {
			UserEntity user = new UserEntity();
			System.out.println("new user: " + key);
			user.setId(key);
			return user;
		}
		
	});

	UserEntity user1 = userCaches.get(1L);
	UserEntity user2 = userCaches.get(1L);
	Assert.assertNotNull(user1);
	Assert.assertNotNull(user2);
	Assert.assertTrue(user1==user2);

	LangUtils.await(3);
	user2 = userCaches.get(1L);
	Assert.assertNotNull(user1);
	Assert.assertNotNull(user2);
	Assert.assertTrue(user1!=user2);
	Assert.assertEquals(user1.getId(), user2.getId());
}
 
Example 14
Source File: Relatedness.java    From entity-fishing with Apache License 2.0 5 votes vote down vote up
/**
 * Calculate the relatedness between two articles
 */
public double getRelatedness(Article art1, Article art2, String lang) throws ExecutionException{
	comparisonsRequested++;

	LoadingCache<ArticlePair, Double> relatednessCache = caches.get(lang);
	return relatednessCache.get(new ArticlePair(art1,art2));
}
 
Example 15
Source File: GlobalCache.java    From meghanada-server with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("try")
public Source getSource(final File file) throws ExecutionException {

  try (TelemetryUtils.ScopedSpan scope =
      TelemetryUtils.startScopedSpan("GlobalCache.getSource")) {

    TelemetryUtils.ScopedSpan.addAnnotation(
        TelemetryUtils.annotationBuilder().put("file", file.getPath()).build("args"));

    final LoadingCache<File, Source> sourceCache = this.getSourceCache();
    return sourceCache.get(file);
  }
}
 
Example 16
Source File: GuavaCache9.java    From blog with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static void main(String[] args) throws ExecutionException {
	CacheLoader<String, String> loader = new CacheLoader<String, String>() {
		public String load(String key) throws Exception {
			Thread.sleep(1000); // 休眠1s,模拟加载数据
			System.out.println(key + " is loaded from a cacheLoader!");
			return key + "'s value";
		}
	};

	LoadingCache<String, String> loadingCache = CacheBuilder.newBuilder().maximumSize(3).build(loader);// 在构建时指定自动加载器

	loadingCache.get("key1");
	loadingCache.get("key2");
	loadingCache.get("key3");
}
 
Example 17
Source File: LoadingCacheHelper.java    From spring-microservice-exam with MIT License 5 votes vote down vote up
/**
 * 从指定的loadingCache里获取内容
 * @param clazz clazz
 * @param key key
 * @param <K> key
 * @param <V> value
 * @return value,没有对应的key或获取异常则返回null
 */
@SuppressWarnings("unchecked")
public <K, V> V get(Class<? extends CacheLoader<K, V>> clazz, K key) {
	LoadingCache<K, V> cache = this.loadingCacheMap.get(clazz.getSimpleName());
	if (cache != null) {
		try {
			return cache.get(key);
		} catch (Exception e) {
			log.error("Get from loadingCache error, {}, {}, {}", clazz, key, e.getMessage(), e);
		}
	}
	return null;
}