Allow cache size to be configured.

This commit is contained in:
Joel Leitch 2010-05-19 20:47:27 +00:00
parent 2610a2920d
commit 9c7bfc677a
3 changed files with 29 additions and 7 deletions

View File

@ -134,7 +134,7 @@
</workspaceCodeStylesURL>
</configuration>
</plugin>
<!-- plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>javacc-maven-plugin</artifactId>
<executions>
@ -157,7 +157,7 @@
<version>4.2</version>
</dependency>
</dependencies>
</plugin-->
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jxr-plugin</artifactId>

View File

@ -34,9 +34,11 @@ import java.util.Collections;
* @since 1.4
*/
public final class FieldAttributes {
// TODO(Joel): Fix how we configure this cache in a follow-up CL.
private static final String MAX_CACHE_PROPERTY_NAME =
"com.google.gson.annotation_cache_size_hint";
private static final Cache<Pair<Class<?>, String>, Collection<Annotation>> ANNOTATION_CACHE =
new LruCache<Pair<Class<?>,String>, Collection<Annotation>>(1500);
new LruCache<Pair<Class<?>,String>, Collection<Annotation>>(getMaxCacheSize());
private final Class<?> parentClazz;
private final Field field;
@ -64,6 +66,17 @@ public final class FieldAttributes {
field = f;
}
private static int getMaxCacheSize() {
final int defaultMaxCacheSize = 2000;
try {
String propertyValue = System.getProperty(
MAX_CACHE_PROPERTY_NAME, String.valueOf(defaultMaxCacheSize));
return Integer.parseInt(propertyValue);
} catch (NumberFormatException e) {
return defaultMaxCacheSize;
}
}
/**
* @return the name of the field
*/

View File

@ -53,21 +53,30 @@ public class LruCacheTest extends TestCase {
}
public void testCacheEviction() throws Exception {
Cache<String, Integer> cache = new LruCache<String, Integer>(3);
Cache<String, Integer> cache = new LruCache<String, Integer>(5);
cache.addElement("key1", 1);
cache.addElement("key2", 2);
cache.addElement("key3", 3);
cache.addElement("key4", 4);
cache.addElement("key5", 5);
assertEquals(1, cache.getElement("key1").intValue());
assertEquals(2, cache.getElement("key2").intValue());
assertEquals(3, cache.getElement("key3").intValue());
assertEquals(4, cache.getElement("key4").intValue());
assertEquals(5, cache.getElement("key5").intValue());
// Access key1 to show key2 will be evicted (shows not a FIFO cache)
cache.getElement("key1");
cache.addElement("key4", 4);
cache.getElement("key3");
cache.addElement("key6", 6);
cache.addElement("key7", 7);
assertEquals(1, cache.getElement("key1").intValue());
assertNull(cache.getElement("key2"));
assertEquals(3, cache.getElement("key3").intValue());
assertEquals(4, cache.getElement("key4").intValue());
assertNull(cache.getElement("key4"));
assertEquals(5, cache.getElement("key5").intValue());
assertEquals(6, cache.getElement("key6").intValue());
assertEquals(7, cache.getElement("key7").intValue());
}
}