AtomicReference
不适用于 Objects.equals()
和 Objects.hash()
。
AtomicReference<String> ref1 = new AtomicReference<>("hi");
AtomicReference<String> ref2 = new AtomicReference<>("hi");
System.out.println(Objects.equals(ref1, ref2)); //false
System.out.println(Objects.equals(ref1.get(), ref2.get())); //true but potentially not thread safe
System.out.println(Objects.hash(ref1) == Objects.hash(ref2)); //false
System.out.println(Objects.hash(ref1.get()) == Objects.hash(ref2.get())); //true but potentially not thread safe
检查 AtomicReference
持有的两个对象是否相等并以既有效又线程安全的方式计算相同哈希的最佳方法是什么?
最佳答案
What's the best way to check if two [variables]...are equal...in a way that both works and is thread safe?
这个问题没有任何意义。假设您有线程 A 想要测试变量,线程 B 可以随时更改其中一个变量而不发出警告。
您想知道变量是否相等吗?好吧,然后呢?如果您的“线程安全”相等性测试表明它们相等,那么在您执行相等性测试和对信息执行某些操作之间,什么会阻止线程 B 更改其中任何一个。
知道两个变量在某个时刻是否相等是没有任何值(value)的:您想知道当程序处于某种特定状态时变量是否相等,然后您想要执行以下操作在状态改变之前发生一些事情。
所以,是的,您需要在锁对象上同步
,但这不仅仅是为了保护相等测试。它必须防止程序在您测试变量的整个过程中更改您关心的状态,然后根据测试结果执行某些操作。
关于java - 对 AtomicReference 持有的对象执行 equals 和 hashcode 的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53884445/