Skip to content

Commit b94345c

Browse files
committed
optimize typetoken performance
1 parent 4453a3f commit b94345c

1 file changed

Lines changed: 12 additions & 2 deletions

File tree

sdk/src/main/java/software/amazon/lambda/durable/TypeToken.java

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,9 @@
44

55
import java.lang.reflect.ParameterizedType;
66
import java.lang.reflect.Type;
7+
import java.util.Collections;
8+
import java.util.Map;
9+
import java.util.WeakHashMap;
710

811
/**
912
* Framework-agnostic type token for capturing generic type information at runtime.
@@ -26,6 +29,9 @@
2629
* @param <T> the type being captured
2730
*/
2831
public abstract class TypeToken<T> {
32+
// cache for types
33+
private static final Map<Type, Type> TYPE_CACHE = Collections.synchronizedMap(new WeakHashMap<>());
34+
2935
private final Type type;
3036

3137
/**
@@ -35,9 +41,13 @@ public abstract class TypeToken<T> {
3541
* @throws IllegalStateException if created without a type parameter
3642
*/
3743
protected TypeToken() {
38-
Type superClass = getClass().getGenericSuperclass();
44+
this.type = TYPE_CACHE.computeIfAbsent(getClass(), k -> resolveType(getClass()));
45+
}
46+
47+
private static Type resolveType(Class<?> aClass) {
48+
Type superClass = aClass.getGenericSuperclass();
3949
if (superClass instanceof ParameterizedType) {
40-
this.type = ((ParameterizedType) superClass).getActualTypeArguments()[0];
50+
return ((ParameterizedType) superClass).getActualTypeArguments()[0];
4151
} else {
4252
throw new IllegalStateException("TypeToken must be created as an anonymous subclass with a type parameter. "
4353
+ "Example: new TypeToken<List<String>>() {}");

0 commit comments

Comments
 (0)