Skip to content

Commit 249ddec

Browse files
edalquistchingor13
authored andcommitted
Remove blocking ClassInfo.of (#643)
* Remove blocking ClassInfo.of Replaces blocking logic in ClassInfo.of with ConcurrentMap.computeIfAbsent. Also removes WeakHashMap as it wasn't actually doing the intended operation. The ClassInfo value has a strong reference to the Class which prevents the weak key reference from ever being collected. * Remove dependency on JDK8 API computeIfAbsent isn't available in all supported environments. Replace with the same logic as the default computeIfAbsent implementation.
1 parent 1c68403 commit 249ddec

File tree

1 file changed

+15
-14
lines changed
  • google-http-client/src/main/java/com/google/api/client/util

1 file changed

+15
-14
lines changed

google-http-client/src/main/java/com/google/api/client/util/ClassInfo.java

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,8 @@
2424
import java.util.Locale;
2525
import java.util.Map;
2626
import java.util.TreeSet;
27-
import java.util.WeakHashMap;
27+
import java.util.concurrent.ConcurrentHashMap;
28+
import java.util.concurrent.ConcurrentMap;
2829

2930
/**
3031
* Computes class information to determine data key name/value pairs associated with the class.
@@ -37,11 +38,12 @@
3738
public final class ClassInfo {
3839

3940
/** Class information cache, with case-sensitive field names. */
40-
private static final Map<Class<?>, ClassInfo> CACHE = new WeakHashMap<Class<?>, ClassInfo>();
41+
private static final ConcurrentMap<Class<?>, ClassInfo> CACHE =
42+
new ConcurrentHashMap<Class<?>, ClassInfo>();
4143

4244
/** Class information cache, with case-insensitive fields names. */
43-
private static final Map<Class<?>, ClassInfo> CACHE_IGNORE_CASE =
44-
new WeakHashMap<Class<?>, ClassInfo>();
45+
private static final ConcurrentMap<Class<?>, ClassInfo> CACHE_IGNORE_CASE =
46+
new ConcurrentHashMap<Class<?>, ClassInfo>();
4547

4648
/** Class. */
4749
private final Class<?> clazz;
@@ -81,16 +83,15 @@ public static ClassInfo of(Class<?> underlyingClass, boolean ignoreCase) {
8183
if (underlyingClass == null) {
8284
return null;
8385
}
84-
final Map<Class<?>, ClassInfo> cache = ignoreCase ? CACHE_IGNORE_CASE : CACHE;
85-
ClassInfo classInfo;
86-
synchronized (cache) {
87-
classInfo = cache.get(underlyingClass);
88-
if (classInfo == null) {
89-
classInfo = new ClassInfo(underlyingClass, ignoreCase);
90-
cache.put(underlyingClass, classInfo);
91-
}
92-
}
93-
return classInfo;
86+
final ConcurrentMap<Class<?>, ClassInfo> cache = ignoreCase ? CACHE_IGNORE_CASE : CACHE;
87+
88+
// Logic copied from ConcurrentMap.computeIfAbsent
89+
ClassInfo v, newValue;
90+
return ((v = cache.get(underlyingClass)) == null
91+
&& (newValue = new ClassInfo(underlyingClass, ignoreCase)) != null
92+
&& (v = cache.putIfAbsent(underlyingClass, newValue)) == null)
93+
? newValue
94+
: v;
9495
}
9596

9697
/**

0 commit comments

Comments
 (0)