Skip to content

Commit

Permalink
Make the FieldQueryMapEncoder encoder thread safe
Browse files Browse the repository at this point in the history
Change the caching map to be concurrent and only
insert items that are missing to the map.
Fixes #1257
  • Loading branch information
Budlee committed Feb 27, 2021
1 parent ee8d517 commit 002e660
Showing 1 changed file with 14 additions and 16 deletions.
30 changes: 14 additions & 16 deletions core/src/main/java/feign/querymap/FieldQueryMapEncoder.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/**
* Copyright 2012-2020 The Feign Authors
* Copyright 2012-2021 The Feign Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
Expand All @@ -13,12 +13,17 @@
*/
package feign.querymap;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import feign.Param;
import feign.QueryMapEncoder;
import feign.codec.EncodeException;
import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;

/**
* the query map will be generated using member variable names as query parameter names.
Expand All @@ -31,13 +36,15 @@
public class FieldQueryMapEncoder implements QueryMapEncoder {

private final Map<Class<?>, ObjectParamMetadata> classToMetadata =
new HashMap<Class<?>, ObjectParamMetadata>();
new ConcurrentHashMap<>();

@Override
public Map<String, Object> encode(Object object) throws EncodeException {
ObjectParamMetadata metadata =
classToMetadata.computeIfAbsent(object.getClass(), ObjectParamMetadata::parseObjectType);
Map<String, Object> fieldNameToValue = new HashMap<>();

try {
ObjectParamMetadata metadata = getMetadata(object.getClass());
Map<String, Object> fieldNameToValue = new HashMap<String, Object>();
for (Field field : metadata.objectFields) {
Object value = field.get(object);
if (value != null && value != object) {
Expand All @@ -52,15 +59,6 @@ public Map<String, Object> encode(Object object) throws EncodeException {
}
}

private ObjectParamMetadata getMetadata(Class<?> objectType) {
ObjectParamMetadata metadata = classToMetadata.get(objectType);
if (metadata == null) {
metadata = ObjectParamMetadata.parseObjectType(objectType);
classToMetadata.put(objectType, metadata);
}
return metadata;
}

private static class ObjectParamMetadata {

private final List<Field> objectFields;
Expand Down

0 comments on commit 002e660

Please sign in to comment.