gpt4 book ai didi

java - 创建新对象是否有助于防止静态方法内的并发问题?

转载 作者:行者123 更新时间:2023-12-02 10:33:09 24 4
gpt4 key购买 nike

我有一个接受 OkHttp#response 的方法:

public static Map<String, Object> getResponseBody(Response response) throws IOException {
return new ObjectMapper()
.readValue(response.body().string(),
new TypeReference<Map<String, Object>>() {
});
}

据我了解,如果多个类使用 getResponseBody,我将遇到大问题,因为它们都将访问相同的 Response

这样做可以解决吗?:

public static Map<String, Object> getResponseBody(Response response) throws IOException {
ResponseBody responseBody = response.body();
String responseString = responseBody.string();
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map = mapper
.readValue(responseString,
new TypeReference<Map<String, Object>>() {
});
return map;
}

最佳答案

正如评论中提到的,

tl;dr:我提供的第一个代码始终是线程安全的。

Every thread that calls the getResponseBody method will provide a thread local Response instance. There is no shared static resource needing synchronization here. It looks thread safe.

Local variables are not shared between threads for non-static and static methods. What they reference could be.

The second method does the same thing as the first method, but with named variables for some of the values. It doesn't change it's behaviour.

关于java - 创建新对象是否有助于防止静态方法内的并发问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53490877/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com