GuardedBy 和 ConcurrentHashMap

huangapple go评论51阅读模式
英文:

GuardedBy and concurrentHashMap

问题

I saw a code snippets like below:

@GuardedBy("this") private final Map<Id, Supplier<List<Predicate>>> filters = new ConcurrentHashMap<>();

My question is like since this object (filters) is already being guarded, could I just use HashMap instead of ConcurrentHashMap?

Thank you.

英文:

I saw a code snippets like below:

@GuardedBy(&quot;this&quot;)
private final Map&lt;Id, Supplier&lt;List&lt;Predicate&gt;&gt;&gt; filters = new ConcurrentHashMap&lt;&gt;();

My question is like since this object (filters) is already being guarded, could I just use HashMap instead of ConcurrentHashMap?

Thank you.

答案1

得分: 2

@GuardedBy("this") 是我记得的一个自定义注解,它的使用被建议在Brian Goetz的《Java并发编程实战》中(强烈推荐阅读这本书!)或者可能是这个注解中,它并不是标准的JDK注解。因此,它只能被视为对程序员的提示,即用于保护可以从多个线程访问的字段的锁对象是什么,或者换句话说,它是一个标记注解。

简而言之 - 不,你不能这样做。如果你希望对过滤器的访问是线程安全的,请保留ConcurrentHashMap。@GuardedBy注解不会使对字段的访问同步,它只是帮助你理解代码。

英文:

@GuardedBy(&quot;this&quot;) is, as far as I recall, a custom annotation, which usage was advised in Java Concurrency in Practice by Brian Goetz (highly recommend reading theh book!), or possibly this annotation and it's not a standard JDK annotation. Thus, it can be only treated as a hint to the programmer, what is the lock object which guards the field which can be accessed from multiple thread, or to put it another way a marker annotation.

TL;DR - no, you cannot. If you want the access to the filters to be thread safe, leave the ConcurrentHashMap. The @GuardedBy annotation does not makes the access to the field synchronized, it just helps you understand the code.

huangapple
  • 本文由 发表于 2020年7月23日 05:01:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/63043132.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定