java - 对 AtomicReference 持有的对象执行 equals 和 hashcode 的正确方法

标签 java multithreading

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/

相关文章:

java - 将缓存的 Map<String , List> 对象复制到临时 Map<String , List> 对象中

multithreading - 为什么这个小的 c++11 多线程程序会出现段错误

C# Bruteforce - 多线程处理固定长度的密码

多线程可以和事件编程结合起来吗?

java - 八皇后数组越界 (Java)

java - 为伪装的 URL 地址抛出新的异常

java - 如何修复 GridBagLayout 按钮大小

java - 正则表达式在坐标数据上出现故障

multithreading - 核心数据 : warning: Unable to load class named

windows - 指示 win32 线程在单个处理器内核上运行