给您tl; dr:AtomicReference具有更多功能,但使用额外的内存来提供该功能,我个人认为,如果您不关心内存,请继续使用AtomicReference,它更具可读性,并且您不知道何时会发现自己需要其他功能A bit confused about the usage of ConcurrentHashSets in DTOs.This DTO is accessed by many threads at a time.First Case public class LogDTO { private Set<String> person = ConcurrentHashMap.newKeySet(); public void setPerson(Set<String> person) { this.person = person; } public Set<String> getPerson() { return this.person; } }Does this give Thread Safety?Second Case public class LogDTO { private volatile Set<String> person; public void setPerson(Set<String> person) { this.person = person; } public Set<String> getPerson() { return this.person; } }or do I have to use AtomicReference?Third Case public class LogDTO { private AtomicReference<Set<String>> ref = new AtAtomicReference<>(); public void setPerson(Set<String> person) { this.ref.set(person); } public Set<String> getPerson() { return this.ref.get(); } }If to populate an entirely new HashSet then assigning it to the existing variable, then is it better to use volatile? 解决方案 First Caseit is not thread safe, ConcurrentHashMap only provides thread safety when working with the HashMap api meaning adding and removing things from the HashMap. it does not provide thread safety when changing the reference to the HashMap, if you think of it, changing the reference to the HashMap has no connection to how the HashMap is implemented.Second and Third casesThose cases are thread safe, in those cases you changed the way assigning and retrieving the HashMap reference is implemented to allow thread safety.in regards to whether to use volatile or AtomicReference you can read thisto give you the tl;dr:AtomicReference has more functionality but uses additional memory to provide that functionality, my personal opinion is that if you are not that concerned with memory go ahead and use AtomicReference it is more readable and you dont't know when you will find your self needing additional functionality. 这篇关于使用ConcurrentHashSet时的线程安全引用分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-03 21:23