new一个对象竟然不是原子操作?

4 篇文章 0 订阅

那时你怎么说
你说对我的牵挂一朵朵
尤其是在犯困的夏日午后
那时你怎么说
你说大雨都是乌云在解脱
叫我赶紧回家钻进被窝

首先需要肯定的是:new操作不是原子操作!

public class Demo2 {
    public static void main(String[] args) {
        Demo2 demo2 = new Demo2();
    }
}

直接看main方法的字节码
在这里插入图片描述
重点4行字节码

0 new #2 <work/Demo2>
3 dup
4 invokespecial #3 <work/Demo2.<init>>
7 astore_1

new—创建一个对象,并将其引用值压入栈顶。

在这里插入图片描述

dup—复制栈顶一个字长的数据,将复制后的数据压栈。

在这里插入图片描述

invokespecial—编译时方法绑定调用方法。

也就是进行对象的初始化,调用构造方法
在这里插入图片描述

0 aload_0
1 invokespecial #1 <java/lang/Object.<init>>
4 return

aload_0—从局部变量0中装载引用类型值入栈,其实就是this操作
每个非静态方法,局部变量表index=0的位置永远存放的都是this

mian方法会弹出栈顶元素作为this对象
在这里插入图片描述
astore_1—将栈顶引用类型值保存到局部变量1中。

哪个是局部变量1?
在这里插入图片描述
在这里插入图片描述
完成变量demo2赋值操作

总结

new一个对象看起来是一行代码,但在内部实际性进行了4步操作,是非原子性的。

这也是为什么DCL双重检查需要volitile禁止指令重排序

文章持续更新,可以微信搜索「 绅堂Style 」第一时间阅读,回复【资料】有我准备的面试题笔记。
GitHub https://github.com/dtt11111/Nodes 有总结面试完整考点、资料以及我的系列文章。欢迎Star。
在这里插入图片描述

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
在C++中,std::atomic<std::string>可以用来实现对std::string类型的原子操作。 使用std::atomic<std::string>时,需要注意以下几点: 1. 必须使用默认构造函数来初始化std::atomic<std::string>对象。 2. 对于std::string类型的原子操作,只能使用std::atomic<std::string>提供的一些特殊的操作函数,如load(), store(), exchange()等。 3. 由于std::string类型是动态分配的,所以需要使用std::shared_ptr<std::string>来进行管理。 下面是一个简单的示例代码,展示了如何使用std::atomic<std::string>实现对std::string类型的原子操作: ```c++ #include <iostream> #include <thread> #include <atomic> #include <string> #include <memory> std::atomic<std::shared_ptr<std::string>> atomic_str; void write_thread() { std::shared_ptr<std::string> new_str(new std::string("Hello")); atomic_str.store(new_str); } void read_thread() { std::shared_ptr<std::string> str_ptr = atomic_str.load(); std::cout << *str_ptr << std::endl; } int main() { std::thread t1(write_thread); std::thread t2(read_thread); t1.join(); t2.join(); return 0; } ``` 在上面的示例中,我们使用了std::atomic<std::shared_ptr<std::string>>来实现对std::string类型的原子操作。在write_thread()函数中,我们创建了一个新的std::string对象,并将其包装在std::shared_ptr中。然后,我们使用std::atomic<std::shared_ptr<std::string>>的store()函数将其存储到atomic_str对象中。 在read_thread()函数中,我们使用std::atomic<std::shared_ptr<std::string>>的load()函数获取atomic_str对象中存储的std::shared_ptr<std::string>指针,并通过该指针访问std::string对象。 值得注意的是,由于std::string类型是动态分配的,所以我们需要使用std::shared_ptr<std::string>来进行管理。这可以确保在多个线程之间安全地共享std::string对象
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值