英文:
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("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.
答案1
得分: 2
@GuardedBy("this")
是我记得的一个自定义注解,它的使用被建议在Brian Goetz的《Java并发编程实战》中(强烈推荐阅读这本书!)或者可能是这个注解中,它并不是标准的JDK注解。因此,它只能被视为对程序员的提示,即用于保护可以从多个线程访问的字段的锁对象是什么,或者换句话说,它是一个标记注解。
简而言之 - 不,你不能这样做。如果你希望对过滤器的访问是线程安全的,请保留ConcurrentHashMap。@GuardedBy注解不会使对字段的访问同步,它只是帮助你理解代码。
英文:
@GuardedBy("this")
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论