Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make StringConverter threadsafe #3157

Merged
merged 1 commit into from
Mar 11, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.matsim.utils.objectattributes.AttributeConverter;

Expand All @@ -29,7 +30,7 @@
* @author mrieser
*/
public class StringConverter implements AttributeConverter<String> {
private final Map<String, String> stringCache = new HashMap<String, String>(1000);
private final Map<String, String> stringCache = new ConcurrentHashMap<>(1000);
@Override
public String convert(String value) {
String s = this.stringCache.get(value);
Copy link
Member

@Janekdererste Janekdererste Mar 12, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With ConcurrentHashMap you also have to change the insertion logic, as you might have a race condition here, with two processes getting a null value at the same time and then updating the cache. You could use:

return map.computeIfAbsent(value, k -> k);

Expand All @@ -44,4 +45,4 @@ public String convert(String value) {
public String convertToString(Object o) {
return (String) o;
}
}
}
Loading