【发布时间】:2019-11-13 06:31:53
【问题描述】:
我在我的应用程序中看到了这个遗留代码,它导致线程在生产中的 synchronized 方法上被阻塞。
private synchronized void productMapBuilder(List<Product> products) {
Map<String, Set<Product>> map = new HashMap<>();
for (Product product : products) {
map.putAll(buildProductMap(product));// this call another method which isn't synchronised.
}
this.productsMap = map;
}
现在,List<product> products 被传递给这个productMapBuilder,我知道它是一个线程特定的,线程之间唯一的共享变量是productsMap。
那么我们真的需要将synchronized 放在整个方法上吗?
我也想不出任何其他方法来优化这个方法,因为我不是并发程序方面的专家,因此欢迎任何有价值的资源和建议:)
【问题讨论】:
-
Map<String, Set<Product>> productsMap = new HashMap<>();不在线程之间共享。它总是在调用此方法时创建。 -
如果 productsMap 是跨线程共享的,您可以尝试使用 ConcurrentHashMap,但从 sn-p 来看,它看起来不像是共享的。此外,如果 buildProductMap 是线程安全的,则可以在同步范围之外进行重构。
-
@VikramSingh,很抱歉造成混淆,但如果您注意到它已分配给同名变量
this.productsMap= = productsMap并且当我提到共享时,我的意思是this.productsMap -
重命名变量名以避免混淆。
-
这是否可以改变取决于更多的代码。是否有其他方法可以在同一个锁上同步?
this.productsMap是如何使用的?等等。
标签: java concurrency synchronized