001// *************************************************************************************************************************** 002// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file * 003// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file * 004// * to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance * 005// * with the License. You may obtain a copy of the License at * 006// * * 007// * http://www.apache.org/licenses/LICENSE-2.0 * 008// * * 009// * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an * 010// * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * 011// * specific language governing permissions and limitations under the License. * 012// *************************************************************************************************************************** 013package org.apache.juneau.internal; 014 015import java.util.concurrent.*; 016 017/** 018 * Simple in-memory cache of objects. 019 * 020 * <p> 021 * Essentially just a wrapper around a ConcurrentHashMap. 022 * 023 * @param <K> The key type. 024 * @param <V> The value type. 025 */ 026public class Cache<K,V> { 027 private final boolean nocache; 028 private final int maxSize; 029 private final ConcurrentHashMap<K,V> cache; 030 031 /** 032 * Constructor. 033 * 034 * @param disabled If <jk>true</jk> then the cache is disabled. 035 * @param maxSize The maximum size of the cache. If this threshold is reached, the cache is flushed. 036 */ 037 public Cache(boolean disabled, int maxSize) { 038 this.nocache = disabled; 039 this.maxSize = maxSize; 040 if (! nocache) 041 cache = new ConcurrentHashMap<>(); 042 else 043 cache = null; 044 } 045 046 /** 047 * Retrieves the value with the specified key from this cache. 048 * 049 * @param key The key. 050 * @return The value, or <jk>null</jk> if the value is not in the cache, or the cache is disabled. 051 */ 052 public V get(K key) { 053 if (nocache || key == null) 054 return null; 055 return cache.get(key); 056 } 057 058 /** 059 * Adds the value with the specified key to this cache. 060 * 061 * @param key The key. 062 * @param value The value. 063 * @return 064 * Either the value already in the cache if it already exists, or the same value passed in. 065 * Always returns the same value if the cache is disabled. 066 */ 067 public V put(K key, V value) { 068 if (nocache || key == null) 069 return value; 070 071 // Prevent OOM in case of DDOS 072 if (cache.size() > maxSize) 073 cache.clear(); 074 075 while (true) { 076 V v = cache.get(key); 077 if (v != null) 078 return v; 079 cache.putIfAbsent(key, value); 080 return value; 081 } 082 } 083}